我在下面使用此代碼在另一個使用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)打開文件獲取工作表名稱和關閉它。以我的答案爲例。 –