VBA下标超出范围select

我有Sheet1中的2个值,我想迁移到sheet2 。 截至目前我的CommandButton工作正常,直到我创build一个新闻表 。 但是,只要我select我的新闻稿,它会给我一个超出范围错误下标 。 在评论我的最后一行代码的程序运行良好。

Private Sub CommandButton1_Click() Dim CustomerName As String, CustomerProblem As Integer, newSheet As Worksheet, newName As String Do newName = Application.InputBox("What do you want to name the new sheet?", Type:=2) If newName = "False" Then Exit Sub: Rem cancel pressed Set newSheet = ThisWorkbook.Sheets.Add(After:=ThisWorkbook.Sheets(1)) On Error Resume Next newSheet.Name = newName newName = Error On Error GoTo 0 If newName <> vbNullString Then Application.DisplayAlerts = False newSheet.Delete Application.DisplayAlerts = True MsgBox newName End If Loop Until newName = vbNullString Worksheets("sheet1").Select CustomerName = Range("C4") CustomerProblem = Range("C5") 

这条线给了我错误。

 Worksheets("newName").Select 

引号内的任何内容都将被视为string而不是variables。 更改

 Worksheets("newName").Select 

 Worksheets(newName).Select 

也几乎不需要使用。select.Select/.Activate.Select/.Activate 。 你可能想看到这个

从评论后续

这是你正在尝试?

 Private Sub CommandButton1_Click() Dim CustomerName As String Dim CustomerProblem As Integer Dim newSheet As Worksheet Dim newName As Variant Do newName = InputBox("What do you want to name the new sheet?", _ "Please enter a sheet name") If newName = False Or Len(Trim(newName)) = 0 Then Exit Sub Application.DisplayAlerts = False On Error Resume Next ThisWorkbook.Sheets(newName).Delete On Error GoTo 0 Application.DisplayAlerts = True Set newSheet = ThisWorkbook.Sheets.Add(After:=ThisWorkbook.Sheets(1)) newSheet.Name = newName newSheet.Activate Loop End Sub