[英]How to get the sheet name using GetOpenFilename in VLOOKUP
我在下面使用此代碼在使用GetOpenFilename
選擇的另一個文件中使用VLOOKUP。 我希望shtName
是您選擇的文件中工作表的名稱,但是每當我逐步執行它時,它始終是我正在處理並將其放入VLOOKUP的工作表的名稱。
我的VLOOKUP中有shtName
,單步執行時不顯示任何內容。 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
類似於以下內容的文件應為您提供工作表名稱
Dim wbk As Workbook
Set wbk = Workbooks.Open(Filename:="YOUR_FILE_PATH", ReadOnly:=True)
Dim shtName As String
shtName = wbk.Worksheets(1).Name
wbk.Close
注意:如果我們不打算更改任何內容,則可以以只讀模式打開工作簿。
另外,我建議您(遵循良好實踐的良好代碼):
始終指定一個工作表。
例如,對於每個 Range("")
類的Worksheets("YourSheetName").Range("")
或使用With
語句:
With Worksheets("YourSheetName") .Range("A1").Value = 5 'recognize the starting full stop referring to the with statement End With
每個 Rows
, Columns
, Cells
等都相同。
.Select
, .Activate
和Selection.
完全沒有 Option Explicit
並在使用前聲明所有變量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.