VBA ADO备份,只有csv数据源进行了测试

'import Microsoft ActiveX Data Objects 6.1 Library   or 2.X
Public gBaseLibConn As Object, gBaseLibRs As Object, gBaseLibConnStr$
Sub getConnectionObj(ByVal dbtype$, ByVal ServerPath$, ByVal db$, ByVal uid$, ByVal pwd$)
    If Not gBaseLibConn Is Nothing Then Set gBaseLibConn = Nothing

    Set gBaseLibConn = CreateObject("ADODB.Connection")
    Set gBaseLibRs = CreateObject("ADODB.Recordset")
    gBaseLibConnStr = ""

    Select Case dbtype
    Case "SQL"
        gBaseLibConnStr = "driver={sql server};" & "server=" & ServerPath & ";" & "database=" & db & ";" & "uid=" & uid & ";" & "pwd=" & pwd & ";"
    Case "Access"
        gBaseLibConnStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & ServerPath & ";Jet OLEDB:Database Password=" & pwd
    Case "Excel"
        'gBaseLibConnStr = "Provider=Microsoft.Jet.OleDb.4.0;Extended Properties=Excel 8.0;Data Source=" & ServerPath
        gBaseLibConnStr = "Excel File=" & ServerPath
    Case "MYSQL"
        gBaseLibConnStr = "DRIVER={MySql ODBC 3.51 Driver};SERVER=" & ServerPath & ";Database=" & db & ";Uid=" & uid & ";Pwd=" & pwd & ";Stmt=set names GBK"
    Case "CSV"
        'gBaseLibConnStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & ServerPath & ";Extended Properties='Text;HDR=Yes;FMT=Delimited'"  'for before Office 2007 version
        gBaseLibConnStr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & ServerPath & ";Extended Properties='Text;HDR=Yes;FMT=Delimited'" 'after Office 2007 version
    End Select
End Sub

Sub openConnect(ByVal dummy%)
    If gBaseLibConn.State = 1 Then gBaseLibConn.Close
    gBaseLibConn.Open gBaseLibConnStr
End Sub

Sub closeConnect(ByVal dummy%)
    Set gBaseLibRs = Nothing
    gBaseLibConn.Close
    Set gBaseLibConn = Nothing
End Sub

Sub excuteSql(ByVal ssql$)
    If gBaseLibRs Is Nothing Then
        Set gBaseLibRs = New ADODB.Recordset
    ElseIf gBaseLibRs.State = adStateOpen Then
            gBaseLibRs.Close
            Set gBaseLibRs = Nothing
            Set gBaseLibRs = New ADODB.Recordset
    End If
    gBaseLibRs.Open ssql, gBaseLibConn, 1, 3
End Sub

Sub testADO_csv()
    Dim ssql$, i%
    Call getConnectionObj("CSV", "E:\tmp\", "", "", "")
    Call openConnect(1)
    ssql = "select * from (select * from [a.csv] union select * from [b.csv]) as ut where ut.aType='A'  and ut.x > 1.0"
    Call excuteSql(ssql)
    Sheets("testAdo").Cells.Clear
    
    For i = 0 To gBaseLibRs.Fields.Count - 1
        Sheets("testAdo").Cells(1, i + 1) = gBaseLibRs.Fields(i).Name
    Next
    Sheets("testAdo").Range("a2").CopyFromRecordset gBaseLibRs
    Call closeConnect(1)
End Sub

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值