我是vba excel的新手。
我有这张纸 Sheet1 :
我想在其他工作表( Sheet2 )中复制第一张工作表的数据,但要问 Sheet1 的特定数字,问我是指列A的数字,可以将其捕获为单元格范围,也可以将其写入代码中。我所拥有的是非常原始的,它实际上是这样复制的:
Sub planilla()
Sheets("Sheet1").Range("A1:B14").Copy
Sheets("Sheet2").Select
Range("A2").PasteSpecial xlPasteValues
End Sub
单击我拥有的按钮时将使用前面的代码,例如,如果大小写为1,则我希望将其复制到 Sheet2 中:
当案例是2或5时,我不希望它从单元格 A:2 开始,我需要它从单元格 A:10 开始>,例如,如果案例为1,然后为5,则结果应如下所示:
并非在所有情况下,起始范围都是相同的,例如,如果我尝试使用数字2和5,则5的起始单元格将是 A:4 ,这是唯一的单元格常数确定为 A:2 。
答案 0 :(得分:1)
这可能是您的起点。
您可以将范围构建为:
Range(A1:D1) -> Range(Cells(A1), Cells(D1)) ->
Range(Cells(row number, column number), Cells(row number, column number)) ->
Range(Cells(1, 1), Cells(1, 4))
按F8键在代码中一行一行地查看每一行会发生什么。
VBA代码:
Sub CopyValues()
Dim ws1 As Worksheet
Set ws1 = ActiveWorkbook.Worksheets("Sheet1") 'Set the name of worksheet "Sheet1"
Dim ws2 As Worksheet
Set ws2 = ActiveWorkbook.Worksheets("Sheet2") 'Set the name of worksheet "Sheet2"
Dim lrow As Long
Dim lrow2 As Long
Dim Number As Variant
Dim i As Long
lrow = ws1.Cells(Rows.Count, 1).End(xlUp).Row 'Find the last row in Sheet1
lrow2 = ws2.Cells(Rows.Count, 1).End(xlUp).Row 'Find the last row in Sheet2
Number = Application.InputBox(Prompt:="Enter a number", Type:=1) 'Input box where you write which number to copy from column A
'Number = 2
For i = 1 To lrow 'Loop through column A, from row 1 to lastrow
If ws1.Cells(i, 1).Value = Number Then 'If cell value in column A is equal to your number then...
ws2.Cells(lrow2 + 1, 1).Value = ws1.Cells(i, 1).Value 'Then copy the current row from Column A to the other sheet, first empty row in column A,
ws2.Cells(lrow2 + 1, 2).Value = ws1.Cells(i, 2).Value 'Then copy the current row from Column B to the other sheet, in column B,
lrow2 = lrow2 + 1 'Add one incremental to the last row.
End If
Next i 'Go to next row number
End Sub