Excel VBA - 具有不同文件名的VLookup

时间:2015-02-17 20:26:28

标签: excel-vba filenames vlookup vba excel

我正在尝试对没有常量名称的文件执行vlookup。文件名由两个TextBox中显示的文件名确定。我已经开始设置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

1 个答案:

答案 0 :(得分: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)"

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

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

附录:.Address with external:= True

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

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