2014-01-08 109 views
1

我有2個值sheet1我想遷移到sheet2。截至目前,我的CommandButton正常工作,直到我創建一個報表。但只要我選擇我的報表它給了我一個下標超出範圍錯誤。在評論我的最後一行代碼時,程序運行良好。VBA下標超出範圍選擇

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 

回答

0

引號內的任何內容都將被視爲字符串而不是變量。更改

Worksheets("newName").Select 

Worksheets(newName).Select 

而且幾乎沒有任何需要使用.Select/.Activate。您可能希望看到THIS

從評論

跟進這是你想什麼呢?

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 
+0

上刪除引號我仍然得到了同樣的錯誤:/ – user2735206

+0

在這種情況下,檢查什麼是'newName'的價值?它不能爲空,也不能包含不需要的空格。它必須包含與工作表相同的確切名稱。如果你看一下上面的代碼,請參考 –

+0

。我將該工作表的名稱作爲用戶的輸入。 newSheet.Name = newName – user2735206