无法获取VLookup来引用另一个工作簿

问题描述 投票:1回答:1

所以我对VBA比较陌生,我试图让Vlookup返回一个搜索另一个工作簿的值。问题是,我不断获得经典

1004错误

在Vlookup的线上。我只是想在当前工作簿上搜索一个数字并在另一个工作簿上找到它,返回与之关联的日期,但它不会给我任何东西

我见过很多人问这样的东西,但是没有看到我的特定问题的答案,我想这在初学者中很常见。所以,除了我的问题的实际解决方案之外,任何有关如何制作更好的代码的帮助都表示赞赏。

Sub Add_Dates()

    Application.CutCopyMode = False

    Dim Lastzip As Integer, Val As Integer

    'Open this workbook just in case it's not yet selected
    Workbooks.Open ("C:\(%)\combine zslb and zpdi.xlsm")
    LastRow = Range("A1").End(x1Down).Row 
    'get the value for the last row

    Workbooks.Open ("C:\(%)\zipe zpdi zslb.xlsx")
    Sheets("ZSLB").Activate
    ActiveCell.SpecialCells(x1LastCell).Select
    Lastzip = ActiveCell.Row
    'Same, get the value of the last row of this wbk, 
    'which changes everyday, so can't be a fix value

    Workbooks("combine zslb and zpdi.xlsm").Sheets("zslb").Activate
    Range("A2").End(x1ToRight).Select
    col = Selection.Offset(0,1).Column

    For i = 2 to LastRow
        Val = Application.VLookup(Cells(i, 1), Workbooks("zipe zpdi zslb.xlsx"). _
            Sheets("ZSLB").Range(Cells(2, 1), Cells(Lastzip, 31)), 31, False)
        Cells(i, col).Value = Val
    Next i
End Sub
vba excel-vba vlookup excel
1个回答
1
投票

未经测试但编译:

Sub Add_Dates()

    Const WB_PATH As String = "C:\(%)\"

    Application.CutCopyMode = False

    Dim LastZipRow As Long, LastCombRow As Long, col As Long, v
    Dim wbComb As Workbook, wbZipe As Workbook, i As Long
    Dim shtComb As Workbook, shtZipe As Workbook, rngLookup As Range

    Set wbComb = GetWorkbook(WB_PATH, "combine zslb and zpdi.xlsm")
    Set wbZipe = GetWorkbook(WB_PATH, "zipe zpdi zslb.xlsx")

    Set shtComb = wbComb.Sheets("ZSLB")
    Set shtZipe = wbZipe.Sheets("ZSLB")

    LastCombRow = shtComb.Range("A1").End(xlDown).Row
    LastZipRow = shtZipe.SpecialCells(xlLastCell).Row
    col = shtComb.Range("A2").End(xlToRight).Column

    Set rngLookup = shtZipe.Range(shtZipe.Cells(2, 1), _
                                  shtZipe.Cells(LastZipRow, 31))

    For i = 2 To LastCombRow
        v = Application.VLookup(shtComb.Cells(i, 1), rngLookup, 31, False)
        shtComb.Cells(i, col).Value = IIf(IsError(v), "???", v)
    Next i

End Sub

'return a reference to an already-open file, or if not open then open it
Function GetWorkbook(wbPath, wbName) As Workbook
    Dim rv As Workbook
    If Right(wbPath, 1) <> "\" Then wbPath = wbPath & "\"
    On Error Resume Next '<< ignore error if file not open
    Set rv = Workbooks(wbName)
    On Error GoTo 0
    'note there's no error handling here to account for "file not found"
    If rv Is Nothing Then Set rv = Workbooks.Open(wbPath & wbName)
    Set GetWorkbook = rv
End Function

注意 - 在你的常量中,你使用的是“1”而不是“l” - 例如x1Down

© www.soinside.com 2019 - 2024. All rights reserved.