gpt4 book ai didi

VBA vlookup公式错误

转载 作者:行者123 更新时间:2023-12-02 13:37:16 25 4
gpt4 key购买 nike

我是 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() 返回一个 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. 您无需循环单元格即可输入公式。您可以在整个范围内一次性输入公式。

关于VBA vlookup公式错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30817359/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com