我正在编写一个脚本,如果Sheet2的M列中的任何单元格更改为“Special”,则该单元格的行号将复制到Sheet12的B列。如果行号在列中最大,则将其添加到末尾。如果没有,则从模板行复制一行并插入(与行号一起),以便列B中的所有数字都是连续的。
用于插入/复制中间序列号的代码效果很好,但是无法在最后添加最大数字。我没有收到错误;它只是不工作。这是代码(在Sheet2中):
If Target.column = 13 Then
Dim cell As Integer
Dim l As Long
cell = ActiveCell.Row
If ActiveCell.Value = "Special" Then
With Sheet12
For l = .Cells(rows.count, "B").End(xlUp).Row To 3 Step -1
If .Cells(l, 2).Value = vbNullString And .Cells(l - 1, 2).Value < cell Then
Sheet12.Cells(l, 2).Value = cell
ElseIf .Cells(l, 2).Value > cell And .Cells(l - 1, 2).Value < cell Then
Sheet12.Cells(l, 2).EntireRow.Insert shift:=xlDown
Sheet12.Range("A3").EntireRow.Copy Sheet12.Cells(l, 2).EntireRow
Sheet12.Cells(l, 2).Value = cell
End If
Next
End With
End If
End If
需要更改的代码部分是If .Cells(l, 2).Value = vbNullString And .Cells(l - 1, 2).Value < cell Then
。我已经尝试了不同的方法来检查空单元格(即isempty(),使用“”等)并使用工作表名称以不同方式引用单元格。有任何想法吗?在此先感谢您的帮助!
答案 0 :(得分:0)
问题是循环是从B列中的第一个非空单元格开始的,因此该值不可能是vbnullstring。以下是工作代码:
If Target.column = 13 Then
Dim cell As Long
Dim l As Long
cell = ActiveCell.Row
If ActiveCell.Value = "Special" Then
If Sheet12.[B4].Value = vbNullString Then
Sheet12.[B4].Value = cell
Else
With Sheet12
For l = .Cells(rows.count, "B").End(xlUp).Row + 1 To 4 Step -1
If .Cells(l, 2).Value = vbNullString And .Cells(l - 1, 2).Value < cell Then
Sheet12.Cells(l, 2).Value = cell
Exit For
ElseIf .Cells(l - 1, 2).Value > cell And .Cells(l - 2, 2).Value < cell Then
Sheet12.Cells(l - 1, 2).EntireRow.Insert shift:=xlDown
Sheet12.Range("A3").EntireRow.Copy Sheet12.Cells(l - 1, 2).EntireRow
Sheet12.Cells(l - 1, 2).Value = cell
Exit For
End If
Next
End With
End If
ElseIf ActiveCell.Value = vbNullString Or ActiveCell.Value = "Normal" Then
With Sheet12
For l = .Cells(rows.count, "B").End(xlUp).Row To 4 Step -1
If .Cells(l, 2).Value = cell Then
.Cells(l, 2).EntireRow.Delete
End If
Next
End With
End If
End If
注意:这不是最有效的执行方式,如评论中所述;但是,如果有人遇到类似的问题,我想解释一下这个问题。