excel 在VBA脚本中按索引号引用表的正确语法是什么

hyrbngr7  于 2023-04-13  发布在  其他
关注(0)|答案(2)|浏览(173)

我尝试将一个非常简单的VBA脚本放在一起,以清除指定工作表中所有表的指定表列范围内的单元格内容([Front Straddle]:[Front Option])。此脚本将仅存在于“VolJump”工作表中,该工作表包含任意数量的格式相同但名称不同的表。因此,我觉得最好的方法是通过索引号引用表。
这就是我在'Range'函数中遇到的正确引用/嵌套问题,如下所示。任何帮助都非常感谢。

Sub ClearCells()

    Dim i As Long
    Dim sh As Worksheet

    Set sh = ThisWorkbook.Worksheets("VolJump")

 If sh.ListObjects.Count > 0 Then
  For i = 1 To sh.ListObjects.Count

  Range("Activesheet.ListObjects(1)[[Front Straddle]:[Front Option]]").Select
    Selection.ClearContents
            
        Next i
    End If
End Sub
ux6nzvsh

ux6nzvsh1#

清除表列范围内容

Option Explicit

Sub ClearCells()
    Dim ws As Worksheet: Set ws = ThisWorkbook.Worksheets("VolJump")
    Dim tbl As ListObject
    For Each tbl In ws.ListObjects
        ws.Range(tbl.Name & "[[Front Straddle]:[Front Option]]").ClearContents
    Next tbl
End Sub
3okqufwl

3okqufwl2#

使用ListObjects:

Sub ClearColumns()

    Dim lo As ListObject
    Dim ColNum1 As Long, ColNum2 As Long
    For Each lo In ThisWorkbook.Worksheets("Sheet1").ListObjects
        'Get the index numbers of the start and end columns.
        ColNum1 = lo.ListColumns("Front Straddle").Index
        ColNum2 = lo.ListColumns("Front Option").Index
        
        'Resize the range from the start column to the end column and clear it.
        lo.DataBodyRange.Columns(ColNum1).Resize(, ColNum2 - ColNum1 + 1).ClearContents
    Next lo

End Sub

相关问题