如何使固定列和变化的行变为两者?

时间:2012-02-24 02:58:20

标签: vba excel-vba excel

当找到0时,我正在尝试清除行和列的内容。

我能够编写清除它们的代码,但我只能改变行。我的专栏是固定的,在我添加更多类似的代码以考虑列A到Z后,它开始变得有点冗长。

我的代码如下

Sub Macro1()

Dim columnval As Long, k As Long

For k = 5 To 6

    If (Range("A" & k)) = 0 Then
    Range("A" & k).ClearContents
    End If

Next k

For k = 5 To 6

    If (Range("B" & k)) = 0 Then
    Range("B" & k).ClearContents
    End If

Next k

End Sub

代码正在运行,只是当它到达Z列时太长了。如果你有更好的方法,请与我分享!谢谢!

3 个答案:

答案 0 :(得分:1)

这种方法会将评估的单元格数量减少到您使用的行和列,不再需要。应该很快:

Option Explicit

Sub ClearZeroValuesInUsedRange()
Dim LR As Long, LC As Long, r As Long, c As Long

LR = Cells.Find("*", Cells(Rows.Count, Columns.Count), SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
LC = Cells.Find("*", Cells(Rows.Count, Columns.Count), SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column

Application.ScreenUpdating = False

    For r = 1 To LR
        For c = 1 To LC
            If Cells(r, c) = 0 Then Cells(r, c).ClearContents
        Next c
    Next r

Application.ScreenUpdating = True
End Sub

如果您想通过将 1 增加到更高的数字来跳过顶部或左侧的列,可以改变起始编号。

此示例适用于第5行和第5行。仅限6 A-Z:

Sub ClearZeroValuesInUsedRange()
Dim r As Long, c As Long

Application.ScreenUpdating = False

    For r = 5 To 6
        For c = 1 To 26
            If Cells(r, c) = 0 Then Cells(r, c).ClearContents
        Next c
    Next r

Application.ScreenUpdating = True
End Sub

答案 1 :(得分:1)

这是实现您想要的最短最快方式。

Option Explicit

Sub Sample()
    Sheets("Sheet1").Cells.Replace What:="0", Replacement:="", _
    LookAt:=xlWhole, SearchOrder:=xlByRows, MatchCase:=False, _
    SearchFormat:=False, ReplaceFormat:=False
End Sub

关注

  
    
      

嗨,如果我只想清除第5行和第6行A-Z列的内容怎么办?好像它正在清除一切。 - user1204868 14分钟前

    
  
Option Explicit

Sub Sample()
    Dim Rng As Range

    Set Rng = Sheets("Sheet1").Range("A5:" & "Z" & Rows.Count)

    Rng.Replace What:="0", Replacement:="", _
    LookAt:=xlWhole, SearchOrder:=xlByRows, MatchCase:=False, _
    SearchFormat:=False, ReplaceFormat:=False
End Sub

西特

答案 2 :(得分:0)

option explicit

sub conditional_clear()
    dim r as long
    dim c as long
    dim ws as worksheet

    for each ws in worksheets
        for r = 1 to ws.usedrange.rows.count
            for c = 1 to ws.usedrange.columns.count
                with ws.cells(r,c)
                    if .value = 0 then 
                        .clearcontents
                    end if 
                end with 
            next c
        next r
    next ws
end sub

编辑:
如果您想要更好地控制清除单元格内容的区域,请更改为此类

sub conditional_clear(srow as long, erow as long, scol as long, ecol as long)
    ...
        for r = srow to erow
            for c = scol to ecol
    ...

并像这样称呼它

call conditional_clear(5, 6, 1, 26)