Open_Workbook例程手动但不自动工作

时间:2013-10-14 15:42:12

标签: sql excel vba excel-vba

我将以下代码粘贴到ThisWorkbook对象中。但是,每当我打开工作簿时,它什么也没做,只要我进入VBA并手动单步执行它,它就可以运行并且组合框被填充了?我确定它是一个简单的设置或简单的东西,而不是任何复杂的代码,但我完全不知道为什么这会失败。

非常感谢任何帮助

Option Explicit
Public bClear As Boolean

Private Sub Open_Workbook()

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
ConnectionString = "Provider=sqloledb.1;data source=SQL-SERVER;Initial catalog=SQL-DB;Integrated Security = SSPI;"
Set objConn = New ADODB.Connection

stSQL = "EXEC('SELECT NAME FROM TABLE1')"

With objConn
    .CursorLocation = adUseClient
    .Open ConnectionString
    Set rst = .Execute(stSQL)
End With

With rst
    Set .ActiveConnection = Nothing
    k = .Fields.Count
    vaData = .GetRows
End With

Sheets("Menu").CB_Book.List = Application.Transpose(vaData)

objConn.Close

Set rst = Nothing
Set objConn = Nothing

bClear = True

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

End Sub

1 个答案:

答案 0 :(得分:3)

尝试更改此内容:

Private Sub Open_Workbook()

对此:

Private Sub Workbook_Open()