为VLOOKUP代码定义variables

一直试图运行一个示例代码,但无法这样做。 最可能是因为我没有正确定义variables(表1&2和Cl)。任何人都可以帮助我纠正它,所以我有一个更好的想法,我将来应该怎么做?非常感谢。 这是代码

Option Explicit Sub ADDCLM() On Error Resume Next Dim Dept_Row As Long Dim Dept_Clm As Long Dim Table1 As Range Dim Table2 As Range Dim cl As Variant Table1 = Sheet1.Range("A3:A13") ' Employee_ID Column from Employee table Table2 = Sheet1.Range("H3:I13") ' Range of Employee Table 1 Dept_Row = Sheet1.Range("E3").Row ' Change E3 with the cell from where you need to start populating the Department Dept_Clm = Sheet1.Range("E3").Column For Each cl In Table1 Sheet1.Cells(Dept_Row, Dept_Clm) = Application.WorksheetFunction.VLookup(cl, Table2, 2, False) Dept_Row = Dept_Row + 1 Next cl MsgBox "Done" End Sub 

你不仅没有正确设置范围(正如KS Sheon已经指出的那样),而且你也使用了无效的引用: Sheet1应该被replace为Worksheets("Sheet1")

此外,代码可以简化如下

 Option Explicit Sub ADDCLM() Worksheets("Sheet1").Range("E3:E13").FormulaR1C1 = "=Vlookup(RC1,R3C8:R13C9,2,False)" MsgBox "Done" End Sub 

或者,如果只想在E3:E13中保留值

 Option Explicit Sub ADDCLM2() With Worksheets("Sheet1").Range("E3:E13") .FormulaR1C1 = "=Vlookup(RC1,R3C8:R13C9,2,False)" .Value = .Value End With MsgBox "Done" End Sub 

table1和table2被声明为范围“对象”。 为一个“对象”赋值你必须使用set ,即

 set Table1 = Sheet1.Range("A3:A13")` set Table2 = Sheet1.Range("H3:I13") 

你不需要为Dept_Row和Dept_clm使用set ,因为它们只被赋值为“value”。

cl应该声明为range,因为你正在调用For Each cl In Table1

HTH。

下面的代码应该适合你。 唯一需要的更改是将Table1和Table2更新为Varianttypes或在Table1和Table2之前使用Set。 这是在以下Application.WorksheetFunction.VLookupexpression式的语法中定义的。

 'Option 1 Declare Tables as vaiants Option Explicit Sub ADDCLM() On Error Resume Next Dim Dept_Row As Long Dim Dept_Clm As Long Dim Table1 As Variant Dim Table2 As Variant Dim cl As Variant Table1 = Sheet1.Range("A3:A13") ' Employee_ID Column from Employee table Table2 = Sheet1.Range("H3:I13") ' Range of Employee Table 1 Dept_Row = Sheet1.Range("E3").Row ' Change E3 with the cell from where you need to start populating the Department Dept_Clm = Sheet1.Range("E3").Column For Each cl In Table1 Sheet1.Cells(Dept_Row, Dept_Clm) = Application.WorksheetFunction.VLookup(cl, Table2, 2, False) Dept_Row = Dept_Row + 1 Next cl MsgBox "Done" End Sub 

要么: '

 'Option 2 Set Ranges using "Set" Option Explicit Sub ADDCLM() On Error Resume Next Dim Dept_Row As Long Dim Dept_Clm As Long Dim Table1 As Range Dim Table2 As Range Dim cl As Variant Set Table1 = Sheet1.Range("A3:A13") ' Employee_ID Column from Employee table Set Table2 = Sheet1.Range("H3:I13") ' Range of Employee Table 1 Dept_Row = Sheet1.Range("E3").Row ' Change E3 with the cell from where you need to start populating the Department Dept_Clm = Sheet1.Range("E3").Column For Each cl In Table1 Sheet1.Cells(Dept_Row, Dept_Clm) = Application.WorksheetFunction.VLookup(cl, Table2, 2, False) Dept_Row = Dept_Row + 1 Next cl MsgBox "Done" End Sub