简体   繁体   中英

Looping through a large spreadsheet row by row that is filtered and has hidden rows. How do I copy the previous visible rows and make a table?

My program works like this:

I have a running total of dollar amounts (from $0 to $260m). Each row has data related to the cost. My objective was to extract each row when it goes up by a budget increment eg $5mil, so I would extract the row that has $4.9mil then $9.9mil then $14.9mil (to stay little bit under $5mil) in the running total column. To do this I created a new column that subtracts $5mil from the column with the running total. Starting from $0 running total will give me a negative number until the running total is bigger than the budget increment of $5mil which will then give me a positive number. When it reaches this positive number the running total will be $5+mil but I would want something like $4.9mil. (When it reaches a positive number I add $5mil to the budget increment. I need to extract the previous (last) negative number.

Here is an annotated picture:

在此处输入图片说明

Here is the code I have so far:

Private Sub CommandButton2_Click()

    Dim number_of_rows As Long
    Dim budget_increment As Long
    Dim rng_data As Range
    Dim prev_visible_row As Object

    number_of_rows = Cells(Rows.Count, 5).End(xlUp).Row
    Set rng_data = Range("I2:I" & number_of_rows)
    budget_increment = 5000000

    For i = 180 To number_of_rows
        Range("I" & i & ":I" & i) = Range("H" & i & ":H" & i) - budget_increment
        If Range("I" & i).Value > 0 Then
            budget_increment = budget_increment + 5000000
            'find out how to copy the last visible row and paste onto new sheet my attempt at solving this (did not work):
            AutoFilter.Range.Offset(i - 1).SpecialCells(xlCellTypeLastCell).Cells.Copy
            'Sheets("Sheet3").Range("T1").Select
            'Sheets("Sheet3").Paste
        End If
    Next
    Application.ScreenUpdating = True
End Sub

Try adding this to the top Dim inc, counter As Integer: counter = 0

and change the If Range("I" & i).Value > 0 Then to :

    If Range("I" & i).Value < Range("I" & (i-1)).Value Then
        For inc = 1 to 999
            If Rows(i-inc).RowHeight > 0 And Range("I" & (i-inc)).Value < 0 Then
                Sheets("Sheet3").Range("A” & (counter + 1) & ":Z" & (counter + 1)).Value = Range("A" & (i-inc) & ":Z" & (i-inc)).Value ' Or something
                counter = counter + 1
                Exit For
            End If
        Next
    End If

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