[VB/VBA]SQL操作EXCEL

 

[VB/VBA]SQL操作EXCEL

1、添加引用

      (1)、Microsoft Active Data Objects 2.8 Library

      (2)、Microsoft ADO Ext . 2.8 For DDL and Security

2、用ADOX连接EXCEL文件

    Dim cat As ADOX.Catalog
    Dim tbl As ADOX.Table
    Dim col As ADOX.Column
    Dim cmd As ADODB.command
    Dim rs As Recordset
    
    Set cat = New ADOX.Catalog
    cat.ActiveConnection = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
        "Data Source=" & ThisWorkbook.Path & _
        "/book2.xls;Extended Properties=Excel 8.0"

3、创建Sheet以及给单元格赋值

    Set tbl = New ADOX.Table
    tbl.Name = "TestTable"
    Set col = New ADOX.Column
    With col
        .Name = "Col1"
        .Type = adDouble
    End With
    tbl.Columns.Append col
    Set col = Nothing
    
    Set col = New ADOX.Column
    With col
        .Name = "Col2"
        .Type = adVarWChar
    End With
    tbl.Columns.Append col
    cat.Tables.Append tbl

4、执行SQL文(SELECT、INSERT、UPDATE、DELETE都可以,下面的代码以SELECT为例)

    Set cmd = New ADODB.command
    cmd.CommandText = "select TA.*, TB.w from [表1$] TA, [表2$] TB where TA.A = Tb.A and TA.A < 'A10'"
    cmd.CommandType = adCmdText
    cmd.ActiveConnection = cat.ActiveConnection
    Set rs = cmd.Execute()
    While Not rs.EOF
        Debug.Print rs.GetString()
    Wend
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值