2012-07-18 88 views
1

我一直在尝试使用VBA将VLookup公式插入到列中。 Table_array是可变的并且每个月都在变化,所以我想要一个对话框来指定我想要使用的文件。该Table_array是相同的格式每个月和我的公式至今如下:VBA VLookup允许用户选择目录上的文件名

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列。

回答

3

GetOpenFileName不会返回一个对象。因此,你不能Set的价值。

尝试:

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 
+0

+ 1是的,这将有助于。但是'GetOpenFileName'不一定会返回一个字符串。 – 2012-07-18 16:23:19

+0

谢谢悉达思,我已经稍微纠正了我的答案 – JMax 2012-07-18 17:26:33

0

您已声明MyFile为范围,但您试图在var中添加一个文件名。 GetOpenFileName函数返回文件名,但不打开该文件。您必须将文件名保存为字符串变量,然后使用该文件名打开工作簿。

相关问题