VBA,带工作表,表的ClearContents

时间:2018-09-12 18:54:44

标签: excel vba excel-vba

我有一张要清除的表格,我的范围行出现object required错误。

我也尝试了其他方法,但是它也倾向于清除当前页面。

Sub ClearDatabase()
    With ThisWorkbook.Worksheets("database").Select
        Range("A2:FR" & .Cells(.Rows.count, "A").End(xlUp).row).ClearContents  'adjust this if needing to clear more
    End With
End Sub

1 个答案:

答案 0 :(得分:2)

正确使用With ... End With块。

Sub ClearDatabase()
    With ThisWorkbook.Worksheets("database")
        'adjust this if needing to clear more
        .Range("A2:FR" & .Cells(.Rows.count, "A").End(xlUp).row).ClearContents  
        'alternate
        '.Range(.cells(2, "A"), .Cells(.Rows.count, "A").End(xlUp).offset(0, 173)).ClearContents
    End With
End Sub

.CurrentRegion属性将覆盖从A1辐射的区域,直到到达完整的空白行和完全空白的列。

Sub ClearDatabase()
    With ThisWorkbook.Worksheets("database")
        'offset preserves the column header labels in row 1
        .Range("A1").CurrentRegion.offset(1, 0).ClearContents  
    End With
End Sub