通过 VB 将访问数据库导出到 Excel - 使用数据库的前 10 行

Exporting an access DB to Excel through VB - with the first 10 rows of DB

我刚开始使用 VB 和 Excel,需要帮助。

我有两个访问数据库;一个数据库有 10 列多行(超过 10 行),另一个数据库有 8 列和与另一个数据库相同的行数。

我想做的是将两个数据库的前 10 行导出到 excel sheet(在单独的 sheet 或两个单独的 excel 文件,以便可以通过电子邮件发送或打印。

我一直在四处寻找,试图了解如何做到这一点,并尝试了几种方法,但 none 的方法都奏效了。

此外,如果有人可以帮助通过 VB 导出数据库的前 10 行,我会很好。

有人能帮帮我吗

谢谢, 安迪

假设这类似于 Excel 中的“导入数据”按钮,您可能想使用 ADODB 连接到您的访问数据库,select 将数据导入记录集,然后将记录集读入数组并分配给您要导入的工作表(可选地在现有数据的末尾 - 这取决于您是导入“另外 10 行”还是刷新前 10 行(无论那意味着什么 - 猜测您有一个查询不过,请在 Access 中获取这些内容。

方法看起来像这样。哦,在我们开始之前,您需要添加对 Microsoft ActiveX Data Objects 6.1.

的引用(工具 -> 引用)
Public Sub Test()
    Dim strSQL_Query As String
    Dim oCN As ADODB.Connection
    Dim oCMD As ADODB.Command
    Dim oRecords As ADODB.Recordset
    Dim strCN As String
    Dim strDBPath As String
    Dim varValues As Variant
    Dim wksTarget As Excel.Worksheet
    Dim lngRows As Long
    Dim lngCols As Long


    '' Replace with the path to your DB. You could also use a dialog box to let the user choose a DB, if
    '' it moves around or isn't found.
    strDBPath = "C:\myFolder\myAccessFile.accdb"
    strCN = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strDBPath & ";" & _
            "Persist Security Info=False;"

    '' Replace this with a query that does what you need it to
    strSQL_Query = "SELECT TOP 10 FROM [MyTable] WHERE <Conditions> ORDER BY [Column] DESC"

    Set oCN = New ADODB.Connection
    oCN.ConnectionString = strCN
    oCN.Open

    Set oCMD = New ADODB.Command
    oCMD.ActiveConnection = oCN
    oCMD.CommandText = strSQL_Query
    Set oRecords = oCMD.Execute

    If oRecords.BOF And Not oRecords.EOF Then
        varValues = oRecords.GetRows
        Set wksTarget = ThisWorkbook.Worksheets(1)

        '' You might need 0 and 1 instead of 1 and 2 - I forget
        lngCols = UBound(varValues, 1)
        lngRows = UBound(varValues, 2)
        wksTarget.Range("A1", wksTarget.Range("A1").Offset(lngRows, lngCols)) = varValues
    End If

    '' Clean up...
    Set oRecords = Nothing
    Set oCMD = Nothing
    oCN.Close
    Set oCN = Nothing

    '' Do Some more stuff...

    '' And finish by saving the workbook
    '' 1) Check if the directory exists and create it
    Dim strDir as String
    strDir = "C:\Some\Path\Here"
    If Dir(strDir, vbDirectory) = "" Then MkDir(strDir)
    ThisWorkbook.SaveAs strDir & "YourWorkbookName.xlsm", 52 '' 52 is a constant indicating a macro enabled format
End Sub