如何在VLOOKUP中使用GetOpenFilename获取表单名称

我在下面使用这个代码来在使用GetOpenFilenameselect的另一个文件中使用VLOOKUP。 我希望shtName是您select的文件中的工作表的名称,但每当我单步执行时,它始终是我正在工作并将VLOOKUP放入工作表的名称。

我在我的VLOOKUP中使用了shtName ,当我逐步浏览它时,它不显示任何内容。 X显示文件名和path,但是shtName之后什么都不显示。 但是,我的VLOOKUP无论如何都结束了工作,并将表单放入公式中。

这是为什么? 我希望能够自己做,所以我知道我从你select的文件中获取表名。

 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 

注意:如果我们不打算改变任何东西,我们可以以只读模式打开工作簿。


此外,我build议(为了良好的做法,一个好的代码):

  • 总是指定一个工作表。
    例如对于每个 Range("")Worksheets("YourSheetName").Range("")
    或者使用With语句:

     With Worksheets("YourSheetName") .Range("A1").Value = 5 'recognize the starting full stop referring to the with statement End With 
  • RowsColumnsCells等都一样

  • 避免使用.Select.ActivateSelection. 在所有。
    (在互联网上有很多教程如何避免它们)。
  • 使用Option Explicit并在使用之前声明所有的variables。
    (避免许多问题,尤其是打字错误)。