我想从特定的工作簿中获取工作表对象,如下所示:
Set ws = Application.Workbooks("WorkBookName.xlsm").Worksheets("sheet1")
但是,由于可以更改工作表的名称,因此我想使用工作表的CodeName。例如:
Set ws = Application.Workbooks("WorkBookName.xlsm").Sheet1
现在,我知道这是行不通的,因为Sheet1是VBA编辑器为方便起见而创建的全局变量。
我也知道我可以使用索引(即Worksheets(1))来获取工作表对象,但是如果有人在工作簿中四处移动工作表,则功能将无法正常工作。
所以我的问题是:如何从特定工作簿(而不是“ ThisWorkbook”)中获取工作表对象,并使用CodeName将其存储在变量中?
这是一个示例代码段(我对在stackoverflow.com中发布内容非常陌生):
Public Sub Main()
' Test Class
Dim test As New StoreContestModel
test.StoreID = "28"
test.StoreName = "Kippersville"
' Other workbook
Dim wb As Workbook
Dim ws As Worksheet
Dim r As Range
Dim v As String
' Showing test StoreID in other workbook. Code is broken up because as one-line it did not work.
Set wb = Application.Workbooks("Contest.xlsm")
Set ws = Application.Workbooks("Contest.xlsm").Sheet1 ' wb.Sheet1 didn't work
Set r = ws.Range("N2")
r.value = test.StoreID
End Sub
我希望StoreID显示在另一个工作簿中指定的单元格中。但是,出现此错误:
运行时错误“ 438”:
对象不支持此属性或方法
答案 0 :(得分:0)
您可以执行以下操作:
Sub Tester()
Dim ws As Worksheet
Set ws = SheetFromCodeName(ActiveWorkbook, "Sheet1")
Debug.Print ws.Name
End Sub
Function SheetFromCodeName(wb As Workbook, cn As String)
Dim s, rv As Worksheet
For Each s In wb.Worksheets
If s.CodeName = cn Then
Set rv = s
Exit For
End If
Next s
Set SheetFromCodeName = rv
End Function