简体   繁体   English

VBA excel 宏 - 在按钮上方添加行

[英]VBA excel macro - add rows above button

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在我的工作表中,我正在尝试创建 VBA 代码,这将允许我:1)在单击的按钮上方添加特定(恒定)行数 2)以适当的方式格式化它们

What I know is every object (shape) stores value of TopLeftCell which from where I can get row number.我所知道的是每个 object(形状)都存储 TopLeftCell 的值,我可以从中获取行号。 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我想创建 function addNewRows2 对于 ActiveSheet 中的任何按钮都不适用的地方-它获取按钮的 position (行号)并在其上方添加行

Private Sub CommandButton2_Click()
addNewRows2
End Sub

Function addNewRows2()
   Application.ActiveSheet.Buttons(Application.Caller).TopLeftCell.EntireRow.Insert 
End Function

In Class module cButton put the following lines在 Class 模块cButton中放入以下几行

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.现在运行代码Activate_ActiveX_CommandButtons ,之后您可以使用任何命令按钮来执行在按钮上方插入一行的任务。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM