VBA VLookup允许用户选择目录上的文件名
我一直在尝试使用VBA将VBA VLookup允许用户选择目录上的文件名,vba,excel,lookup,Vba,Excel,Lookup,我一直在尝试使用VBA将VLookup公式插入到列中。Table\u数组是可变的,每个月都会更改,因此我想要一个对话框来指定要使用的文件。表_数组每个月的格式都相同,我的公式如下: Sub VlookupMacro() Dim FirstRow As Long Dim FinalRow As Long Dim myValues As Range Dim myResults As Range Dim myFile As Range Dim myCount As Integer Set myFi
VLookup
公式插入到列中。Table\u数组
是可变的,每个月都会更改,因此我想要一个对话框来指定要使用的文件。表_数组
每个月的格式都相同,我的公式如下:
Sub VlookupMacro()
Dim FirstRow As Long
Dim FinalRow As Long
Dim myValues As Range
Dim myResults As Range
Dim myFile As Range
Dim myCount As Integer
Set myFile = Application.GetOpenFilename("Excel Files (*.xls), *.xls")
Set myValues = Application.InputBox("Please select the first cell in the column with the values that you're looking for", Type:=8)
Set myResults = Application.InputBox("Please select the first cell where you want your lookup results to start ", Type:=8)
Range(myResults, myResults.Offset(FinalRow - FirstRow)).Formula = _
"=VLOOKUP(" & Cells(FirstRow, myValues.Column) & ", myFile.value($A$2:$B$U20000), 5, False)"
If MsgBox("Do you want to convert to values?", vbYesNo) = vbNo Then Exit Sub
Columns(myResults.Column).Copy
Columns(myResults.Column).PasteSpecial xlPasteValues
Application.CutCopyMode = False
End Sub
当代码没有通过
Set=myFile
行时,“myFile”出现问题。欢迎提出任何建议或修正案。除此之外,变量文件的长度永远不会超过20000行(这就是我在公式中固定了范围的原因),我们将始终选择第5列。您已将MyFile声明为范围,但尝试将文件名放入变量中。GetOpenFileName函数返回文件名,但不打开文件。您必须将文件名保存为字符串变量,然后使用该文件名打开工作簿。GetOpenFileName
不会返回对象。因此,您不能设置该值
尝试:
+1是的,那会有帮助。但是GetOpenFileName
不一定返回字符串。
FileName = Application.GetOpenFilename(FileFilter:="Excel Files (*.xls), *.xls", Title:="Please select a file")
If FileName = False Then
' User pressed Cancel
MsgBox "Please select a file"
Exit Sub
Else
Workbooks.Open Filename:=FileName
End If