我正在学习VBA,我想缩短我编写的代码。我想复制一个变量行,并将其粘贴到上面的行,然后粘贴到第二列。理想情况下,它也将行(-1,2)和(2,1)粘贴在一起,因为它在Excel中是断行。
我现在有以下代码:
Sub Clean()
Dim i As Long
Dim x As Long
For i = 2 To 48987
x = i - 1
If IsNumeric(Cells(i, 1)) = True Then
'Do nothing
Else
Cells(x, 2) = Cells(x, 2) + Cells(i, 1)
Cells(x, 3) = Cells(i, 2)
Cells(x, 4) = Cells(i, 3)
Cells(x, 5) = Cells(i, 4)
Cells(x, 6) = Cells(i, 5)
Cells(x, 7) = Cells(i, 6)
Cells(x, 8) = Cells(i, 7)
Cells(x, 9) = Cells(i, 8)
Cells(x, 10) = Cells(i, 9)
Cells(x, 11) = Cells(i, 10)
Cells(x, 12) = Cells(i, 11)
Cells(x, 13) = Cells(i, 12)
Cells(x, 14) = Cells(i, 13)
Cells(x, 15) = Cells(i, 14)
Cells(x, 16) = Cells(i, 15)
Rows(i).Delete
End If
Next i
End Sub
我假设您想缩短重复的Cells(x, 3) = Cells(i, 2)
位。可以通过以下方法轻松地完成此操作:将第一个计算添加到第二个中,然后将行的其余部分复制如下:
Sub Clean2()
Dim i As Long
For i = 2 To 48987
If Not IsNumeric(Cells(i, 1)) = True Then
Cells(i - 1, 2) = Cells(i - 1, 2) + Cells(i, 1)
Range(Cells(i, 2), Cells(i, 15)).Copy Range(Cells(i - 1, 3), Cells(i - 1, 16))
Rows(i).Delete
End If
Next i
End Sub
[请注意,不需要变量x
,因为i-1
同样有效,并且不需要任何读取您的代码的人来查找变量x
的作用。但这可能是个人喜好。
或者,您可以添加另一个循环,但这可能不那么快(未经测试)
For j = 2 To 15
Cells(i - 1, j + 1) = Cells(i, j)
Next j