【问题标题】:How to apply a VBA code to every page in a workbook? Mine does part of the code to every page, but only applies entire code to last page如何将 VBA 代码应用于工作簿中的每一页?我的将部分代码应用于每一页,但仅将整个代码应用于最后一页
【发布时间】:2018-08-31 21:36:45
【问题描述】:

我正在为 7 页的工作簿编写 VBA 代码。每个页面都有相同布局的库存数据。每只股票都有一个股票代码,并有一年中每一天的开盘、收盘、最高价、最低价和成交量数据。

我想要一个代码,它将为股票代码创建一个新列,并在这些列旁边创建年度变化、百分比变化和总交易量。

我希望能够运行一次宏并让它遍历工作簿的每一页。它将标记股票代码并计算每一页上的总库存量,但它只计算最后一页的年度变化和百分比变化。

This is what should happen on each page

This is what all but the last page look like

从图片中可以看出,它在每一页上都执行了部分代码,但只有最后一页才会应用整个代码。

谁能告诉我发生了什么或给我一个提示?由于 I 列和 L 列已经完成,宏肯定会在每一页中运行,但 J 和 K 列只在最后一页完成。

这是我正在使用的代码: 子股票()

    'This creates a "worksheet loop" that will automatically cycle through each page of the workbook and apply the macro thereto.
    Dim sheets As Worksheet
    For Each sheets In ThisWorkbook.Worksheets
        sheets.Activate

        'The proceeding lines create the column headings, as well as the headings horizontal headings used to show the greatest and least perchange change as well as the greatest total volume.
        Range("I1").Value = "Ticker"
        Range("J1").Value = "Yearly Change"
        Range("K1").Value = "Percent Change"
        Range("L1").Value = "Total Stock Volume"

        Range("P1").Value = "Ticker"
        Range("Q1").Value = "Value"
        Range("O2").Value = "Greatest % Increase"
        Range("O3").Value = "Greatest % Decrease"
        Range("O4").Value = "Greatest Total Volume"
        Range("O5").Value = "Least Total Volume"

        'This creates a variable which will identify and label the stock ticker.
        Dim stock_ticker As String

        'This creates a variable which will hold the total stock volume.
        Dim stock_volume As Double
        stock_volume = 0

        'This variable is used to input the ticker value in the correct cell in column I.  The ticker changes at a faster rate in column I than in column A.  This variable is therefore used to adjust the rate tickers are copied over from column A to column I.
        Dim j As Integer
        j = 2

        'This loop checks to see if the value in cell 'Ax" is equal to "Ay", where x and y are integers, and y=x+1.  If they are equal, Excel will recognize the tickers as being the same, and add the stock volume in the xth row to an accumlative total stock volume.  If Ax does not equal Ay, Excel will recognize that the ticker just changed.  When this happens, Excel will will add the last stock volume for the current ticker to the accumlative total stock volume; then it will identify what the current ticker is and insert this into column I, insert the total stock volume for that ticker into column L, then reset the total stock volume back to 0, then repeat the process.
        For i = 2 To 43398
            If Cells(i, 1).Value = Cells(i + 1, 1).Value Then
                stock_volume = stock_volume + Cells(i, 7).Value
            ElseIf Cells(i, 1).Value <> Cells(i + 1, 1).Value Then
                stock_volume = stock_volume + Cells(i, 7).Value
                Cells(j, 9).Value = Cells(i, 1).Value
                Cells(j, 12).Value = stock_volume
                j = j + 1
                stock_volume = 0
            End If
        Next i

        Dim stock_year_start As Double
        Dim stock_year_end As Double
        Dim stock_year_change As Double
        Dim stock_percent_change
        Dim k As Integer
        k = 2

        For i = 2 To 43398
            If Right(Cells(i, 2), 4) = "0101" Then
                stock_year_start = Cells(i, 3)
            ElseIf Right(Cells(i, 2), 4) = "1231" Then
                stock_year_end = Cells(i, 6)
                stock_year_change = stock_year_end - stock_year_start
                stock_percent_change = stock_year_change / stock_year_start
                Cells(k, 10).Value = stock_year_change
                If Cells(k, 10).Value > 0 Then
                    Cells(k, 10).Interior.ColorIndex = 4
                ElseIf Cells(k, 10).Value < 0 Then
                    Cells(k, 10).Interior.ColorIndex = 3
                End If
                Cells(k, 11).Value = stock_percent_change
                k = k + 1
            End If
        Next i

        Range("K1").EntireColumn.NumberFormat = "0.00%"

        'The proceeding lines automatically resize the cells created throughout the program to fit the content therein.
        Dim sheet_name As String
        sheet_name = ActiveSheet.Name
        Worksheets(sheet_name).Columns("I:L").AutoFit
        Worksheets(sheet_name).Columns("O:Q").AutoFit

    'This cycles to the next page in the workbook and repeats all the code hitherto.
    Next sheets

End Sub

