0

in my Sheet I'm trying to create VBA code which will allow me to: 1)add specific (constant) number of rows above clicked button 2)format them in a proper way

What I know is every object (shape) stores value of TopLeftCell which from where I can get row number. I can simply add rows(s) above or belowe specific row in my Sheet

ActiveSheet.Rows(21).Insert shift:=xlShiftDown, CopyOrigin:=xlFormatFromLeftOrAbove

I would like to create where function addNewRows2 is unviersal for any button in the ActiveSheet - it gets the position of button(the row number) and adds row(s) above it

Private Sub CommandButton2_Click()
addNewRows2
End Sub

Function addNewRows2()
   Application.ActiveSheet.Buttons(Application.Caller).TopLeftCell.EntireRow.Insert 
End Function
1
  • 1
    What is your question / what is the issue? Commented Jul 27, 2020 at 17:34

1 Answer 1

2

In Class module cButton put the following lines

Public WithEvents MyButton As MSForms.CommandButton

Private Sub MyButton_Click()
    ActiveSheet.Rows(MyButton.TopLeftCell.Row).Insert
End Sub

Then in standard module put the code

Dim TheCommandButtons() As New cButton

Sub Activate_ActiveX_CommandButtons()
    Dim shp As Shape, iButtonCount As Long
    ReDim TheCommandButtons(1 To 1)
    iButtonCount = 0
    For Each shp In ActiveSheet.Shapes
        If shp.OLEFormat.Object.OLEType = xlOLEControl Then
            iButtonCount = iButtonCount + 1
            ReDim Preserve TheCommandButtons(1 To iButtonCount)
            Set TheCommandButtons(iButtonCount).MyButton = shp.OLEFormat.Object.Object
        End If
    Next shp
End Sub

Now run the code Activate_ActiveX_CommandButtons, after that you can use any command button to do the task of inserting a row above the button.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.