在VBA中使用Vlookup

时间:2012-08-13 18:45:54

标签: vba excel-vba excel

我添加了单元格和工作表的循环,但是我收到了语法错误。

Sub check() 
Dim ws As Worksheet 
Dim i As Long 
For Each ws In Worksheets 

For i = 5 To 10

ws.Range("F" & i).Formula = _
 "=VLookup((CONCATENATE(C1,"" "",C5)),'C:\Documents[TestData.xlsx]Sheet1'!$A$2:$G$28,7, FALSE)"
Sheets("Sheet1").Range("F5").Value = Sheets("Sheet1").Range("F5").Value

Next
End Sub

1 个答案:

答案 0 :(得分:0)

这是你在尝试的吗?

Sub check()
    Sheets("Sheet1").Range("F5").Formula = _
    "=VLookup((CONCATENATE(C1,"" "",C5)),'C:\Documents[TestData.xlsx]Sheet1'!$A$2:$G$28,7, FALSE)"
    Sheets("Sheet1").Range("F5").Value = Sheets("Sheet1").Range("F5").Value
End Sub

<强>后续

要将它放在循环中,您必须将行存储在变量中,然后使用它。例如

Range("F5")也可以写为Range("F" & "5")

所以现在你所要做的就是继续在循环中替换5。见下面的例子

Sub check()
    Dim i As Long

    '~~> From Row 5 to row 10
    '~~> Chnage as applicable
    For i = 5 To 10
        Sheets("Sheet1").Range("F" & i).Formula = _
        "=VLookup((CONCATENATE(C1,"" "",C" & i & _
        ")),'C:\Documents[TestData.xlsx]Sheet1'!$A$2:$G$28,7, FALSE)"

        Sheets("Sheet1").Range("F" & i).Value = Sheets("Sheet1").Range("F" & i).Value
    Next i
End Sub