我是VBA的新手。 我的excel下有2张:“数据”,“Sheet1”。数据表每天都会修改。 我想将vlookup VBA宏用于添加到Sheet1中的A列的行。但是我的代码没有给我任何结果(如果我在相同的工作表下运行宏,它可以工作)。谢谢
Private Sub CommandButton21_Click()
On Error Resume Next
Sheet1.Range("B3:D500").Clear
Dim Dept_Row As Long
Dim Dept_Clm As Long
Table1 = Sheet1.Range("A3:A50")
Table2 = Data.Range("A3:H24")
Dept_Row = Sheet1.Range("B3").Row
Dept_Clm1 = Sheet1.Range("B3").Column
Dept_Clm2 = Sheet1.Range("C3").Column
Dept_Clm3 = Sheet1.Range("D3").Column
For Each cl In Table1
Sheet1.Cells(Dept_Row, Dept_Clm1) = Application.WorksheetFunction.VLookup(cl, Table2, 6, False)
Sheet1.Cells(Dept_Row, Dept_Clm2) = Application.WorksheetFunction.VLookup(cl, Table2, 7, False)
Sheet1.Cells(Dept_Row, Dept_Clm3) = Application.WorksheetFunction.VLookup(cl, Table2, 8, False)
Dept_Row = Dept_Row + 1
Next cl
MsgBox "Done"
End Sub
答案 0 :(得分:0)
如果您要对解决方案进行编码,那么最好将工作表标注为:
Dim sWS as worksheet 'Source worksheet
dim tWS as worksheet 'Target worksheet
dim aCell as range
with thisworkbook
set sws = .sheets("Data")
set tws = .sheets("Sheet1")
end with
for each acell in sws.range("A3:A50")
with tws
.cells(Dept_Row, Dept_Clm1).value = application....
'also check out the offset function for fetching values in cells to the left or right of the cell you are looping down through.
end with
next acell
或者,查看匹配,索引和间接公式,了解如何将数据从一个工作表传输到另一个工作表。这三个函数比vLookup更有效和准确,特别是如果您将三个单元格从一个工作表传输到另一个工作表。