簡體   English   中英

Excel VBA事件根據用戶輸入計算

[英]Excel VBA event to calculate based on user input

作為前言,我是VBA編程的新手,所以任何幫助都將不勝感激。

我有兩列; 一個用戶可以輸入美元值(“AL”),另一個用戶可以輸入百分比值(“AK”)。 對象是使用戶能夠輸入值(%或$)並計算其他值。 例如,如果用戶在“AL”中輸入10%,則適用的$值將在“AK”中生成,反之亦然。

下面是我到目前為止提出的代碼,但它不起作用。 任何想法/建議將不勝感激! 謝謝!

Private Sub Worksheet_Change(ByVal Target As Range)
   Dim cell As Range
   Set cell = Range("AK9:AL50")
   'Application.EnableEvents = False Application.EnableEvents = True'

   If Not Application.Intersect(cell, Range(Target.Address)) Is Nothing Then
    If Target.Column = 37 Then ' Value in first column changed
        Range("AL" & Target.Row).Value = Range("AK" & Target.Row).Value / Range("V" & Target.Row).Value
        Exit Sub
    ElseIf Target.Column = 38 Then ' value in second column changed
        Range("AK" & Target.Row).Value = Range("AL" & Target.Row).Value * Range("V" & Target.Row).Value
        Exit Sub
    'Application.EnableEvents = False Application.EnableEvents = True'
    End If
  End If
End Sub

您需要刪除Exit Sub

Application.EnableEvents = True需要在if之外。

第一次使用Application.EnableEvents = False行啟用它時,它關閉了事件,因為您在將它們重新打開之前退出了子,所以它保持關閉狀態,並且從未再次調用該子。

Private Sub Worksheet_Change(ByVal Target As Range)
   Dim cell As Range
   Set cell = Range("AK9:AL50")
   Application.EnableEvents = False

   If Not Application.Intersect(cell, Range(Target.Address)) Is Nothing Then
    If Target.Column = 37 Then ' Value in first column changed
        Range("AL" & Target.Row).Value = Range("AK" & Target.Row).Value / Range("V" & Target.Row).Value

    ElseIf Target.Column = 38 Then ' value in second column changed
        Range("AK" & Target.Row).Value = Range("AL" & Target.Row).Value * Range("V" & Target.Row).Value

    End If
    Application.EnableEvents = True
  End If
End Sub

我的猜測是你的事件被禁用了。

在上面的表格中輸入正確的代碼后運行此代碼:

Sub foooo()
Application.EnableEvents = True
End Sub

這將使事件重新開啟。 它只需要一次。

您可以更好地使用Worksheet_Change參數,例如Target

1.而不是:

Range("AL" & Target.Row).Value 

您可以使用:

Target.Offset(, 1).Value

2.而不是:

Range("AK" & Target.Row).Value 

您可以使用:

Target.Value

3.Also Range(Target.Address)實際上是Target

Private Sub Worksheet_Change(ByVal Target As Range)

Dim cell As Range
Set cell = Range("AK9:AL50")

Application.EnableEvents = False

If Not Application.Intersect(cell, Target) Is Nothing Then
    If Target.Column = 37 Then ' Value in first column changed
        Target.Offset(, 1).Value = Target.Value / Range("V" & Target.Row).Value
    ElseIf Target.Column = 38 Then ' value in second column changed
        Target.Offset(, 2).Value = Target.Value * Range("V" & Target.Row).Value
    End If
End If
Application.EnableEvents = True '<-- RESTORE SETTING OUTSIDE THE IF

End Sub

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM