当 ColumnDifferences 方法不再发现差异时如何退出 Do While 循环?

问题描述 投票:0回答:1

我创建了一个宏,它使用 ColumnDifferences 搜索 K 列中的任何编号值更改,然后插入格式化行作为这些值之间的分隔符。任何编号值之间都没有空白单元格。一旦 ColumnDifferences 方法用完要比较的值,一切都会按预期工作,但运行时错误“1004”“未找到单元格”除外。我是 VBA 和一般编程的新手。我确信在 ColumnDifferences 运行完毕后,我会缺少一些简单的代码来退出此循环。任何帮助将不胜感激。

Sub Divider_On_Column_Difference()
'
Range("K1").Select

Do

Range(ActiveCell, ActiveCell.End(xlDown)).Select
Selection.ColumnDifferences(ActiveCell).Select
ActiveCell.Select

    Selection.EntireRow.Insert
    Range(ActiveCell.Offset(0, -10), ActiveCell.Offset(0, -1)).Select
    Selection.RowHeight = 4
    
    With Selection.Borders(xlEdgeLeft)
        .LineStyle = xlContinuous
        .Weight = xlMedium
        .ColorIndex = 1
    End With
    With Selection.Borders(xlEdgeTop)
        .LineStyle = xlContinuous
        .Weight = xlMedium
        .ColorIndex = 1
    End With
    With Selection.Borders(xlEdgeBottom)
        .LineStyle = xlContinuous
        .Weight = xlMedium
        .ColorIndex = 1
    End With
    With Selection.Borders(xlEdgeRight)
        .LineStyle = xlContinuous
        .Weight = xlMedium
        .ColorIndex = 1
    End With
    ExecuteExcel4Macro "PATTERNS(1,0,5,TRUE,2,4,0,0)"
    
    ActiveCell.Offset(1, 10).Select
    
Loop While ActiveCell.Value <> ""

End Sub
excel vba while-loop difference
1个回答
0
投票

代码已被修改和简化。

虽然值得注意的是,一般不建议使用

Select
,但在应用
PATTERNS
之前是必要的。

Option Explicit
Sub Divider_On_Column_Difference()
    Dim curCell As Range, endCell As Range
    Dim c As Range
    Set curCell = Range("K1")
    Set endCell = Cells(Rows.Count, "K").End(xlUp)
    Do
        If curCell = endCell Then Exit Do
        Set c = Range(curCell, endCell).ColumnDifferences(curCell)
        Set curCell = c.Cells(1)
        curCell.EntireRow.Insert
        With Cells(curCell.Row - 1, 1).Resize(1, 10)
            .RowHeight = 4
            With .Borders
                .LineStyle = xlContinuous
                .Weight = xlMedium
                .ColorIndex = 1
            End With
            .Select
            ExecuteExcel4Macro "PATTERNS(1,0,5,TRUE,2,4,0,0)"
        End With
    Loop While True
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.