VBA-在每个工作表中执行循环

时间:2018-11-19 16:22:17

标签: excel vba loops worksheet

预先感谢所有帮助;我是一个初学者,非常感谢您的宝贵时间!

我有一个VBA脚本,可以在第一部分中完美执行(在每个工作表中添加两列。

但是,脚本的第二部分(汇总每个工作表中新列中的总数)仅在第一个选项卡上执行,而不在其他选项卡上执行。

我知道可以使用SUMIFs代替VBA来完成,但是我现在正在学习VBA,必须使用它。

代码如下:

Sub test()
    Dim wb As Workbook: Set wb = ThisWorkbook
    Dim ws As Worksheet: Set ws = ThisWorkbook.Sheets(1)
    Dim ticker_name As String
    Dim ticker_total As Double
    Dim summary_table_Row As Double
    Dim i As Double

    ticker_total = 0
    summary_table_Row = 2

    For Each ws In wb.Worksheets
        'Create columns for ticker totals
        ws.Range("I1").Value = "Ticker"
        ws.Range("J1").Value = "Total Stock Volume"

        'Autofit to display data
        '  ws.Columns("A:J").AutoFit

        'THE SECTION BELOW IS THE ONE THAT WILL NOT LOOP THROUGH EACH TAB.
        '_________________________________________________________________

        'Do While IsEmpty(ws.Cells(i + 1, 1)) = True
        For i = 2 To 99999
            ' Check if we are still within the same credit card brand, if it is not...
            If ws.Cells(i + 1, 1).Value <> ws.Cells(i, 1).Value Then
              ' Set the Brand name
              ticker_name = ws.Cells(i, 1).Value

              ' Add to the Brand Total
              ticker_total = ticker_total + ws.Cells(i, 7).Value

              ' Print the Credit Card Brand in the Summary Table
              ws.Range("I" & summary_table_Row).Value = ticker_name

              ' Print the Brand Amount to the Summary Table
              ws.Range("J" & summary_table_Row).Value = ticker_total

              ' Add one to the summary table row
              summary_table_Row = summary_table_Row + 1

              ' Reset the Brand Total
              ticker_total = 0

            ' If the cell immediately following a row is the same brand...
            Else
              ' Add to the Brand Total
               ticker_total = ticker_total + ws.Cells(i, 7).Value
            End If
        Next i
        'Loop
    Next ws
End Sub

0 个答案:

没有答案