我正在尝试在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
new“股票/股票行情指示器”上或其他位置。可以将其切换为if
或True
的False
语句(假设我正确理解了您的问题)。
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