我在下面使用此代码在另一个使用GetOpenFilename
选择的文件中使用VLOOKUP。我想shtName
是您选择的文件中的工作表的名称,但是每当我单步执行时,它始终是我工作的工作表的名称并将VLOOKUP放入。如何在VLOOKUP中使用GetOpenFilename获取图纸名称
我有shtName
在我的VLOOKUP中,当我逐步浏览它时,它不会显示任何内容。 X
显示文件名和路径,但shtName
后显示什么。但是我的VLOOKUP无论如何都会结束工作,并将表单放入公式中。
这是为什么?我希望能够自己做到这一点,所以我知道我从你选择的文件中得到表单名称。
Dim iRet As Integer
Dim strPrompt As String
Dim strTitle As String
' Promt
strPrompt = "Please select the last Kronos Full File before the dates of this HCM Report." & vbCrLf & _
"This will be used to find the Old Position, Org Unit, and Old Cost Center." & vbCrLf & _
"For example, if the date of this report is 7-28-17 thru 8-25-17, the closest Kronos Full File you would want to use is 7-27-17."
' Dialog's Title
strTitle = "Last Kronos Full File for Old Positions"
'Display MessageBox
iRet = MsgBox(strPrompt, vbOK, strTitle)
Dim LR As Long
Dim X As String
Dim lNewBracketLocation As Long
X = Application.GetOpenFilename(_
FileFilter:="Excel Files (*.xls*),*.xls*", _
Title:="Choose the Kronos Full File.", MultiSelect:=False)
MsgBox "You selected " & X
'Find the last instance in the string of the path separator "\"
lNewBracketLocation = InStrRev(X, Application.PathSeparator)
'Edit the string to suit the VLOOKUP formula - insert "["
X = Left$(X, lNewBracketLocation) & "[" & Right$(X, Len(X) - lNewBracketLocation)
shtName = ActiveWorkbook.Worksheets(1).name
LR = Range("E" & Rows.Count).End(xlUp).Row
Range("T2").Formula = "=VLOOKUP($E2,'" & X & "]shtName'!$B$1:$AP$99999,15,0)"
Stop
Range("T2").AutoFill Destination:=Range("T2:T" & Range("E" & Rows.Count).End(xlUp).Row)
Stop
Range("T2:T" & Range("E" & Rows.Count).End(xlUp).Row).Select
Stop
Range("U2").Formula = "=VLOOKUP($E2,'" & X & "]shtName'!$B$1:$AP$99999,41,0)"
Range("U2").AutoFill Destination:=Range("U2:U" & Range("E" & Rows.Count).End(xlUp).Row)
Range("U2:U" & Range("E" & Rows.Count).End(xlUp).Row).Select
Range("V2").Formula = "=VLOOKUP($E2,'" & X & "]shtName'!$B$1:$AP$99999,18,0)"
Range("V2").AutoFill Destination:=Range("V2:V" & Range("E" & Rows.Count).End(xlUp).Row)
Range("V2:V" & Range("E" & Rows.Count).End(xlUp).Row).Select
Cells.Select
Cells.EntireColumn.AutoFit
您设置了'shtName = ActiveWorkbook.Worksheets(1).name'这意味着'shtName'是当前打开和活动工作簿中第一个工作表的名称。所以,如果你想让'shtName'成为别的东西,你需要设置它。 –
啊,我认为GetOpenFilename是一旦我做到了,就会成为主动的。好的。你会推荐什么来获取表单名称?我可以从GetOpenFilename或其他东西激活文件吗? – Robillard
我推荐:使用[Workbooks.Open Method](https://msdn.microsoft.com/en-us/vba/excel-vba/articles/workbooks-open-method-excel)打开文件获取工作表名称和关闭它。以我的答案为例。 –