【发布时间】:2018-05-30 02:08:43
【问题描述】:
这是场景。当在工作表中插入一行时,会出现一个 worksheet_change 事件,该事件会调用一个 sub,在插入的行上插入五对按钮。单击其中一个按钮时,它会运行一个子程序,该子程序发出一个 MsgBox,显示按钮的 TopLeftCell.Row 和 Column。可以插入多行,每行有五组按钮(总共十个)。可以随时选择任意行中的任意按钮。
我看到的是,在我打开工作簿并按下其中一个按钮后,MsgBox 始终显示正确的列,但无论我按下哪一行按钮,它似乎都“卡在”某一特定行'我点击实际上是。如果我删除它卡在的行,那么它会“卡”在不同的行上(只要它还包含按钮)。但并非所有按钮都会卡在同一行上。
如果我将两个相邻行的按钮“卡”在同一行上,复制到另一个位置,这些按钮仍然卡在一起,除了在不同的行上。
按钮集合似乎有问题。如果我保存工作簿,问题就会消失。如果我插入一个新行并且 Add_Buttons 例程再次运行,问题会再次出现,但涉及不同的行。所以我的按钮例程可能会留下一些暂时的东西,当我进行保存时会被清除。
这是构建按钮的代码。
Public activeWS As Worksheet
Public activeRG As Range
Public Sub Add_Buttons(ByVal myRow As Long)
'Add the five sets of Submit IM and Submit Webins buttons to a new row. The code
'uses named ranges to locate the cells where the buttons should be added so that
'new columns can be added to the spreadsheet without requiring changes to the code.
'The headings must be labeled 'IM#' and 'Webins#'.
Dim i As Long
Dim t As Range
Dim btn As Button
'In each range, place the button below the column label.
Application.ScreenUpdating = False
For i = 1 To 5
Set activeWS = Sheet1
Set activeRG = activeWS.Range("Scan" & i & "_Hdngs")
'The start of the range plus the position of the specified column in
'the range gives the absolute column location to add the button
'Create the Submit IM button
nCol = activeRG.Cells(1, 1).Column + findCol("IM#", activeRG) - 1
Set t = activeWS.Range(Cells(myRow, nCol), Cells(myRow, nCol))
Set btn = activeWS.Buttons.Add(t.Left, t.Top, t.Width, t.Height)
With btn
.OnAction = "Create_Primary_IM"
.Caption = "Submit IM"
.Name = "BtnIM" & myRow & i
.Font.Size = 10
End With
'Create the Submit Webins button
nCol = activeRG.Cells(1, 1).Column + findCol("Webins#", activeRG) - 1
Set t = activeWS.Range(Cells(myRow, nCol), Cells(myRow, nCol))
Set btn = activeWS.Buttons.Add(t.Left, t.Top, t.Width, t.Height)
With btn
.OnAction = "Create_Primary_WAS"
.Caption = "Submit Webins"
.Name = "BtnWAS" & myRow & i
.Font.Size = 10
End With
Next i
Application.ScreenUpdating = True
End Sub
这是按钮执行的代码:
Public Sub Create_Primary_IM()
MsgBox ("Row, Col of pressed button: " & ActiveSheet.Shapes(Application.Caller).TopLeftCell.Row _
& ", " & ActiveSheet.Shapes(Application.Caller).TopLeftCell.Column)
End Sub
Public Sub Create_Primary_WAS()
MsgBox ("Row, Col of pressed button: " & ActiveSheet.Shapes(Application.Caller).TopLeftCell.Row _
& ", " & ActiveSheet.Shapes(Application.Caller).TopLeftCell.Column)
End Sub
【问题讨论】:
-
欢迎来到SO,我找不到明确的问题,你能修改你的帖子并定义一个要解决的问题吗?请阅读>How to Ask
-
在行上插入五对按钮 哪一行?被插入?
-
JohnyL - 是的。 Worksheet_Change 事件使用目标范围来确定应将按钮添加到哪一行。
-
David G. - 我的问题是:为什么 TopLeftCell.Row 属性的行为是这样的?插入后不正确,然后在保存工作簿后更正。按钮每次都在同一行。我知道这不是一个明确定义的问题。我会尽量让原来的问题更清楚。
-
您遗漏了关键部分:返回行并显示您的 MsgBox 的函数或子。