继续@Larry 的回答,如果需要通过 CodeName 引用工作表,您可以使用以下模块,或者如果想通过工作表名称引用,您可以使用工作表选项,感谢 MVP-Juan Pablo González 在另一个博客上的回答:
'Strating sub procedure to write VBA Code to Open an only Excel 2007 macro Files using File Dialog Box
Sub Browse_File()
Dim strFileToOpen As String
Dim Wbk_WeeklyTemplate As Workbook
Dim Tgt_ShtNm As String
Dim Src_ShtNm As String
'Choosing an Excel File using File dialog Box and capturing the file path in the variable
strFileToOpen = Application.GetOpenFilename(Title:="Please select the file to open", FileFilter:="Excel Files *.xlsm (*.xlsm),")
'Checking if file is selected
If strFileToOpen = "False" Then
MsgBox "No file selected.", vbExclamation, "Sorry!"
Exit Sub
Else
Set Wbk_WeeklyTemplate = Workbooks.Open(strFileToOpen)
End If
''Refer sheet by Sheet CodeName
Src_ShtNm = SheetName(Wbk_WeeklyTemplate, "sheetCodeName")
Tgt_ShtNm = SheetName(ThisWorkbook, "sheetCodeName")
Wbk_WeeklyTemplate.Sheets(Src_ShtNm).Range("N15:X18").Copy
ThisWorkbook.Sheets(Tgt_ShtNm).Range("A1").PasteSpecial xlPasteValues
End Sub
''The function SheetName returns the actual name of the sheet by passing sheet code name
Function SheetName(Wb As Workbook, CodeName As String) As String
SheetName = Wb.VBProject.VBComponents(CodeName).Properties("Name").Value
End Function
MVP-Juan Pablo González 解决方案的链接:
https ://www.mrexcel.com/forum/excel-questions/58845-codename-selecting-sheets-through-visual-basic-applications.html
希望有帮助。