我有两个Excel工作簿:
Source.xlsx
Tool.xlsm
Source.xlsx
包含一个包含VBA对象名称shtTests
的工作表:
我们假设在Tool.xlsm
中我有一个变量,其中包含对Source.xlsx
中存储的工作簿的引用:
Dim wkbSource as Workbook
Set wkbSource = GetSourceWorkbook() ' Some function that gives a reference to the workbook
核心问题:如何使用shtTests
'在Tool.xlsm
中引用shtTests
VBA名称?
或者将问题表示为代码...假设您有此代码段:
Dim wkbSourceShtTests as Worksheet
Set wkbSourceShtTests = GetShtTestsFromWkbSources(wkbSources)
问题:GetShtTestsFromWkbSources
看起来像什么?
注意:我不希望通过Excel名称引用它,就像使用wkbSources.Worksheets("Test Cloning")
一样,因为有些人可能会在某天更改其Excel名称。
答案 0 :(得分:3)
这是你在尝试的吗?
>>> timeit('i=0\nwhile i<10000: True; i+=1', number=10000)
8.416439056396484
>>> timeit('for i in range(10000): True', number=10000)
5.589155912399292
注意:为此,您需要启用对Visual Basic项目的访问
在Sub Sample()
Dim wbThis As Workbook, wbThat As Workbook
Dim wsThat As Worksheet
Dim wsCodeName As String
Set wbThis = ThisWorkbook
Set wbThat = Workbooks("Book4") '<~~ Change this to relevant workbook
wsCodeName = "ShtSheets"
Set wsThat = wbThat.Worksheets(CStr(wbThat.VBProject.VBComponents(wsCodeName).Properties(7)))
Debug.Print wsThat.Name
End Sub
菜单上,单击File
,选中“信任对VBA项目对象模型的访问权限”框
答案 1 :(得分:1)
如果您想要一个功能而不是设置受信任的访问权限,那么这可能会起作用:
Sub example()
Dim wkbSource As Workbook
Set wkbSource = GetSourceWorkbook()
Dim wkbSourceShtTests As Worksheet
Set wkbSourceShtTests = GetShtTestsFromWkbSources(wkbSource, "shtTests")
End Sub
Function GetShtTestsFromWkbSources(wkbk As Workbook, codename As String) As Worksheet
For Each sht In wkbk.Sheets
If sht.codename = codename Then Set GetShtTestsFromWkbSources = sht
Next
End Function