【问题标题】:How to find the first and last values in a conditional loop in VBA如何在VBA的条件循环中找到第一个和最后一个值
【发布时间】:2019-12-22 04:55:36
【问题描述】:

我正在创建一份关于股票指数的报告,我应该在该报告中获得市场上每只股票的年度开盘价和收盘价净变化。我有面板数据,一年中的每一天都对每只股票进行观察。我目前也在使用条件 for 循环来创建年度总量。我有什么办法可以在条件中选择第一个和最后一个值来选择股票的年度开盘价和收盘价?第 1 列是股票的名称,因此我将其用作股票何时变化的条件。这是我到目前为止所拥有的。第 4 列是每日开放,第 5 列是每日关闭观察。

'Establish variables
Dim ticker As String
Dim change_price As Double
Dim change_percent As Double
Dim volume As Double
Dim annual_open As Double
Dim annual_close As Double


' Keep track of each stock the summary table
  Dim Summary_Table_Row As Integer
  Summary_Table_Row = 2


For i = 2 To 800000
    If Cells(i + 1, 1).Value <> Cells(i, 1).Value Then
        'create a list of stocks
        ticker = ticker + Cells(i, 1).Value
        'total volume for each stock
        volume = volume + Cells(i, 7).Value
        'annual_open = ?
        'annual_close = ?

         ' Print the stock in the Summary Table
      Range("H" & Summary_Table_Row).Value = ticker

      ' Print the stock volume to the Summary Table
      Range("I" & Summary_Table_Row).Value = volume

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

      'reset the stock name
      ticker = ""

      ' Reset the Brand Total
      volume = 0


    ' If the cell immediately following a row is the same stock...
    Else

      ' Add to the stock total
      volume = volume + Cells(i, 7).Value


    End If
Next i

【问题讨论】:

  • Query the data-range with sql 通过 sql-statementt(Sum()、Count()、Min()、Max() 按股票分组)获取这些值。避免使用对 ActiveSheet 的隐式引用(例如,在没有明确定义工作表(和工作簿)的情况下使用 Cells()、Range()!查看RubberduckVBA 以获取相关提示。

标签: excel vba loops if-statement


【解决方案1】:

如果您添加数据布局的屏幕截图会更清楚。另外,需要澄清一下——第一个和最后一个值是什么?这些是最小值和最大值吗?

或者那些是在适当的列中第一次“打开”和最后一次“关闭”?如果是这样,您可以尝试这样做:

' This will be first stock's open
annual_open = Cells(2, 4).Value

For i = 2 To 800000

    If Cells(i + 1, 1).Value <> Cells(i, 1).Value Then

        '[Your code]

        ' Here, i is the last row of the current stock, so assign it
        annual_close = Cells(i, 5).Value

        '''''''''''''''''''''''''''''''''''''''''''''''''
        ' Handler for your "annual_open" and "annual_close"
        ' because lines after will overwrite "annual_open" with new value

        '   [Add code here]

        '''''''''''''''''''''''''''''''''''''''''''''''''

        ' Here, i + 1 is the first row of next stock
        ' so assign it
        annual_open = Cells(i + 1, 4).Value

        '[Your code]

    Else
        ' If stock is the same do nothing to "annual_open" and "annual_close"
        '[Your code]



    End If
Next i

【讨论】:

    猜你喜欢
    • 2022-01-03
    • 1970-01-01
    • 2018-08-17
    • 1970-01-01
    • 1970-01-01
    • 2016-02-22
    • 1970-01-01
    • 2019-11-28
    • 2020-12-19
    相关资源
    最近更新 更多