如何在for循环中保留初始值?

问题描述 投票:1回答:2

我正在尝试在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
2个回答
0
投票
我想我看到了你的问题。您需要指定循环何时在

new“股票/股票行情指示器”上或其他位置。可以将其切换为ifTrueFalse语句(假设我正确理解了您的问题)。

请参阅下面的修改后的代码(我删除了与您的问题无关的项目。)>

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


3
投票
在for循环之外执行:
© www.soinside.com 2019 - 2024. All rights reserved.