分组Excel 1004错误

我想要做的是:我有一个9列的Excel表。 在excel表中按列A分组

我到目前为止做了什么

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 

对于这个解决scheme,我使用了一个叫做“Sam”的休闲堆栈stream程/ co程序员的代码, 在这里输入图像说明 当我在excel中优化我的macros时,我出现错误1004

尝试删除从您设置您的专栏通过myRange列的neighborColumnValue减1你不能拿一列从A

 neighborColumnValue = Cells(currentRow, myRange.Column - 1).Value 

 neighborColumnValue = Cells(currentRow, myRange.Column).Value