VBA Macro跳到另一个?

时间:2014-08-14 16:24:16

标签: excel vba

这段代码有什么理由

Private Sub CT_Company_Loss_Change()

With Application
    .Calculation = xlManual
    .EnableEvents = False
    .ScreenUpdating = False
End With

Dim stSQL As String, rst As ADODB.Recordset, k As Integer, vaData As Variant
Dim objConn As ADODB.Connection
Dim ConnectionString As String, sCompany As String
ConnectionString = "Provider=sqloledb.1;data source=se-sqlct-0100;Initial catalog=AirCT2Loss;Integrated Security = SSPI;"
Set objConn = New ADODB.Connection

With CY_Program1
        .Clear
        .AddItem "Select Program"
        .ListIndex = 0
End With

获取最后一行,然后跳转到此宏:

Private Sub CY_Program1_Change()

With Application
    .Calculation = xlManual
    .EnableEvents = False
    .ScreenUpdating = False
End With

Dim stSQL As String, rst As ADODB.Recordset, k As Integer, vaData As Variant
Dim objConn As ADODB.Connection
Dim ConnectionString As String, sCompany As String, sProgram As String
ConnectionString = "Provider=sqloledb.1;data source=se-sqlct-0100;Initial catalog=AirCT2Loss;Integrated Security = SSPI;"
Set objConn = New ADODB.Connection

我之前从未见过这种情况,而且我甚至没有使用通话功能,那么是什么让它成为了我的电子表格呢?

提前致谢

2 个答案:

答案 0 :(得分:3)

正如@ sous2817指出的那样,CT_Company_Loss_Change()CY_Program1_Change()都是事件处理程序,这意味着Excel会在发生某些操作时运行它们。我同意@ sous2817的猜测," CT_Company_Loss"和" CY_Program1"是控件,特别是" CY_Program1"是一个列表框(这可以从代码与之交互的方式中看出来。)

以下代码行导致"更改"到" CY_Program1"列表框:

With CY_Program1
    .Clear
    .AddItem "Select Program"
    .ListIndex = 0
End With

因此,在函数完成之后,Excel所做的下一件事就是触发"更改" " CY_Program1"的事件处理程序列表框:CY_Program1_Change()


<强>更新

如果您希望CY_Program1_Change()事件处理程序在您清除&#34;在列表框中,尝试在CY_Program1_Change()函数的开头添加它:

If CY_Program1.ListCount = 1 And CY_Program1.List(0) = "Select Program" Then
    Exit Sub
End If

基本上,如果CY_Program1列表框只是&#34;清除&#34;,它会在不运行其余事件处理程序代码的情况下退出。

答案 1 :(得分:1)

这是在userforms(userform表格代码)中启用事件或禁用它们的方法:

(对于一个精简表,您可以应用相同的方法,但在优化表代码中)

Option Explicit
Dim Events As Boolean

Private Sub CT_Company_Loss_Change()
With Application
    .Calculation = xlManual 'works only for the exel worksheet, not the userform
    .EnableEvents = False 'works only for the exel worksheet, not the userform
    .ScreenUpdating = False 
End With

Events = False

'much more code here (....)

With CY_Program1
    .Clear
    .AddItem "Select Program"
    .ListIndex = 0
End With

events = True

With Application
    .Calculation = xlAutomatic
    .EnableEvents = true
    .ScreenUpdating = true
End With

End sub

并在相同的用户表单代码中:

Private Sub CY_Program1_Change()
if events then  'so, if CY_Program1_Change is called/triggered, then if events is false it won't allow the code to run
   'more code (...)
end if
end sub