繁体   English   中英

VBA Excel宏来解析Excel中的数据块

[英]VBA excel macro to parse blocks of data in excel

我是VBA的新用户,是excel的新手(例如几个小时前的新手),但实际上不是程序员,所以请多多包涵。

我有一个excel数据集,所有数据都集中在一个这样的列(A列)中:

Data
Data
Data

Data
Data
Data

Data
Data
Data
Data
Data

Data
Data

即,数据块由空白行隔开,但不是有规律的间隔。 我正在尝试编写一个宏,该宏将遍历文件和Group(特定的excel命令)这些数据块。 到目前为止,我有这个:

Set firstCell = Worksheets("627").Range("A1")
Set currentCell = Worksheets("627").Range("A1")

Do While Not IsEmpty(firstCell)
    Set firstCell = currentCell

    Do While Not IsEmpty(currentCell)

        Set nextCell = currentCell.Offset(1, 0)

        If IsEmpty(nextCell) Then
        Range("firstCell:currentCell").Select
        Selection.Rows.Group
        Set firstCell = nextCell.Offset(1, 0)

        Else
            Set currentCell = nextCell

        End If


    Loop

Loop

我有些困惑,在转移到下一个数据块并启动逻辑上遇到了特别麻烦。

任何帮助,将不胜感激!

你们来了 您只需要提取您范围内的地址即可,而不是尝试引用该对象。 您还需要在if语句中重置当前和第一个单元格。

Sub test()
Set firstCell = Worksheets("test2").Range("A1")
Set currentcell = Worksheets("test2").Range("A1")

Do While Not IsEmpty(firstCell)
    Set firstCell = currentcell

    Do While Not IsEmpty(currentcell)

        Set nextcell = currentcell.Offset(1, 0)
        If IsEmpty(nextcell) Then
          Range(firstCell.Address, currentcell.Address).Select
          Selection.Rows.group
          Set currentcell = nextcell.Offset(1, 0)
          Set firstCell = nextcell.Offset(1, 0)

        Else
            Set currentcell = nextcell

        End If


    Loop

Loop

End Sub

这样的事情怎么样:

Option Explicit

Public Sub tmpTest()

Dim i As Long
Dim lngLastRow As Long

With ThisWorkbook.Worksheets(1)
    lngLastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
    For i = lngLastRow To 1 Step -1
        If .Cells(i, 1).Value2 = vbNullString Then
            .Range(.Cells(i + 1, 1), .Cells(lngLastRow, 1)).EntireRow.Group
            lngLastRow = i - 1
        End If
    Next i
    .Range(.Cells(1, 1), .Cells(lngLastRow, 1)).EntireRow.Group
End With

End Sub

首先,您的代码在显示以下内容时出错

Range("firstCell:currentCell").Select

您正在尝试选择名为“ firstCell:currentCell”的范围,而不是

选择范围从第一个单元格到当前单元格

您应该将其更改为

.Range(firstCell,currentCell).select

尝试使用下面的代码,看看它是否满足您的要求

Dim GROUP_LAST_CELL As Range

With Worksheets("627")

    LAST_ROW = .Range("A" & Rows.Count).End(xlUp).Row

    I = 1

    While I <= LAST_ROW
        Set GROUP_LAST_CELL = .Cells(I, 1).End(xlDown)
        .Range(.Cells(I, 1), GROUP_LAST_CELL).Rows.Group
        I = GROUP_LAST_CELL.Row + 2
    Wend

End With

根据我对问题的理解,我认为您想要做的是遍历特定列中的所有元素,跳过所有空白。

你可以这样做

  • 计算列的最后一行
  • 从第一行计数循环到计算出的lastRow计数
  • 在循环中应用条件以仅打印非空单元格

代码块

Sub test()

Dim j As Long, lastRow As Long

lastRow = Cells(Rows.Count, "A").End(xlUp).Row

For j = 1 To lastRow

    If Cells(j, "A").Value <> "" Then
        MsgBox (Cells(j, "A").Value)

     End If
Next j

End Sub

希望对您有所帮助!

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM