0

我对 VBA 很陌生,但到目前为止,我还在继续。直到这一刻,我都被这个挑战困住了。

My goal is to select a percentage (10, 90 or 100) from a drop down menu in a cell in column B, C, D or E and when one of the percentages is selected, I want the same cell to calculate the selected percentage A列中的值。

因此,当 A 列中的单元格的值为“500”并且在 CI 列的同一行中选择“90”时,我希望将 90 替换为 450 (0.9*500)

这里给出的代码是我到目前为止所得到的,包括一些已经从另一个主题“借来”的代码。虽然它可以在一个新的、干净的 excel 表中工作,但它不能在我希望它工作的文档中工作。

你们中的一些人有什么想法可以找到缺陷吗?(我什至创建了一个只有任务的命令按钮:Application.EnableEvents = True)

Private Sub Worksheet_Change(ByVal Target As Range)

On Error GoTo Whoa

If Not Intersect(Target, Range("B:D")) Is Nothing Then
    Application.EnableEvents = False
    If Target.Value = 90 Then Target.Value = 0.9 * Cells(Target, 1).Value
    ElseIf Target.Value = 10 Then Target.Value = 0.1 * Cells(Target, 1).Value
    ElseIf Target.Value = 100 Then Target.Value = Cells(Target, 1).Value
    Else
        MsgBox "Not a valid percentage"
    End If

Letscontinue:
    Application.EnableEvents = True
    Exit Sub
Whoa:
    MsgBox Err.Description
    Resume Letscontinue
End Sub
4

3 回答 3

0

这意味着您在 application.enableevents=false 时因错误而停止,并且您在没有 application.enableevents=true 的情况下再次运行该东西...

我实际上有一个解决这个问题的按钮,就在我调试代码时,或者在VB编辑器中,Ctrl+G,在即时窗口中,你可以写application.enableevents=true

于 2013-12-24T12:06:04.787 回答
0

听起来你想要 Workbook_SheetChange 事件。在 VBA 编辑器中将您的逻辑添加到 ThisWorkbook。

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
    MsgBox "Cell changed. Target: " & Target.Worksheet.Name & "!" & Target.Address
End Sub

将上述代码添加到ThisWorkbook工作簿中任何工作表上的更改都会触发该事件。

于 2013-07-31T16:08:44.493 回答
0

您不需要 VBA 来完成您的要求。数据验证和公式将起作用:

数据验证示例

于 2013-07-31T20:11:49.540 回答