我正在努力为 VBA ListBox 用户窗体建立 SQL 连接/源。我已经能够将正确的 sql 表导入到 Excel 工作表(来自下面的代码),但到目前为止,我所有尝试加载与列表框源相同的数据都失败了。下面的代码是我的一位同事给我的,并适用于我们的数据库。
Sub SQL_VBA()
Dim sConn As String
Dim oQt As QueryTable
Dim sSql As String
'defining the connection string
sConn = "ODBC;DSN=RISK_DB;UID=;PWD=;"
sConn = sConn & "WSID=;DATABASE=RISK_DB"
sSql = str_SQLText
Set oQt = Sheet1.QueryTables.Add(Connection:=sConn, Destination:=Sheet1.Range("A1"), Sql:=sSql)
With oQt
.Name = "Query from"
.FieldNames = True '' This returns the headers of the tables you need
.RowNumbers = False
.PreserveFormatting = True
.RefreshOnFileOpen = False '' Dont want to refresh file each time it opens
.BackgroundQuery = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.PreserveColumnInfo = True
.Refresh BackgroundQuery:=True
End With
End Sub
有没有人将 SQL 表加载为用户表单的数据源的经验?