VBA vlookup公式错误

VBA vlookup formula error

我是 excel 宏 vba 的新手。我的 vlookup 代码有问题,它引用了用户选择的另一个工作簿。

这是我的代码:

Private Sub vlookups()

Dim data_file_new As String
Dim i As Integer
Dim a As String, b As String, path As String

data_file_new = CStr(Application.GetOpenFilename(FileFilter:="Excel Workbooks (*.xls*),*.xls*", Title:="Select new data file for VLOOKUP"))

path = data_file_new

a = "=VLOOKUP(A:A,'[" & path & "]Source'!$A:$AB,28,0)"
b = "=VLOOKUP(A:A,'[" & path & "]Source'!$A:$AJ,36,0)"
i = 7

Do Until Sheets("Macro Template").Cells(i, 1) = ""

    Sheets("Macro Template").Cells(i, 37) = a
    Sheets("Macro Template").Cells(i, 38) = b

    i = i + 1
Loop

End Sub

我的问题是我的代码没有给出正确的 vlookup 公式。相反,它给出了这个公式:

=VLOOKUP(A:A,'[E:\AP NO APPROVAL\[No Approval Monitoring Log_June 2015 xlsx.xlsx]Source]No Approval Monitoring Log_June'!$A:$AB,28,0)

正确的公式是这样的:

=VLOOKUP(A:A,'E:\AP NO APPROVAL\[No Approval Monitoring Log_June 2015 xlsx.xlsx]Source'!$A:$AB,28,0)

如有任何帮助,我们将不胜感激。

谢谢!

试试这个(未测试

Private Sub vlookups()
    Dim ws As Worksheet
    Dim lRow As Long
    Dim sPath As String, sFile As String, sTemp As String
    Dim Ret

    Set ws = ThisWorkbook.Sheets("Macro Template")

    Ret = Application.GetOpenFilename(FileFilter:="Excel Workbooks (*.xls*),*.xls*", _
                                      Title:="Select new data file for VLOOKUP")

    If Ret = False Then Exit Sub

    sFile = GetFilenameFromPath(Ret)
    sPath = Split(Ret, sFile)(0)
    sTemp = "=VLOOKUP(A:A,'" & sPath & "[" & sFile

    With ws
        lRow = .Range("A" & .Rows.Count).End(xlUp).Row

        .Range("AK7:AK" & lRow).Formula = sTemp & "]Source'!$A:$AB,28,0)"
        .Range("AL7:AL" & lRow).Formula = sTemp & "]Source'!$A:$AJ,36,0)"
    End With
End Sub

Public Function GetFilenameFromPath(ByVal strPath As String) As String
    If Right$(strPath, 1) <> "\" And Len(strPath) > 0 Then
        GetFilenameFromPath = _
        GetFilenameFromPath(Left$(strPath, Len(strPath) - 1)) + Right$(strPath, 1)
    End If
End Function

解释

  1. Application.GetOpenFilename()returns一个Variant。如上代码所示处理。

  2. 您要查找的公式是 =VLOOKUP(A:A,'E:\AP NO APPROVAL\[No Approval Monitoring Log_June 2015 xlsx.xlsx]Source'!$A:$AB,28,0)Ret 将为您提供直接的文件路径和名称 E:\AP NO APPROVAL\No Approval Monitoring Log_June 2015 xlsx.xlsxVlookup 在文件名周围放置一个 []。您必须首先从文件路径中提取文件名并重建整个字符串。我们在上面的代码中使用 Function GetFilenameFromPath 来检索它。

  3. 您无需循环单元格即可输入公式。您可以在整个范围内一次输入公式。

您没有指定 sheet 您的公式所指的。就是这个问题。