使用Excel VBA从sql数据库中提取数据并将数据推送到sql数据库,而无需在Excel工作表中粘贴数据

时间:2015-06-08 13:04:24

标签: sql excel excel-vba vba

我想使用Excel vba从一个数据库(服务器)提取数据,然后将其推送到另一个数据库(本地)。但是,我不想在此过程中将数据粘贴到任何Excel工作表中,因为这会大大减慢Excel的速度。我怎样才能做到这一点?以下是我到目前为止的工作。我突出显示了我的代码停止的错误 - 错误的参数数量或无效的属性赋值

Sub get_data_temp()
    Dim cn As Object
    Dim rs As Object
    Dim strConnection As String
    Dim server, port, id, pass As String
    Dim strSQL As String

    'get data from server (MS SQL based)
    strSQL = Range("query_1").Value
    server = Range("db_server").Value
    port = Range("db_port").Value
    id = Range("db_id").Value
    pass = Range("db_pass").Value

    Set cn = CreateObject("ADODB.Connection")
    strConnection = "Provider=SQLOLEDB;Data Source=" & server & "," & port & ";User ID=" & id & ";Password=" & pass & ";"
    cn.Open strConnection
    Set rs = cn.Execute("SET NOCOUNT ON;" & strSQL)

    'connect to ms access to import data
    Dim xcn As Object
    Dim xrs As Object
    Dim xdbpath As String
    Dim xstrConnection As String
    Dim xdb_name As String
    Dim xstrSQL As String

    ''''''''the code stops at the line below'''''''''''''
    xstrSQL = "insert into crm_main select * from " & rs
    ''''''''the code stops at the line above'''''''''''''

    xdb_name = "temp.accdb"
    xdbpath = ThisWorkbook.Path & Application.PathSeparator & xdb_name
    Set xcn = CreateObject("ADODB.Connection")
    xstrConnection = "Provider=Microsoft.ACE.OLEDB.12.0;" & "Data Source=" & dbpath
    xcn.Open xstrConnection
    xcn.Execute(xstrSQL)
    cn.Close
    Set cn = Nothing
    xcn.Close
    Set xcn = Nothing

End Sub

0 个答案:

没有答案