在Excel中引用错误的行的button
我有这块代码,它可以帮助一个button识别它是哪一行。但是,当我隐藏上面的行,button引用该隐藏行。
例如:如果button位于第20行,并且隐藏第19行,则单击该button将返回第19行。如果我隐藏了第19行和第18行,则该button将返回第18行。
这真的很奇怪。
这是我用来创buildbutton的块:
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
下面是一个返回单击button的行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
你的时间和帮助表示赞赏。
你可以使用这个function:
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
它检查TopLeftCell
方法返回的单元格是否不在隐藏行中。 如果是,则函数尝试下面的单元格等等,只要它从未隐藏的行中find单元格即可。
你可以在你的子程序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