在Excel VBA中清除特定的列集

时间:2016-08-12 13:46:08

标签: excel vba excel-vba

我似乎无法为此获得正确的语法。我想编写一个VBA脚本来清除第4行中的A到H列,直到列中的最后一个单元格。我知道我可以写

Sheets("BAC").Rows(4 & ":" & Sheets("BAC").Rows.Count).ClearContents
Sheets("JPM").Rows(4 & ":" & Sheets("JPM").Rows.Count).ClearContents
Sheets("CITI").Rows(4 & ":" & Sheets("CITI").Rows.Count).ClearContents

清除行,但如何将其更改为仅应用于列A到H而不是所有列?

4 个答案:

答案 0 :(得分:2)

这将为你做。

Sub clearRowsAtoH()

Dim i As Integer

For i = 1 To 8

    Sheets("BAC").range(Sheets("BAC").Cells(4, i), Sheets("BAC").Cells(Rows.count, i).End(xlUp)).ClearContents
    Sheets("JPM").range(Sheets("JPM").Cells(4, i), Sheets("JPM").Cells(Rows.count, i).End(xlUp)).ClearContents
    Sheets("CITI").range(Sheets("CITI").Cells(4, i), Sheets("CITI").Cells(Rows.count, i).End(xlUp)).ClearContents
Next i

End Sub

编辑:使用'with'语句可以更清晰。

Sub clearRowsAtoH()

Dim i As Integer

For i = 1 To 8
With Sheets("BAC")
    .range(.Cells(4, i), .Cells(Rows.count, i).End(xlUp)).ClearContents
End With
With Sheets("JPM")
    .range(.Cells(4, i), .Cells(Rows.count, i).End(xlUp)).ClearContents
End With
With Sheets("CITI")
    .range(.Cells(4, i), .Cells(Rows.count, i).End(xlUp)).ClearContents
End With
Next i

End Sub

答案 1 :(得分:1)

使用

Sheets("BAC").Range("A4:H" & Sheets("BAC").UsedRange.Rows.Count).ClearContents
Sheets("JPM").Range("A4:H" & Sheets("JPM").UsedRange.Rows.Count).ClearContents
Sheets("CITI").Range("A4:H" & Sheets("CITI").UsedRange.Rows.Count).ClearContents

答案 2 :(得分:1)

试试这个,例如

With Sheets("BAC")
    .Range("A4:H" & .Range("A4").End(xlDown).Row).ClearContents
End With

答案 3 :(得分:1)

如果您的图书中有多个工作表,请尝试以下方法:

Sub clear_rows()
Dim Wks As String
Dim i As Integer
Dim last_cell As Long

Application.ScreenUpdating = False
For Each Worksheet In Worksheets ' loop through all worksheets
    Wks = Worksheet.Name    'get the name of the sheet as a string
    If Wks = "BAC" Or Wks = "JPM" Or Wks = "CITI" Then  'check the string against your list (could use array or modify to fit your application)
        Worksheets(Wks).Activate
        For i = 1 To 8      'loop through all columns you want a=1,h=8 and so on
            last_cell = Worksheets(Wks).Cells(Rows.Count, i).End(xlUp).Row 'get the last used cell in the column i
            If Not last_cell < 4 Then Worksheets(Wks).Range(Cells(4, i), Cells(last_cell, i)).Clear 'clear it if the column has more than 3 cells
        Next
    End If
Next
Application.ScreenUpdating = True

End Sub

修改以适合您的口味!