CopyFromRecordset到Excel仅复制数字

时间:2018-12-08 16:50:01

标签: excel vba excel-vba

我正在尝试将整个记录集复制到Excel工作表中,但只能复制正确的数字。单元格应为空白。有人可以帮助我吗?

这是我的代码:

public cn As New ADODB.Connection
public rs As New ADODB.Recordset
public rs2 As New ADODB.Recordset
public strFile$, strCon$, strsQL$

Sub macro() 
    strFile = ThisWorkbook.Path & "\" & ThisWorkbook.Name
    cn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strFile & ";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=1"";"
    cn.CursorLocation = adUseClient
    cn.Open
    strsQL = "SELECT A, B, C FROM SqlTable5"
    rs.Open strsQL, cn

    Set rs2 = rs.Clone
    For iCols = 0 To rs2.Fields.Count - 1
        ThisWorkbook.Sheets("test").Cells(1, iCols + 1).Value = rs2.Fields(iCols).Name
    Next
    ThisWorkbook.Sheets("test").Range("A2").CopyFromRecordset rs2
    rs.Close
    rs2.Close
    cn.Close
    Close Connection
    Set rs = Nothing
    Set cn = Nothing
End Sub

在名称管理器中设置了SqlTable5。

0 个答案:

没有答案