问题陈述: 我使用Macro在电子表格上动态放置了按钮。当我点击按钮时,它会显示按钮的位置。在宏内部,我还插入了更改按钮位置的新行。但是当我点击由于插入新行而改变其位置的相同按钮时,它仅显示在创建期间存储的旧位置。
如何让按钮每次都显示新位置,同时考虑到可以随时添加新行?
我的代码:
Sub AddWithin(ByRef pr As Integer, ByRef pc As Integer, ByRef parentCont As Integer)
MsgBox "Row=" & pr & " Column=" & pc
Dim r As Integer 'row number
Dim c As Integer 'column number
Dim cn As String 'column name
Dim i As Integer 'looping var
Dim ContNum As Integer 'value taken from another sheet that keeps count of number of buttons added to the worksheet
Dim nr As Integer 'New Row Number for new button
nr = pr + 2
'Inserting 2 rows below parent container and shifting all cells down
Rows(nr).Insert Shift:=xlShiftDown
Rows(nr).Insert Shift:=xlShiftDown
'Taking the last container number (ContNum) from Sheet2, incrementing it by 1 and adding it back to the Sheet2
ContNum = Worksheets("Sheet2").Range("A1").Value + 1
Worksheets("Sheet2").Range("A1").Value = ContNum
'New position for adding a new button
r = nr
c = pc + 1
'Adding a + button to the 1st column
Dim btn As Button
Application.ScreenUpdating = False
Dim t As Range
Set t = ActiveSheet.Range(Cells(r, c), Cells(r, c))
Set btn = ActiveSheet.Buttons.Add(t.Left, t.Top, t.Width, t.Height)
With btn
.OnAction = "'AddWithin " & btn.TopLeftCell.Row & "," & btn.TopLeftCell.Column & "," & ContNum & " '"
.Caption = "+"
.Name = "Button" & ContNum
End With
Application.ScreenUpdating = True
End Sub
输出屏幕截图:
Position of button before adding new rows Position of button after adding new rows