Excel VBA宏根据条件

时间:2016-05-16 01:59:01

标签: excel vba excel-vba

我正在尝试创建一个宏,根据列A中是否有值对行进行分组。某些没有值的单元格可能仍然具有空文本字符串,因此最好使用类似长度的内容大于2作为分组的条件而不仅仅是空白。应用宏的范围是第3行到数据集的最后一行(或者如果需要定义范围,则通过行3000就足够了)。例如,如果A4有一个值,而A10有一个值,那么第5行到第9行应该成为一个组。我发现一些代码只是谷歌搜索,但我无法正确应用它,所以我宁愿从头开始。提前谢谢!

2 个答案:

答案 0 :(得分:3)

试一试 如果空单元格是空白的话,对我有用

sub ashGrp()

Dim rng As Range
Dim blankRange As Range
Dim grp As Range
Set rng = Range("a3", Cells(Rows.Count, 1).End(xlUp))
Set blankRange = rng.SpecialCells(xlCellTypeBlanks)

For Each grp In blankRange
    grp.Rows.Group
Next

end sub

如果您需要对文本或空白进行分组,那么此联合代码将执行此操作

Sub ashGrp()

    Dim rng As Range
    Dim blankRange As Range
    Dim grp As Range
    Dim txtRange As Range
    Dim unionRange As Range

    Set rng = Range("a3", Cells(Rows.Count, 1).End(xlUp))
    Set blankRange = rng.SpecialCells(xlCellTypeBlanks)
    Set txtRange = rng.SpecialCells(xlCellTypeConstants, xlTextValues)
    Set unionRange = Union(blankRange, txtRange)

    For Each grp In unionRange
    grp.Rows.Group
    Next


End Sub

答案 1 :(得分:1)

你可以试试这个。这篇帖子是一个缩小的宏:https://stackoverflow.com/a/14967281/6201755

Public Sub GroupCells()
    Dim myRange As Range
    Dim rowCount As Integer, currentRow As Integer
    Dim firstBlankRow As Integer, lastBlankRow As Integer
    Dim currentRowValue As String

    'select range based on given named range
    Set myRange = Range("A3:A3000")
    rowCount = Cells(Rows.Count, myRange.Column).End(xlUp).Row

    firstBlankRow = 0
    lastBlankRow = 0
    'for every row in the range
    For currentRow = 1 To rowCount
        currentRowValue = Cells(currentRow, myRange.Column).Value

        If (IsEmpty(currentRowValue) Or currentRowValue = "") Then
            'if cell is blank and firstBlankRow hasn't been assigned yet
            If firstBlankRow = 0 Then
                firstBlankRow = currentRow
            End If
        ElseIf Not (IsEmpty(currentRowValue) Or currentRowValue = "") Then
            If firstBlankRow <> 0 Then
                'if firstBlankRow is assigned and this row has a value
                'then the cell one row above this one is to be considered
                'the lastBlankRow to include in the grouping
                lastBlankRow = currentRow - 1
            End If
        End If

        'if first AND last blank rows have been assigned, then create a group
        'then reset the first/lastBlankRow values to 0 and begin searching for next
        'grouping
        If firstBlankRow <> 0 And lastBlankRow <> 0 Then
            Range(Cells(firstBlankRow, myRange.Column), Cells(lastBlankRow, myRange.Column)).EntireRow.Select
            Selection.Group
            firstBlankRow = 0
            lastBlankRow = 0
        End If
    Next
End Sub