【问题标题】:How do you update the same cell you've entered a value in, based on another cell?如何根据另一个单元格更新您输入值的同一单元格?
【发布时间】:2020-04-03 11:19:52
【问题描述】:

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

所以,我在 A1 中输入 100。

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

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

任何帮助或指导都会很棒:)

【问题讨论】:

    标签: excel vba cell target byval


    【解决方案1】:

    您需要一个在单元格 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
    

    【讨论】:

    • 很好地使用CountLarge 并包含错误处理程序(+1)
    • 感谢您的回复。我不知道凯斯,将进一步调查。我确实忘了提到,C5 的每次更改都应该根据输入到 A1 中的原始值进行计算。
    • 查看编辑后的代码。如果它解决了您的问题,您也可以接受直接未来读者的答案......
    【解决方案2】:

    为什么不将结果显示在像 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多