Including a counter within an advanced filter

2019-08-17 17:04发布

I have an advanced filter set up and separate to that subroutine I have another subroutine that loops through the filter results and places the value into a text box. That all works fine but I'm trying to include a counter so for every result that's being displayed the counter goes up, and then when the criteria changes and new results are found it goes back to 1 and counts again from there.

Public Sub GetNextResult()
    FilterData

    Dim ws As Worksheet
    Set ws = ThisWorkbook.Worksheets("Database")

    Dim header As String
    header = "txtbox1"

    Dim LastRow As Long
    LastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row

    Dim DataRange As Range
    Set DataRange = ws.Range("A5", "H" & LastRow) 

    Dim FilteredData As Range
    Set FilteredData = DataRange.Resize(ColumnSize:=1).SpecialCells(xlCellTypeVisible)

    If CurrentRow + 1 > FilteredData.Cells.Count Then
        CurrentRow = 1
    End If

    CurrentRow = CurrentRow + 1
    Dim i As Long
    Dim cell As Variant

    Dim counter As Integer
    counter = 1

    For Each cell In FilteredData
        i = i + 1
        If i = CurrentRow Then
            Call ShowAll

            TextboxName = "txtbox1"
            ActiveSheet.Shapes(TextboxName).DrawingObject.Text = cell.Offset(0, 2)

            TextboxName2 = "txtbox2"
            ActiveSheet.Shapes(TextboxName2).DrawingObject.Text = cell.Offset(0, 3)

            TextboxName3 = "Cardcounter"
            ActiveSheet.Shapes(TextboxName3).DrawingObject.Text = counter

            If ActiveSheet.Shapes(TextboxName).DrawingObject.Text = header Then
                'MsgBox "header detected"
                'Exit Sub
                Call GetNextResult
            End If

            Call quick_artwork

            counter = counter + 1

        Else
            Call ShowAll
            'Exit Sub
            'MsgBox "No data found matching this criteria"
            'TextboxName = "txtbox1"
            'ActiveSheet.Shapes(TextboxName).DrawingObject.Text = "No data found matching this criteria"

            'TextboxName2 = "txtbox2"
            'ActiveSheet.Shapes(TextboxName2).DrawingObject.Text = ""
        End If
    Next cell

End Sub

So I've put counter = 1 before the for loop and then within the for loop I've put counter = counter + 1 and I thought that would work but it doesn't. It doesn't show an error, but the number doesn't change.

Any help would be appreciated!

标签: excel vba
1条回答
放我归山
2楼-- · 2019-08-17 18:05

You could declare counter outside the GetNextResult() routine, and set it to 1 before calling the GetNextResult() routine.

Dim counter As Integer

Sub SomeOtherSubCallingGetNextResult()
    ...
    counter = 1
    GetNextResult
    ...
End sub
查看更多
登录 后发表回答