我在使用VBA重命名工作表时遇到了问题。
我正在编写一个Sub,需要检查工作簿中是否有一个具有特定名称的工作表,如果没有,则创建一个具有此名称的新工作表。 我得到运行时错误1004应用程序定义或对象定义错误。我希望有人能帮助我。这是我的代码:
Dim ws As Worksheet Dim ArrayElement As Variant Dim Current_Tabs(1 To 10) As String NumberNewTab = 1 Tab_Name_Current_Game = Echt_team1 + "vs. " + Echt_team2 For Each ws In Worksheets 'For every worksheet in this workbook Found = False For Each ArrayElement In Current_Tabs array If Tab_Name_Current_Game = ArrayElement Then Worksheets(ws).Activate Worksheets.Select Found = True End If Next ArrayElement If Found = False Then Worksheets.Add Sheets(1).Name = Tab_Name_Current_Game **'Here I get the error** Current_Tabs(NumberNewTab) = Tab_Name_Current_Game NumberNewTab = NumberNewTab + 1 End If Next ws
如果我使用Sheets(1).Name = "Test"
,那么我就不会遇到错误。我不明白为什么这对VBA来说是一个问题。希望有人可以帮助我。谢谢!
答案 0 :(得分:0)
您从未定义过Tab_Name_Current_Game
。
将Dim Tab_Name_Current_Game as String
添加到顶部的声明中。然后看看会发生什么。
答案 1 :(得分:0)
你可以让它变得更容易:
Public Sub renameSheet()
Dim wb As Excel.Workbook
Dim ws As Excel.Worksheet
Dim Tab_Name_Current_Game As String
Set wb = Excel.ActiveWorkbook
'The line below is copied from your code, but I don't like it.
'You should pass Echt_team1 and Echt_team2 as input parameters to this Sub.
Tab_Name_Current_Game = Echt_team1 + "vs. " + Echt_team2
On Error Resume Next
Set ws = wb.Worksheets(Tab_Name_Current_Game)
On Error GoTo 0
If ws Is Nothing Then
Set ws = wb.Worksheets.Add
ws.Name = Tab_Name_Current_Game
End If
End Sub
为了使代码更可靠,您还可以将此功能添加到代码中:Function to check if sheet name is valid,并更改此行:
ws.Name = Tab_Name_Current_Game
到
ws.Name = legalSheetName(Tab_Name_Current_Game)
它将确保您尝试分配给工作表的名称不会太长并且没有非法字符。