【问题标题】:How do I keep initial value in a for loop?如何在 for 循环中保持初始值?
【发布时间】:2019-12-23 21:39:57
【问题描述】:

我正在尝试在 Excel VBA 中编写代码,并且我需要初始数值保持不变,直到字符串值发生变化,以便从初始数值中减去最后一个数值。字符串值改变后,需要一个新的初始数值。

更具体地说:
对于给定的股票代码,我需要保留年初的开盘价,并从年底的收盘价中减去它,以找到年度变化。当股票代码发生变化时,我需要新股票的新年初开盘价。不幸的是,我编写的 for 循环并没有保持相同的年初开盘价,而是从同一天的开盘价中减去年末收盘价(因为它们在同一行 i)。我不能硬编码开盘价,因为它需要在代码更改时更改。

代码如下:

'Loop through all stock trades
For i = 2 To LastRow

    ' Set opening price
    Dim Opening_Price As Double
    Opening_Price = Cells(i, 3).Value


    ' Check if we are still within the same ticker.
    If Cells(i + 1, 1).Value <> Cells(i, 1).Value Then

      ' Set the ticker name
      Ticker = Cells(i, 1).Value

      ' Print the ticker name in the Summary Table
      Range("I" & Summary_Table_Row).Value = Ticker

      ' Add or subtract closing price from first opening price
      Yearly_Change = Cells(i, 6).Value - Opening_Price

      ' Print the change in stock price in the Summary Table
      Range("J" & Summary_Table_Row).Value = Yearly_Change

      ' Calculate percent change from opening to closing price
      Percent_Change = (Yearly_Change / Opening_Price) * 100

      ' Print the percent change in the summary table
      Range("K" & Summary_Table_Row).Value = Percent_Change

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


    End If



Next i

【问题讨论】:

  • 不,每只股票的年初价格是该股票名称(股票代码)的第一行,工作表上有几个股票名称。您后来的回复(我接受了)回答了我的问题。谢谢。
  • 是的,我明白了。感谢您的点击。祝你好运。

标签: excel vba for-loop


【解决方案1】:

在for循环之外做:

' Set opening price
Dim Opening_Price As Double
Opening_Price = Cells(2, 3).Value

'Loop through all stock trades
For i = 2 To LastRow

【讨论】:

  • 当代码发生变化时,这是否适用于新的 Opening_Price?
  • @jason-hernandez-73 不,它没有,但 D Stanley 的答案是您的 LITERAL 问题的答案。您可能会考虑将问题改写为“如何在循环中保持一个值直到满足某个条件”,因为您不仅关心第一个价格,还关心所有未来的新股票/等。
【解决方案2】:

我想我看到了你的问题。您需要指定循环何时在 new “股票/股票行情”或诸如此类上。 if 语句将其切换为 TrueFalse 应该这样做(假设我正确理解您的问题)。

在下面查看您修改后的代码(我删除了与您的问题无关的项目)。

For i = 2 To LastRow

'Capture price if first of year
Dim stockPriceAlreadyCaptured As Boolean

    If stockPriceAlreadyCaptured = False Then
         'Set opening price
         Dim Opening_Price As Double
         Opening_Price = Cells(i, 3).Value

         'ensures no future prices captured until condition met.
         stockPriceAlreadyCaptured = True
    End If


    'Check if we are still within the same ticker.
    If Cells(i + 1, 1).Value <> Cells(i, 1).Value Then

        '...unrelated code excluded

        'switch your condition back to capture next price line.
        stockPriceAlreadyCaptured = False

    End If

Next i

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-03
    • 2012-01-02
    相关资源
    最近更新 更多