Динамическое вычисление значений при изменении ячейки VBA

Таким образом, я работаю с электронной таблицей, в которой есть прямая трансляция цен акций. Я записал это в таблицу, чтобы при обновлении цены обновлялась стоимость позиции и вычислялась новая общая стоимость портфеля.

Итак, у меня есть 5 основных заголовков: игроки, код акции, единицы, текущая цена, стоимость.

Сейчас этот код работает, но частично. Когда цена обновляется, она не обновляет значение автоматически, если я не иду туда и обратно из ячейки.

Private Sub Worksheet_SelectionChange(ByVal target As Range)
Dim i As Integer, j As Integer, m As Integer, t As Integer
Dim firstrow As Integer, lastrow As Integer
Dim fr As Integer, lr As Integer, lr2 As Integer
Dim sum As Double
Dim name As Range, stock As Range, value As Range, units As Range, cp As Range

With ActiveSheet.Range("A:Z")

    Set stock = .find(what:="Stock Code", After:=.Cells(.Cells.count), LookIn:=xlValues, _
                Lookat:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False)
    Set value = .find(what:="Value", After:=.Cells(.Cells.count), LookIn:=xlValues, _
                Lookat:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False)
    Set name = .find(what:="Players", After:=.Cells(.Cells.count), LookIn:=xlValues, _
                Lookat:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False)
    Set units = .find(what:="Units", After:=.Cells(.Cells.count), LookIn:=xlValues, _
                Lookat:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False)
    Set cp = .find(what:="Current Price", After:=.Cells(.Cells.count), LookIn:=xlValues, _
                Lookat:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False)

    fr = stock.Row + 1
    lr = .Cells(.Rows.count, stock.Column).End(xlUp).Row

    If Cells(name.Row + 1, name.Column) = "" Then
        End
    End If

    For i = fr To lr

'checks to ensure that there is a player in the spreadsheet
        If Cells(i, name.Column) <> "" Then
         m = i
        End If

'each player has a total row. The word Total identifies the last row for a player
        For j = m To lr
            If Cells(j, stock.Column) = "TOTAL" Then
                lr2 = j
                Exit For
            End If
        Next j

'checks the range where there are stock codes in the sheet, and when the current price updates it
                If Not Intersect(target, target.Worksheet.Range(.Cells(m, cp.Column), .Cells((lr2 - 1), cp.Column))) Is Nothing Then
                    For t = m To (lr2 - 1)
                        Cells(t, value.Column) = Cells(t, cp.Column) * Cells(t, units.Column)
                    Next t
                End If

'checks to see if there has been a change in the value column for each stock and recalculates the new total
            sum = 0
                If Not Intersect(target, target.Worksheet.Range(.Cells(m, value.Column), .Cells((lr2 - 1), value.Column))) Is Nothing Then
                    For t = m To (lr2 - 1)
                        sum = sum + Cells(t, value.Column)
                    Next t
                    Cells(lr, value.Column) = sum
                End If

    Next i

End With

End Sub

Я просто не уверен, почему, когда текущая цена обновляется, мне нужно войти в ячейку значения и выйти снова, прежде чем она действительно обновится.

Ценю любые отзывы.

1 ответ

Извините, я понял это. Я работал под этим Private Sub Worksheet_SelectionChange(ByVal target As Range) скорее, чем Private Sub Worksheet_Change(ByVal target As Range)

Другие вопросы по тегам