我有代码,每次按命令按钮时都会插入一个新行。但是,我想更改代码,以便每次按下命令按钮时,都将以“ 1”开头的值插入D列(在创建新行的行中)。当再次按下按钮并再次插入新行时,例如,如果将先前的行插入第9行,则D10中将出现“ 2”。
当前,我有只添加新行的代码,并粘贴了一些我需要的格式/值。
`Private Sub CommandButton2_Click()
Dim lRow As Long
Dim lRsp As Long
On Error Resume Next
lRow = Selection.Row()
lRsp = MsgBox("Insert New row above " & lRow & "?", _
vbQuestion + vbYesNo)
If lRsp <> vbYes Then Exit Sub
Rows(lRow).Select
Selection.Copy
Rows(lRow + 1).Select
Selection.Insert Shift:=xlDown
Application.CutCopyMode = False
Paste formulas and conditional formatting in new row created
Rows(lRow).PasteSpecial Paste:=xlPasteFormulas, Operation:=xlNone
i = 1
Range("D9").Value = i
End Sub`
答案 0 :(得分:0)
尝试:
Private Sub CommandButton2_Click()
Dim lRow As Long
Dim lRsp As Long
On Error Resume Next
lRow = Selection.Row()
lRsp = MsgBox("Insert New row above " & lRow & "?", _
vbQuestion + vbYesNo)
If lRsp <> vbYes Then Exit Sub
Rows(lRow).Copy 'REMOVED SELECT
Rows(lRow + 1).Insert Shift:=xlDown 'REMOVED SELECT
Application.CutCopyMode = False
'Paste formulas and conditional formatting in new row created
Rows(lRow).PasteSpecial Paste:=xlPasteFormulas, Operation:=xlNone
'i = 1 'REMOVED
'Range("D9").Value = i 'REMOVED
cells(lrow,4).value = Application.max(columns(4))+1 'ADDED
End Sub
此外,请尝试回过头来删除Select
和Selection
(如果适用)...请参阅How to avoid using Select in Excel VBA