我写了一个相对简单的程序,意图执行以下操作:
ThisRow
和LastRow
我的代码不会产生错误消息,但它也不会返回所需的结果:单元格C27的值应为2,但它返回1并且同一列中的所有单元格都是空白。这看起来很奇怪,因为在立即窗口中它们都得到值1(这仍然不正确,但与打印到电子表格的内容不同)。
我已经尝试了一段时间来解决它,但我不知道错误可能在哪里。我非常感谢你的帮助!代码如下:
Sub DataSort()
Dim i As Object, ThisRow As Integer , LastRow As Integer
Range("C26").Value = 1
Range("C27").Activate
ThisRow = ActiveCell.Offset(0, -1).Value
LastRow = ActiveCell.Offset(-1, -1).Value
For Each i In Range("ProcessID")
If ThisRow = 0 Then
Exit Sub
ElseIf ThisRow > LastRow Then
ActiveCell.Value = ActiveCell.Offset(0, -1).Value + 1
Else
ActiveCell.Value = 1
End If
Debug.Print ActiveCell.Value
Next i
End Sub
>更新: 这是电子表格的屏幕截图;希望这有助于:
答案 0 :(得分:2)
您正在循环使用同一组单元格,因为您永远不会更改循环中的活动单元格。您还需要为每一行重新计算ThisRow和LastRow的值,因此需要将其包含在循环中。
Sub DataSort()
Dim i As Range, ThisRow As Integer , LastRow As Integer
' Set the initial active cell and first process number
Range("C26").Value = 1
Range("C27").Activate
' Loop through each cell in the Process column
For Each i In Range("ProcessID")
' Load the value of this row and the last row
ThisRow = ActiveCell.Offset(0, -1).Value
LastRow = ActiveCell.Offset(-1, -1).Value
' Check if we are at the change of a project - update process number
If ThisRow = 0 Then
Exit Sub
ElseIf ThisRow > LastRow Then
ActiveCell.Value = 1
Else
ActiveCell.Value = ActiveCell.Offset(0, -1).Value + 1
End If
' Move the active cell down one row
ActiveCell.Offset(1,0).Activate
Next i
End Sub
注意:我没有测试过这段代码。
但是,您的代码不会接近i
变量。使用它,我们不需要使用ActiveCell
Sub DataSort()
Dim i As Range, ThisRow As Integer , LastRow As Variant
' Loop through each cell in the Process column
For Each i In Range("ProcessID")
' Load the value of this row and the last row
ThisRow = i.Offset(0, -1).Value
LastRow = i.Offset(-1, -1).Value
' Check if we are at the change of a project - update process number
If ThisRow = 0 Then
Exit Sub
' First Row of Data
ElseIf LastRow = "Project ID" Then
i.Value = 1
'Change of Project - reset Process ID
ElseIf ThisRow > LastRow Then
i.Value = 1
'Same Project so increase the Process ID
Else
i.Value = i.Offset(-1, 0).Value + 1
End If
' Move the active cell down one row
Next i
End Sub
我认为在检查ThisRow是否大于最后一行时,您可能已经交换了逻辑 - 这应该意味着项目有更改,因此请重置进程ID号。