excel 定义范围并清除其内容

xe55xuns  于 2023-05-08  发布在  其他
关注(0)|答案(2)|浏览(151)

我有一个很长的报告,其中有几列的0值持续了数百行。0值通常从第50行附近开始,但有时仅从第200行开始。我有一个代码,它做了它所需要的,但需要大量的PC资源,并可能需要几个小时来处理,从而保持整个过程。

Application.Goto Workbooks("doc_flow_report.xlsx").Sheets("Sheet1").Range("a2")
Application.ScreenUpdating = False
    Dim N As Long, i As Long
    N = Cells(Rows.Count, "B").End(xlUp).Row
    For i = N To 2 Step -1
        If Cells(i, "B").Value = Cells(i, "G").Value Then
            Cells(i, "B").EntireRow.Delete
        End If
    Next i
End Sub

我想使用另一种方法,可能会更快地为Excel消化。处理步骤如下:
1.定义一个范围,从B列的第一行(值为0)开始,一直到P列的最后一行(值为0)
1.清除范围的内容。
谢谢任何提示

yacmzcpb

yacmzcpb1#

使用Range.Find两次:

Sub CincoDeMayo()
    Dim ws As Worksheet
    Set ws = Workbooks("doc_flow_report.xlsx").Worksheets("Sheet1")
    
    Dim startCell As Range
    Set startCell = ws.Range("B:B").Find( _
        What:=0, LookIn:=xlValues, _
        LookAt:=xlWhole, SearchDirection:=xlNext)
    
    Dim endCell As Range
    Set endCell = ws.Range("P:P").Find( _
        What:=0, LookIn:=xlValues, _
        LookAt:=xlWhole, SearchDirection:=xlPrevious)
    
    If Not startCell Is Nothing And Not endCell Is Nothing Then
        ws.Range(startCell, endCell).EntireRow.Delete
        ' or change .Delete to .ClearContents
    End If
End Sub

请注意,第一个Find开始搜索 after cell B1。根据您的描述,这应该不是问题:“0值通常从第50行左右开始。”

332nm8kg

332nm8kg2#

清除范围

  • 您可以使用更高效的(与此无关:只有一个匹配)Application.Match来确定单个列中匹配(找到)值的行索引。
Sub RemoveTrailingZeros()

    Dim wb As Workbook
    On Error Resume Next
        Set wb = Workbooks("doc_flow_report.xlsx")
    On Error GoTo 0
    If wb Is Nothing Then
        MsgBox "The workbook is not open.", vbCritical
        Exit Sub
    End If
    
    Dim ws As Worksheet: Set ws = wb.Sheets("Sheet1")
    
    Dim rg As Range
    With ws.Range("A1").CurrentRegion ' nice data: no empty rows or columns
    'With ws.UsedRange ' nothing but the relevant data is in the worksheet
        Set rg = .Resize(.Rows.Count - 1).Offset(1) ' exclude headers
    End With
    
    Dim mrIndex: mrIndex = Application.Match(0, rg.Columns(2), 0)
    If IsError(mrIndex) Then
        MsgBox "No zeros found.", vbCritical
        Exit Sub
    End If
    
    Dim fCell As Range: Set fCell = ws.Cells(mrIndex + 1, "A")
    Dim lCell As Range: Set lCell = rg.Cells(rg.Cells.CountLarge)
    
    Dim crg As Range: Set crg = ws.Range(fCell, lCell)
    
    crg.Clear
    
    MsgBox "Trailing zeros removed.", vbInformation
    
End Sub

相关问题