简体   繁体   中英

How can I get buttons to move when I sort a list?

I have a spreadsheet with buttons for each row of data. One column contains values that can be sorted in ascending order and another column contains a filter that can filter out rows by name. When I run my Sort and Filter macro that accomplishes both of these tasks, the button visibly remains in the same row, but when I click the button to do specific tasks based on the button's row it has moved. I am really lost with this one so I'll include the code that sorts and filters data, along with the code that gets the clicked button's row and column. The buttons' properties are set to move and size with the cell. The button turns a dark grey when its row address has changed for some reason. I have looked around and can't seem to find a solution to this problem... Sorry if I missed something somewhere and thanks in advance for the help.

Code for identifying clicked button's row and column...

Dim b  As Object

Set b = ActiveSheet.Buttons(Application.Caller)

With b.TopLeftCell
    task_row = .Row
    button_col = .Column
End With

Code that sorts and filters rows...

Sub Filter_List()
    ActiveSheet.Range(Cells(start_data_row - 1, 1), Cells(start_data_row +   num_tasks - 1, last_col)).AutoFilter _
        Field:=name_col, Criteria1:=task_owner
End Sub

Sub Sort_List()
    Range(Cells(start_data_row, 1), Cells(start_data_row + num_tasks - 1, last_col)).Sort _
        key1:=Range(Cells(start_data_row, days_left_col), Cells(start_data_row, days_left_col)), _
        order1:=xlAscending
    Worksheets(sht_name).Range(Cells(start_data_row - 1, days_left_col), Cells(start_data_row + num_tasks - 1, days_left_col)).AutoFilter _
        Field:=days_left_col, Criteria1:="<" & max_days, Operator:=xlAnd
End Sub

Rather than use all those buttons, why not use a Private Sub based on a cell selection – especially if, as you say, the same code is run (albeit for different lines) irrespective of which button is clicked? The following sub works if any cell in column A in the used range is selected. Just put your code where I suggest – then you can dispense with all the buttons.

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

Dim LastRow As Long

LastRow = ActiveSheet.UsedRange.Rows(ActiveSheet.UsedRange.Rows.Count).Row

    If Not Intersect(Range("A1:A" & LastRow), Target) Is Nothing Then

      ‘Put your generic code here

    End If

End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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