我想做什么: 我有一个有9列的excel表。在要按列A分组的Excel工作表中
到目前为止我做了什么
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
Dim neighborColumnValue As String
Set myRange = Range("A1:A1000")
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
neighborColumnValue = Cells(currentRow, myRange.Column - 1).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 the cell is not blank and its neighbor's (to the left) value is 0,
'and firstBlankRow hasn't been assigned, then this is the firstBlankRow
'to consider for grouping
If neighborColumnValue = 0 And firstBlankRow = 0 Then
firstBlankRow = currentRow
ElseIf neighborColumnValue <> 0 And firstBlankRow <> 0 Then
'if firstBlankRow is assigned and this row has a value with a neighbor
'who isn't 0, 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
对于这个解决方案,我使用的是一个名为&#34; Sam&#34;的休闲stackoverflow / co程序员的代码。 当我在Excel中表达我的宏时,我会出现错误1004
答案 0 :(得分:2)
尝试从neighborColumnValue
中删除减号1
您已通过myRange
将列设置为A
你不能离开A
neighborColumnValue = Cells(currentRow, myRange.Column - 1).Value
成为
neighborColumnValue = Cells(currentRow, myRange.Column).Value