0

在这里完成 VBA 初学者 - 我正在尝试根据另一个单元格及其变化的值来更新我刚刚输入值的单元格。

所以,我在 A1 中输入 100。

然后,基于在单元格 C5 中键入 3 个单词的选项,我想将 A1 乘以一定数量。

如果我在 C5 中输入“正常”,它将 A1 乘以 1。如果我在 C5 中输入“低”,它会将 A1 乘以 0.5。如果我在 C5 中输入“高”,它将 A1 乘以 2。

任何帮助或方向都会很棒:)

4

2 回答 2

3

您需要一个在单元格 C5 值更改时触发的工作表事件处理程序

将此代码放在工作表代码窗格中(只需右键单击选项卡并选择“查看代码”)

Dim myValue As Variant
Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.CountLarge > 1 Then Exit Sub
    If Target.Address <> "$A$1" Then myValue = Range("A1").Value ' keep track of any "original value" changes
    If Target.Address <> "$C$5" Then Exit Sub

    If IsEmpty(myValue) Then myValue = Range("A1").Value ' retrieve the "original value" if not already set

    On Error GoTo SafeExit
    Application.EnableEvents = False
    Select Case Target.Value
        Case "Normal"
            ' no need to multiply by 1 ...

        Case "Low"
            Range("A1").Value = myValue * 0.5 ' divide "original value"

        Case "High"
            Range("A1").Value = myValue * 2 'multiply "original value"

    End Select

SafeExit:
    Application.EnableEvents = True       
End Sub
于 2020-04-03T11:24:48.580 回答
0

为什么不将结果显示在像 B1 这样的另一个单元格中?
然后你可以在那里使用一个简单的公式:

=A1*IF($C$5="Low",0.5,IF($C$5="High",2,1))

在此处输入图像描述


备用 VBA 解决方案

Option Explicit

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim AffectedCells As Range
    Set AffectedCells = Intersect(Target, Me.Range("A1")) 'you can extend the range to more cells like A1:A10

    If Not AffectedCells Is Nothing Then
        On Error GoTo SafeExit

        Dim Factor As Double
        Select Case Me.Range("C5").Value 'note this is case sensitive
            Case "Normal": Exit Sub
            Case "Low":    Factor = 0.5
            Case "High":   Factor = 2
        End Select

        Application.EnableEvents = False
        Dim Cell As Range
        For Each Cell In AffectedCells.Cells
            If IsNumeric(Cell.Value) Then
                Cell.Value = Cell.Value * Factor
            End If
        Next Cell
    End If

SafeExit:
    Application.EnableEvents = True
End Sub
于 2020-04-03T11:28:11.923 回答