VBAmacros跳转到另一个?

有什么理由为什么这段代码

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 

得到最后一行,然后跳转到这个macros:

 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 

我从来没有见过这个,我什至没有使用通话function,所以是什么让它做它的窃听我的电子表格?

提前致谢

正如@ 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()


UPDATE

如果您希望CY_Program1_Change()事件处理程序在“清除”列表框时忽略它,请尝试在CY_Program1_Change()函数的开始处添加它:

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

基本上,如果CY_Program1列表框被“清除”,它将退出而不运行其余的事件处理程序代码。

这是如何启用事件或在用户窗体中禁用它们(用户窗体代码):

(对于一个神谕,你可以应用相同的方法,但在崇拜代码中)

 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