d12*_*123 5 vba microsoft-excel
我正在尝试创建一个按钮,以B5使用来自另一个工作表单元格的信息自动填充单元格A1:A10。
当按下按钮时,我想B5包含来自 cell 的信息A1。然后,当再次按下按钮时,它应该包含来自A2等等的信息。
这是简短的简单方法。
您将需要一个计数器,以便在每次按下按钮时递增。您需要将其放在电子表格中的某个位置,在本例中,它位于按钮下方。
代码
Sub Button1_Click()
Dim CopySheet As Worksheet, PasteSheet As Worksheet
Dim xFrom As Integer, xTo As Integer, i As Integer
Dim pasteCell As String, cCell As String
'Sheets
Set CopySheet = Worksheets("Sheet2") 'Sheet you are copying from.
Set PasteSheet = Worksheets("Sheet1") 'Sheet you are pasting into.
'Rows, range of rows start from row rStart to rEnd
rStart = 1 'Start of Row you want to copy from.
rEnd = 10 'End of Row you want to copy from.
'Cells
pasteCell = "B5" 'Cell we will paste data from CopySheet.
'Counter will increments with each button press.
cCell = "E5" 'Change "E5" to reference cell on your spreadsheet.
i = Range(cCell).Value
Application.ScreenUpdating = False 'We disable Screen Updating to prevent interruption.
'Update Counter
i = i + 1
If (i > rEnd) Then
i = rStart
End If
Range(cCell).Value = i
'Copy/Paste Functions
CopySheet.Select
Range("A" & i).Select
Selection.Copy
PasteSheet.Select
Range(pasteCell).Select
ActiveSheet.Paste
Application.ScreenUpdating = True 'Enable Screen Updating at end of operation.
End Sub
Run Code Online (Sandbox Code Playgroud)
该按钮将根据计数器编号加 1 进行复制,因此如果按钮上的数字为 0,则宏将添加获取 0 + 1,然后开始复制和粘贴功能。