【发布时间】: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
【问题讨论】:
-
不,每只股票的年初价格是该股票名称(股票代码)的第一行,工作表上有几个股票名称。您后来的回复(我接受了)回答了我的问题。谢谢。
-
是的,我明白了。感谢您的点击。祝你好运。