[英]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
根據我對問題的理解,我認為您想要做的是遍歷特定列中的所有元素,跳過所有空白。
你可以這樣做
代碼塊
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.