无法获取VLookup以引用其他工作簿

时间:2018-01-03 15:22:57

标签: vba excel-vba vlookup excel

所以我对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

1 个答案:

答案 0 :(得分: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

注意 - 在您的常量中,您使用&#34; 1&#34;而不是&#34; l&#34; - 例如x1Down