0

我正在学习 vba 的事件处理。这是我的第一次尝试。

'in sheet Object
Dim WithEvents engine As MCengine

Private Sub engine_OnEachTrial(ByVal i As Integer)
progressBar = Application.Floor(i * 30 / engine.numOfPaths, 0.001)

With ActiveSheet.Range("E10").Characters(start:=0, Length:=progressBar).Font
    .Name = "Calibri"
    .FontStyle = "Bold"
    .Size = 11
    .ColorIndex = 16
End With
End Sub

Private Sub Worksheet_Activate()

Dim btn As Button
Dim rng As Range
Set engine = New MCengine
With ActiveSheet
Set rng = .Range("E9")
Set btn = .Buttons.Add(rng.Left, rng.Top, rng.Width, rng.Height)
    With btn
    .Caption = "Run MC simulation"
    .OnAction = "runMC"
    End With
End With

End Sub

Sub runMC()

engine.process = 1
engine.numOfPaths = 30
engine.start

End Sub

上面代码的问题是onAction注册的子过程不能被调用,因为看起来runMC必须在Module中。我无法将这些代码移动到模块,因为Dim WithEvents engine As MCengine需要在工作表对象中声明。所以我被困在中间。我应该使用其他按钮回调方法吗?

这是否意味着我不能在模块中使用带有事件的类?任何人都可以启发我吗?

4

1 回答 1

1

我假设您希望此代码适用于整个工作簿,这就是您使用“Activesheet”的原因?
如果是这样,您需要将代码粘贴到 Thisworkbook 模块中。

Option Explicit

Private Sub Workbook_SheetActivate(ByVal oSheet As Object)
    Dim btn As Button
    Dim rng As Range


    'Set engine = New MCengine
    With oSheet
        Set rng = .Range("E9")
        Set btn = .Buttons.Add(rng.Left, rng.Top, rng.Width, rng.Height)
        With btn
            .Caption = "Run MC simulation"
            .OnAction = "Thisworkbook.Test_btn"
        End With
    End With
End Sub

Sub Test_btn()

MsgBox "Ok"

End Sub

如果没有,您可以将其粘贴到常规工作表模块和工作表事件中:
private sub Worksheet_Activate,但请注意在以下位置定义正确的工作表对象:

.OnAction = "Sheet1.Test_btn"
于 2012-07-31T08:28:14.213 回答