错误1004重命名工作表

时间:2018-03-13 09:39:19

标签: excel vba excel-vba

我一直遇到麻烦"错误1004 - 方法'姓名'对象' _Worksheet'"在我的VBA宏中。 基本上这个宏的想法是检查列的单元格(包含字符串)并将它们与我的工作簿的工作表的名称进行比较。 如果有一个单元格的值不会出现在工作表的名称中,则宏应创建一个新的工作表,并在单元格内的值之后重命名。

    For j = (RowStart + 1) To 500

    'allocate the value of the reference cell in cell_content
    cell_content = Worksheets("Worksheet1").Cells(j, ColStart).Value
    Switch = 0    

    'check if cell_content appears as the name of one of the worksheet
    For i = 1 To Sheets.Count
        If cell_content = Sheets(i).Name Then
            Switch = Switch + 1
        End If
    Next i

    'if it does not, the macro creates a new worksheets with the name of cell_content
    If Switch = 0 Then
        Set ws = Worksheets.Add(After:=Worksheets(Worksheets.Count))
            ws.Name = cell_content
    End If        
Next j

考虑ColStart和RowStart只是所考虑的列的参考值,变量Switch用于定义是否需要创建新工作表。

问题是宏的最后一部分一直给我1004错误。 有谁知道会出现什么问题?

非常感谢

1 个答案:

答案 0 :(得分:0)

我猜您的工作簿已被锁定。像这样的小代码适用于空Excel:

Public Sub TestMe()    
    Dim ws As Worksheet
    Set ws = Worksheets.Add(After:=Worksheets(Worksheets.Count))
    ws.Name = "CodeThatWorks"    
End Sub

您的代码不起作用的另一个可能原因是名称类似于此ws.Name = "BadNamesIncludeThese:]\?*[]",因此包括工作表中不允许使用名称的特殊字符。