在Excel中更改工作表名称时如何使宏工作

jgwigjjp  于 2023-04-13  发布在  其他
关注(0)|答案(1)|浏览(190)

我做了一个宏,删除20个工作表中的单元格范围内的数据。我在命名工作表之前就这样做了,所以我有下标错误,因为宏引用的工作表名称不再存在。
我选择使用codeName,例如Sheet4,因为这应该永远不会改变(就像其他人在另一个问题上建议的那样)。

Sheet4.Range("TimeSheet4[[Start Time]:[Holiday]]").Select
Selection.ClearContents
Sheet5.Range("TimeSheet45[[Start Time]:[Holiday]]").Select
Selection.ClearContents
Sheet6.Range("TimeSheet456[[Start Time]:[Holiday]]").Select
Selection.ClearContents
Sheet7.Range("TimeSheet4567[[Start Time]:[Holiday]]").Select
Selection.ClearContents

它以前是这样做的,并且工作,但我打算整理代码。

Sheets("Employee 2 ").Select
Range("TimeSheet4[[Start Time]:[Holiday]]").Select
Selection.ClearContents
Sheets("Employee 3").Select
Range("TimeSheet45[[Start Time]:[Holiday]]").Select
Selection.ClearContents
Sheets("Employee 4").Select
Range("TimeSheet456[[Start Time]:[Holiday]]").Select
Selection.ClearContents
Sheets("Employee 5").Select
Range("TimeSheet4567[[Start Time]:[Holiday]]").Select
Selection.ClearContents
kzipqqlq

kzipqqlq1#

清除首表

  • 如果每个表都是每个工作表中的第一个表,则以下内容将完成此工作。
Option Explicit

Sub clearFirstTables()
    
    Const Cols As String = "[[Start Time]:[Holiday]]"
    
    Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
    
    Dim ws As Worksheet
    
    For Each ws In wb.Worksheets
        On Error Resume Next
        ws.Range(ws.ListObjects(1).Name & Cols).ClearContents
        On Error GoTo 0
    Next ws

End Sub

或者,如果每个工作表有多个表,或者它们不是第一个表,则可以使用此方法:

Sub clearAllTables()
    
    Const Cols As String = "[[Start Time]:[Holiday]]"
    
    Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
    
    Dim ws As Worksheet
    Dim tbl As ListObject
    
    For Each ws In wb.Worksheets
        For Each tbl In ws.ListObjects
            On Error Resume Next
            ws.Range(tbl.Name & Cols).ClearContents
            On Error GoTo 0
        Next tbl
    Next ws

End Sub

相关问题