excel vba 宏问题

来源:百度知道 编辑:UC知道 时间:2024/06/07 01:47:13
关于程序出错
Private Sub CommandButton1_Click()

For i = 1 To 10000
If Cells(i, 1) < Cells(i, 2) Then
Cells(i, 2).Select Selection.insert Shift:=xlDown

ElseIf Cells(i, 1) > Cells(i, 2) Then
Cells(i, 1).Select _
Selection.insert Shift:=xlDown _
else
End If
Next i
End Sub
这段宏有什么问题?我刚开始学习编程,很多不懂,大家多多指教

这段宏中
Cells(i, 2).Select Selection.insert Shift:=xlDown
应当分成两句
Cells(i, 2).Select
Selection.insert Shift:=xlDown
还有
Cells(i, 1).Select _
Selection.insert Shift:=xlDown _
也是一样

主要问题还有
插入空单元格后,你的i变量值没有调整,按原有步长加1后,定位会是新插入的空单元格下的那个格,也就是你刚刚定位过的那个

Private Sub CommandButton1_Click()

For i = 1 To 10000
If Cells(i, 1) < Cells(i, 2) Then
Cells(i, 2).Insert Shift:=xlDown

ElseIf Cells(i, 1) > Cells(i, 2) Then
Cells(i, 1).Insert Shift:=xlDown
Else
End If
Next i
End Sub