Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/vba/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
VBA VLookup允许用户选择目录上的文件名_Vba_Excel_Lookup - Fatal编程技术网

VBA VLookup允许用户选择目录上的文件名

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

我一直在尝试使用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 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