我试图对一个没有常量名称的文件执行一个vlookup。文件名由两个TextBoxes中显示的文件名确定。我已经开始建立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发布于 2015-02-17 21:57:22
从myRangeName2 = Range("B2:B2000").Address开始,以获得B2:B 2000部分。如果工作表名称可能包含一个空格,那么您将需要添加像'[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与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)"https://stackoverflow.com/questions/28570499
复制相似问题