未分配工作表CodeName

时间:2017-02-12 07:49:45

标签: vba excel-vba excel

我试图将工作表的代码名称分配给可用的 有时它会正确获取代码名称,有时它不会,变量保持为空。

 Dim sCodeName As String
 sCodeName = Worksheets(atar).CodeName

atar是包含工作表名称的变量。 当我停止代码运行,并在调试模式下,它工作正常。 可能是什么原因?

3 个答案:

答案 0 :(得分:0)

没有限定条件的

WorksheetsActiveWorkbook相同,也许您在某些情况下假设哪些工作簿处于活动状态。

建议完全限定工作表。因此,请引用Workbook对象,例如wbFoo,然后使用sCodeName = wbFoo.Worksheets(atar).CodeName

答案 1 :(得分:0)

您可以尝试使用下面的代码来验证atar中某个工作表名称中是否存在ThisWorkbook

Option Explicit

Sub GetWorksheetCodeName()

Dim sCodeName As String
Dim atar As String
Dim Sht As Worksheet

'atar = "Sheet3" '<-- for tests only

' loop through all worksheets in ThisWorkbook
For Each Sht In ThisWorkbook.Worksheets
    If Sht.Name Like atar Then
        sCodeName = Worksheets(atar).CodeName
        Exit For
    End If
Next Sht

End Sub

答案 2 :(得分:-1)

创建多个工作表但有时不使用工作表中的宏仅使用VBA代码运行

 Sub WSCreate()
    Dim WSA As String
    Dim WSB As String
    Dim WS As Worksheet

        WSA = "SheetA"
        WSB = "SheetB"

        Application.DisplayAlerts = False
        On Error Resume Next

'DELETE MULTIPLE WORKSHEETS  (IF Already Exist)
    Set WS = Nothing
    Set WS = Sheets(WSA)
        WS.Delete
    Set WS = Nothing
    Set WS = Sheets(WSB)
        WS.Delete
    Set WS = Nothing


'CREATE MULTIPLE WORKSHEETS    
   With Application.ThisWorkbook
        .Worksheets.Add.Name = WSA  'WSA = SheetA
        .VBProject.VBComponents(Worksheets(WSA).CodeName).Name = WSA
        .Worksheets.Add.Name = WSB  'WSB = SheetB
        .VBProject.VBComponents(Worksheets(WSB).CodeName).Name = WSB
    End With
     If Err <> 0 Then Exit Sub
    End Sub