【问题标题】:Excel VBA - VLookup with Varying File NamesExcel VBA - 具有不同文件名的 VLookup
【发布时间】:2025-12-29 16:20:09
【问题描述】:

我正在尝试对没有常量名称的文件执行 vlookup。文件名由两个文本框中显示的文件名确定。我已经开始设置 vLookup 方程,但我不确定在运行宏时它出了什么问题。我从 vlookup 行收到类型不匹配错误,并且范围值似乎为空。是否有其他方法可以引用适用于这种情况的范围?感谢您的帮助。

'Populating the textbox
Private Sub openDialog1()

Dim fd As Office.FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
  .AllowMultiSelect = False
  .Title = "Please select the report."
  .Filters.Clear
  .Filters.Add "Excel 2003", "*.xls"
  .Filters.Add "All Files", "*.*"
  If .Show = True Then
    FilePath1 = .SelectedItems(1)'The full File path
    ary = Split(.SelectedItems(1), "\")'Splitting the file name from the file path
    TextBox1.Value = ary(UBound(ary))'Displaying just the file name and extension

  End If
End With
End Sub
'The second textbox is filled the same way.


'VLookup using a cell in File 1 vs. the column in File 2
Private Sub Vlookup()

Windows(TextBox2.Value).Activate
myFileName2 = ActiveWorkbook.Name
mySheetName2 = ActiveSheet.Name
myRangeName2 = Range("B2:B2000")

Windows(TextBox1.Value).Activate
Columns("F:F").Select
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Range("F2").Select

Range("F2").Formula = "=VLOOKUP(E2,[" & myFileName2 & "]" & mySheetName2 & "!" & myRangeName2 & ",1,0)" ' Having issues with the syntax here.

Range("F2").Select
Selection.AutoFill Destination:=Range("F2:F2000")
End sub

【问题讨论】:

  • myRangeName2 = Range("B2:B2000").Address 开始,取出 B2:B2000 部分。如果您的工作表名称可能包含空格,那么您将需要添加环绕刻度(也称为撇号),例如 ='[Book1]Sheet 2'!$F$8
  • 好的,我的范围可以填充,但是我如何在不注释掉所有内容的情况下获得刻度。

标签: excel filenames vlookup vba


【解决方案1】:

myRangeName2 = Range("B2:B2000").Address 开始,取出 B2:B2000 部分。如果您的工作表名称可能包含一个空格,那么您将需要添加环绕刻度(也称为撇号),例如 '[Book1]Sheet 2'!$B$2:$B$2000。示例:

Range("F2:F2000").Formula = "=VLOOKUP(E2, '[" & myFileName2 & "]" & mySheetName2 & "'!" & myRangeName2 & ", 1, FALSE)"

记号在第一个方括号之前开始,在将工作簿/工作表与实际单元格区域分开的感叹号之前结束。

您将在上面注意到,该公式可以以相对向下填充方式一次应用于所有单元格(替换单独的.FillDown 操作)。 myRangeName2 需要表示绝对单元格地址(例如 $B$2:$B$2000),当使用 myRangeName2 = Range("B2:B2000").Address 时这是默认值。请参阅Address property 了解更多信息。

附录:.Address with external:=True

虽然学习工作簿/工作表/单元格范围地址的正确字符串构造绝不是一件坏事,但可以通过将 , External:=True 参数添加到 .Address 检索来直接检索整个内容。

myRangeName2 = ActiveWorkbook.ActiveSheet.Range("B2:B2000").Address(RowAbsolute:=1, ColumnAbsolute:=1, external:=True)
Range("F2:F2000").Formula = "=VLOOKUP(E2, " & myRangeName2 & ", 1, FALSE)"

【讨论】:

  • 事后思考:无论是否真的需要蜱虫,它们都可以进入。除非在实际需要时它们不在场,否则它们不会造成任何伤害。
  • 感谢您对所有这些语法的帮助。但是,现在我收到“应用程序定义或对象定义错误”。对与生产线相关的原因有什么想法。
  • @Tyler - 很高兴这对你有用。如果其他人可以看到我的逐块方法出错的地方,我将不胜感激指出错误,以便我可以编辑此“答案”并进行任何必要的更正。