【发布时间】: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