通过ActiveX控件按钮运行VBA子例程时是否允许用户交互?

时间:2015-12-15 18:51:03

标签: excel vba excel-vba activex

我有一个从宏窗口(ALT + F8)运行时按预期执行的子程序。我还可以将表单按钮链接到此子,它继续正常工作。

现在,当我将ActiveX控件按钮连接到子按钮时,单击该按钮,并确保不再单击任何其他内容,宏再次按预期执行。但是,如果我在宏运行时单击屏幕上的任何位置,我的结果会出现与预期不同的结果。从ActiveX按钮运行时,似乎以某种方式启用了用户交互。即便如此,为什么点击屏幕会改变任何东西呢?

显然,我可以确保在执行时不碰任何东西,或只是使用表单按钮,或者只是总是从宏窗口运行宏...但我喜欢理解它为什么会这样。

Option Explicit

Sub run_loop()

Const FINALSHEET As String = "Final UV's"
Const VARYYEAR As String = "G6"
Const STARTYEAR As String = "H1"
Const ENDYEAR As String = "H2"
Const OUTPUTVECTOR As String = "G6:G46"
Const DIAGONALVECTOR As String = "H3"

' variable declarations
Dim input_year As Range
Dim vector_out As Range
Dim diagonal_vector As Range

Dim start_year As Integer
Dim end_year As Integer
Dim duration As Integer

' variable initializations
With ThisWorkbook.Sheets(FINALSHEET)
    Set input_year = .Range(VARYYEAR)
    Set vector_out = .Range(OUTPUTVECTOR)
    Set diagonal_vector = .Range(DIAGONALVECTOR)

    start_year = .Range(STARTYEAR).Value
    end_year = .Range(ENDYEAR).Value
End With

' clear any prior results
Range(diagonal_vector, Cells(1000, 1000)).Clear

' set initial issue year (loop decrements by 1 immediately so set to 1 higher than initial)
input_year.Value = start_year + 1

' main loop
Do While input_year.Value > end_year   ' ensure that the issue year hasn't gone past the specified end year

    ' decrement the issue year by 1 (sheet auto recalculates at this point)
    input_year.Value = input_year.Value - 1

    ' recalculate duration
    duration = start_year - input_year.Value + 1

    ' copy the resulting vector of UV factors for current issue year to the appropriate column
    vector_out.Offset(0, duration).Value = vector_out.Value

    ' copy diagonal values to a single vector of current year unit values by duration
    diagonal_vector.Offset(0, duration - 1).Value = vector_out(duration + 1, 1)
Loop
End Sub

ActiveX控件按钮的代码位于包含它的工作表的代码中,只需调用run_loop。

Private Sub RunToggle_Click()

run_loop

End Sub

1 个答案:

答案 0 :(得分:0)

我不确定,但尝试更换你的行:

Range(diagonal_vector, Cells(1000, 1000)).Clear 

这一行:

Range(diagonal_vector, ThisWorkbook.Sheets(FINALSHEET).Cells(1000, 1000)).Clear