使用vba将sql数据导入excel

时间:2012-11-16 22:54:27

标签: sql excel vba excel-vba

我正在尝试将数据从SQL表中提取到excel中。我使用数据源工具录制了一个宏。然而,我拉动的数据量通常会崩溃。有没有办法在我的vba脚本中添加一个变量来限制从sql表中提取的数据?基本上将where子句添加到sql中的select语句。

谢谢!

-Sean

With ActiveSheet.ListObjects.Add(SourceType:=0, Source:=Array( _
    "OLEDB;Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Data Source=10.22.30.215;Use Procedure for Prepare=1;Aut" _
    , _
    "o Translate=True;Packet Size=4096;Workstation ID="FakeName";Use Encryption for Data=False;Tag with column collation when possible=Fa" _
    , "lse;Initial Catalog=FakeCatelog"), Destination:=Range("$A$1")). _
    QueryTable
    .CommandType = xlCmdTable
    .CommandText = Array( _
    """FakeName""")
    .RowNumbers = False
    .FillAdjacentFormulas = False
    .PreserveFormatting = True
    .RefreshOnFileOpen = False
    .BackgroundQuery = True
    .RefreshStyle = xlInsertDeleteCells
    .SavePassword = False
    .SaveData = True
    .AdjustColumnWidth = True
    .RefreshPeriod = 0
    .PreserveColumnInfo = True
    .SourceConnectionFile = _
    "C:\UFakeFilePathodc"
    .ListObject.DisplayName = "FakeName"
    .Refresh BackgroundQuery:=False
End With
End Sub`

2 个答案:

答案 0 :(得分:3)

尝试连接数据库并进行查询,而不是尝试将整个数据库拉入工作表。这应该让你开始:
确保添加“”Microsoft ActiveX Data Objects 6.0库“参考或运行此行一次:
ActiveWorkbook.VBProject.References.AddFromGuid "{B691E011-1797-432E-907A-4D8C69339129}", 6, 0

Sub QueryDB()
    Dim dbName As ADODB.Connection
    Dim dbResults As ADODB.Recordset
    Set dbName = openDBConn("YOURDATABASE", "YourTable")
    Set dbResults = dbName.Execute("SELECT * FROM YOURDATABASE")
    While Not dbResults.EOF
        'Do Something'
        dbResults.MoveNext
    Wend
End Sub

Function openDBConn(dataSource As String, table As String) As ADODB.Connection
    Dim newDBConn As ADODB.Connection
    Set newDBConn = New ADODB.Connection
    newDBConn.CommandTimeout = 60
    Dim strConn As String
    strConn = "PROVIDER=SQLOLEDB;DATA SOURCE=" & dataSource & ";INITIAL CATALOG=" & table & ";INTEGRATED SECURITY=SSPI"
    newDBConn.Open strConn
    Set openDBConn = newDBConn
End Function

答案 1 :(得分:1)

一旦您对代码感到满意,可能需要将其转换为late bindingEarly binding很好,因为你在开发应用程序时会得到完整的智能感知,但随着时间的推移,应用程序升级到新版本,我发现后期绑定会稍微麻烦一点。

另外,因为我使用连接字符串非常多,所以在模块的顶部进行十分转换可能会很好...将来可以省去这个硬代码:

(p.s。这只是Kevin的代码,有一些变化;不一定是改进,但更多只是替代品)

Global Const strConn As String = "PROVIDER=SQLOLEDB;DATA SOURCE=" & dataSource & ";INITIAL CATALOG=" & table & ";INTEGRATED SECURITY=SSPI"
Sub QueryDB()
       Dim dbName As Object
       Dim dbResults As Object
       Set dbName = CreateObject("ADODB.Connection")
       dbName = openDBConn("YOURDATABASE", "YourTable")
       Set dbResults = CreateObject("ADODB.Recordset")
       dbResults = dbName.Execute("SELECT * FROM YOURDATABASE")
       While Not dbResults.EOF
           'Do Something'
           dbResults.MoveNext
       Wend
End Sub

Function openDBConn(dataSource As String, table As String) As ADODB.Connection
       Dim newDBConn As Object
       Set newDBConn = CreateObject("ADODB.Connection")
       newDBConn.CommandTimeout = 60

       newDBConn.Open strConn
       Set openDBConn = newDBConn
End Function