【问题讨论】:

  • 不相关但使用 With Sheets ...... End With 这样您就可以删除 .Activate 以加快代码运行速度。查看信息here 如果注释掉的代码与问题无关,您可以edit 将其删除。
  • 您将需要按 F8 单步执行并查看代码与您预期的偏差。您只需为一张失败的工作表执行此操作。好像是逻辑问题。

标签: vba excel


【解决方案1】:

我会避免使用对象名称使变量变暗,因此请考虑将Dim sheets as Worksheet 中的Sheets 更改为ws

要遍历工作表并应用相同的逻辑,您需要执行以下操作:

Dim ws as Worksheet

For Each ws in Worksheets
    'Your code goes here with all objects referring to current ws like so:
     ws.Range(....
     ws.Cells(....
Next ws

不要激活工作表。相反,使用变量ws 限定每个对象(范围、单元格等)。我会使用查找和替换并将Rangews.Range 交换,然后将Cellsws.Cells 交换。在您的代码中看起来像这样。

Sub Stocks()

Dim stock_ticker As String, stock_volume As Double, j As Integer

Dim ws As Worksheet
For Each ws In Worksheets

ws.Range("I1").Value = "Ticker"
ws.Range("J1").Value = "Yearly Change"
ws.Range("K1").Value = "Percent Change"
ws.Range("L1").Value = "Total Stock Volume"
ws.Range("P1").Value = "Ticker"
ws.Range("Q1").Value = "Value"
ws.Range("O2").Value = "Greatest % Increase"
ws.Range("O3").Value = "Greatest % Decrease"
ws.Range("O4").Value = "Greatest Total Volume"
ws.Range("O5").Value = "Least Total Volume"

stock_volume = 0

Dim j As Integer
j = 2

For i = 2 To 43398
    If ws.Cells(i, 1).Value = ws.Cells(i + 1, 1).Value Then
        stock_volume = stock_volume + ws.Cells(i, 7).Value
    ElseIf ws.Cells(i, 1).Value <> Cells(i + 1, 1).Value Then
        stock_volume = stock_volume + ws.Cells(i, 7).Value
        ws.Cells(j, 9).Value = ws.Cells(i, 1).Value
        ws.Cells(j, 12).Value = stock_volume
        j = j + 1
        stock_volume = 0
    End If
Next i

【讨论】:

  • 我做了这些更改,但它没有做任何事情。每页都有股票代码和总库存量,但只有最后一页有年度和百分比变化,如提供的图片所示。
  • 如果它只在最后一页做东西,那么我会感觉更好,但看到它在每页上产生两列告诉我它正在循环所有页面。一切都在“工作页面循环”中,无论我在哪个页面上运行它,它都只是最后一个完全完成的页面。我看过它,休息一下然后回来,对我来说没有任何问题。你能想到为什么不管我在哪个页面上运行宏,它都是最后一页完成的原因吗?
  • 检查表格的格式。确保它们都是数字格式。我可以在一小时内看更多的东西
  • 尝试使用 F8 单步执行代码并检查变量的值
【解决方案2】:

我发现了问题。大多数股票在 12/30 结束,而我只检查 12/31。我将第二个循环重写为:

    For i = 2 To 43398
        If Right(workbook_sheet.Cells(i, 2), 4) = "0101" Then
            stock_year_start = workbook_sheet.Cells(i, 3)
        ElseIf Right(workbook_sheet.Cells(i, 2), 4) = "1231" Then
            stock_year_end = workbook_sheet.Cells(i, 6)
            stock_year_change = stock_year_end - stock_year_start
            stock_percent_change = stock_year_change / stock_year_start
            workbook_sheet.Cells(k, 10).Value = stock_year_change
        ElseIf Right(workbook_sheet.Cells(i, 2), 4) = "1230" Then
            stock_year_end = workbook_sheet.Cells(i, 6)
            stock_year_change = stock_year_end - stock_year_start
            stock_percent_change = stock_year_change / stock_year_start
            workbook_sheet.Cells(k, 10).Value = stock_year_change
        If workbook_sheet.Cells(k, 10).Value > 0 Then
                workbook_sheet.Cells(k, 10).Interior.ColorIndex = 4
        ElseIf workbook_sheet.Cells(k, 10).Value < 0 Then
                workbook_sheet.Cells(k, 10).Interior.ColorIndex = 3
        End If
        workbook_sheet.Cells(k, 11).Value = stock_percent_change
        k = k + 1
        End If
    Next i

我正在考虑一种更优雅的方法来计算年终股票价值。 43398 也是一个临时值,因为每个页面都有不同数量的股票要检查,我还在寻找一段时间来找到每个字段中的行数。

我会留在这里,以防有人想发表评论。

【讨论】:

    猜你喜欢
    • 2021-08-22
    • 2019-07-19
    • 2017-05-01
    • 2021-07-23
    • 1970-01-01
    • 1970-01-01
    • 2014-10-05
    • 2023-03-19
    • 1970-01-01
    相关资源
    最近更新 更多