请协助。我在这里有此代码,它适用于第一张工作表,但是没有在第二张工作表中执行。我想我缺少工作表语法。谢谢。
Dim arrSheets As Variant, sht As Variant
arrSheets = Array("tl_1", "tl_2")
For Each sht In arrSheets
Sheets(sht).UsedRange.Offset(1).ClearContents
Next sht
答案 0 :(得分:3)
我的2美分:不要依赖工作表名称。而是使用从(Visual Basic编辑器)看到的(Name)属性。请注意,您可以自己给有效名称,而不是默认的Sheet1..N。这样,您的代码将可以在对名称的修改(如从Excel底部的选项卡中看到的那样)中保存下来。
Option Explicit
Public Sub DoTheClearThing()
Dim loopVariant As Variant
Dim loopWorksheet As Excel.Worksheet
Dim worksheetsToConsider As Variant
'Use the (Name) property, as seen from the Visual Basic Editor, of the worksheets you're interested in.
'The array below is not a string array; it is an array of worksheet objects.
worksheetsToConsider = Array(TL_1, TL_2)
'The For's variable must be a Variant; you can then Set it to a variable of the Worksheet type and enjoy Intellisense.
For Each loopVariant In worksheetsToConsider
Set loopWorksheet = loopVariant
loopWorksheet.UsedRange.Offset(1).ClearContents
Next
End Sub
从工作簿的代码中,您可以使用其(Name)属性直接与工作表对象进行交互。避免使用ThisWorkbook.Worksheets("tl_1").SomeMethod
,而直接使用TL_1.SomeMethod
。顺便说一句,可以使用其CodeName
属性通过代码读取工作表的(Name)属性。
答案 1 :(得分:1)
Option Explicit
'This will do something to your target sheets,
'just make sure your "something" is what you want
Dim N As Long
Dim wsName As String
'Optional if included
For N = 1 To ThisWorkbook.Sheets.Count
wsName = ThisWorkbook.Worksheets(N).Name
If wsName = "tl_1" or wsName = "tl_2" Then
ThisWorkbook.Worksheets(N).UsedRange.Offset(1).ClearContents
Else 'Do Nothing
End If
Next N
注意:这是非常依赖于工作表名称的,如果您不是唯一的用户,则用户可以更改这些名称。您可能需要对工作表进行CodeName(属性资源管理器并更改名称),然后拉出CodeName。
您可以使用一个数组来保存工作表名称,但是除非将名称加载到数组中,否则似乎比它的价值还麻烦。
-WWC
答案 2 :(得分:1)
Worksheet.UsedRange
并不总是返回正确的地址。考虑下面的测试结果:
Sub Test()
Application.ScreenUpdating = False
Dim cell As Range, target As Range
Debug.Print "Data Range", "|"; "UsedRange"
Debug.Print String(24, "_")
With Worksheets.Add
Set target = .Range("B2:D2")
target.Value = 1
Debug.Print target.Address, "|"; .UsedRange.Address
End With
With Worksheets.Add
.Range("A1:G10").Interior.Color = 65535
Set target = .Range("B2:D2")
target.Value = 1
Debug.Print target.Address, "|"; .UsedRange.Address
End With
End Sub
Sub ClearNonHeaderRows()
Dim arrSheets As Variant, sht As Variant
Dim cell As Range
arrSheets = Array("tl_1", "tl_2")
For Each sht In arrSheets
With Worksheets(sht).UsedRange
Set cell = .Find("*", .Cells(1, 1))
If Not cell Is Nothing Then
cell.Offset(1).Resize(.Cells.Rows.Count - cell.row + .Cells(1, 1).row).EntireRow.ClearContents
End If
End With
Next sht
End Sub