VBA下标超出选择范围

时间:2014-01-08 10:56:17

标签: excel vba excel-vba

我在 sheet1 中有2个值,我想迁移到 sheet2 。截至目前,我的 CommandButton 工作正常,直到我创建新闻稿。但是一旦我选择新闻稿,它就会给我一个下标超出范围错误。在评论我的最后一行代码时,程序运行正常。

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

1 个答案:

答案 0 :(得分: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