Amo*_*afa 5 excel vba module button
我有这个代码块,它帮助按钮识别它所在的行.但是,当我隐藏上面的行时,按钮引用该隐藏的行.
例如:如果按钮在第20行并且我隐藏第19行,则单击该按钮将返回第19行.如果我隐藏第19行和第18行,则该按钮返回第18行.
这真的很奇怪.
这是我用来创建按钮的块:
Sub AddButtons()
Dim button As button
Application.ScreenUpdating = False
Dim st As Range
Dim sauce As Integer
For sauce = 10 To Range("F" & Rows.Count).End(xlUp).Row Step 1
Set st = ActiveSheet.Range(Cells(sauce, 11), Cells(sauce, 11))
Set button = ActiveSheet.Buttons.Add(st.Left, st.Top, st.Width, st.Height)
With button
.OnAction = "GoToIssue.GoToIssue"
.Caption = "Go To Source"
.Name = "Button" & sauce
End With
Next sauce
Application.ScreenUpdating = True
End Sub
Run Code Online (Sandbox Code Playgroud)
这里是一个块,它会在点击按钮后返回按钮的行ID:
Sub GoToIssue()
Dim b As Object
Dim myrow As Integer
Dim hunt As String
Set b = ActiveSheet.Buttons(Application.Caller)
With b.TopLeftCell
myrow = .Row
End With
hunt = Worksheets("Dummy").Range("F" & myrow).Value
'MsgBox hunt
End Sub
Run Code Online (Sandbox Code Playgroud)
感谢您的时间和帮助.
您可以使用此功能:
Public Function FindButtonRow(btn As Object) As Long
Dim cell As Excel.Range
'-------------------------------------------------
Set cell = btn.TopLeftCell
Do While cell.EntireRow.Hidden
Set cell = cell.Offset(1, 0)
Loop
FindButtonRow = cell.row
End Function
Run Code Online (Sandbox Code Playgroud)
它检查方法返回的单元格TopLeftCell是否不在隐藏行中。如果是,该函数会尝试下面的单元格,依此类推,只要它找到来自未隐藏行的单元格。
GoToIssue您可以像这样在子例程中使用它:
Sub GoToIssue()
Dim b As Object
Dim myrow As Integer
Dim hunt As String
Set b = ActiveSheet.Buttons(Application.Caller)
myrow = FindButtonRow(b)
hunt = Worksheets("Dummy").Range("F" & myrow).Value
'MsgBox hunt
End Sub
Run Code Online (Sandbox Code Playgroud)