1) 按索引参考表格:
With Worksheets(1)
'<stuff here>
End With
“索引”取决于“工作簿中工作表的顺序”。如果您打乱您的床单顺序,这可能不再是指同一张床单!
2) 按名称参考工作表:
With Worksheets("Your Sheet Name")
'<stuff here>
End With
这是工作表的 .Name 属性,是在 Excel 工作表选项卡中可见的名称,在 VBA 项目资源管理器的括号中。
3) 按代号参考工作表:
您建议您实际上想要使用工作表的.CodeName 属性。这不能像上面两个例子一样在括号内引用,但确实与上面的一些答案相反!它在创建时自动分配给工作表,并且是“工作表”,然后是先前创建的 CodeNames 中的下一个未使用的编号。
使用CodeName 的优点是它不依赖于工作表顺序(与Index 不同)并且如果用户仅通过在Excel 中重命名工作表来更改Name,它也不会改变。
缺点是代码可能更复杂或模棱两可。由于CodeName 是只读的 [1] 这无法改进,但确实确保了上述优势!有关详细信息,请参阅参考文档。
第一种使用方式:直接...
With Sheet1
'<stuff here>
End With
第二种使用方式:间接地,可能会提供更多的清晰度或灵活性,展示如何使用工作表的CodeName 属性...
通过遍历工作表并读取CodeName 属性,您可以首先找到所需工作表的Index 或Name 属性。然后您可以使用它来引用工作表。
Dim sh as WorkSheet
Dim shName as String
Dim shIndex as Long
' Cycle through all sheets until sheet with desired CodeName is found
For Each sh in ThisWorkbook.WorkSheets
' Say the codename you're interested in is Sheet1
If sh.CodeName = "Sheet1" Then
' - If you didn't want to refer to this sheet later,
' you could do all necessary operations here, and never use shName
' or the later With block.
' - If you do want to refer to this sheet later,
' you will need to store either the Name or Index (below shows both)
' Store sheet's Name
shName = sh.Name
' Store sheet's Index
shIndex = sh.Index
End If
Next sh
' Check if match was found, do stuff as before if it was!
If shName = "" Then
MsgBox "Could not find matching codename"
Else
' Equally to the next line, could use Worksheets(shIndex)
With Worksheets(shName)
'<stuff here>
End With
End If
[1]https://msdn.microsoft.com/en-us/library/office/ff837552.aspx