首页 文章

错误1004重命名工作表

提问于
浏览
1

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

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

    我想你的工作簿是锁定的 . 像这样的小代码适用于空Excel:

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

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

相关问题