如何使用 ADO 从访问 excel WEEKLY 中提取记录

how to pull records from access to excel WEEKLY using ADO

我正在尝试创建一个宏,每周从对 Excel 文件的访问中导出新记录。目前我的代码已将新的 sheet 添加到 Excel 文件,但我怎样才能让它只更新文件中已有的 sheet?

Const ConStrAccess As String = "xxxx;"

Sub CopyDataFomDatabase()

    Dim BrokerConn As ADODB.Connection
    Dim BrokerData As ADODB.Recordset
    Dim BrokerField As ADODB.Field

    Set BrokerConn = New ADODB.Connection
    Set BrokerData = New ADODB.Recordset

    BrokerConn.ConnectionString = ConStrAccess
    BrokerConn.Open

    On Error GoTo CloseConnection

    With BrokerData
        .ActiveConnection = BrokerConn
        .Source = "SELECT * FROM xxxxx;"
        .LockType = adLockReadOnly
        .CursorType = adOpenForwardOnly
        .Open
    End With

    On Error GoTo CloseRecordset

    Worksheets.Add

    For Each BrokerField In BrokerData.Fields
        ActiveCell.Value = BrokerField.Name
        ActiveCell.Offset(0, 1).Select
    Next BrokerField

    Range("A1").Select
    Range("A2").CopyFromRecordset BrokerData
    Range("A1").CurrentRegion.EntireColumn.AutoFit

CloseRecordset:
    BrokerData.Close

CloseConnection:
    BrokerConn.Close

如果您已经知道工作表的名称,您可以在下面的代码中简单地指定名称而不是 Sheet1。如果它不存在,它将创建它。如果将其留空,这将 select 此代码 运行 所在工作簿中的活动工作表。

注意:我假设这将在您保存结果的工作簿上 运行。如果不是这种情况,则需要将 ThisWorkbook 替换为 ActiveWorkbook

Const ConStrAccess As String = "xxxx;"

Const sheetName As String = "Sheet1"

Sub CopyDataFomDatabase()

    Dim BrokerConn As ADODB.Connection
    Dim BrokerData As ADODB.Recordset
    Dim BrokerField As ADODB.Field

    Set BrokerConn = New ADODB.Connection
    Set BrokerData = New ADODB.Recordset

    BrokerConn.ConnectionString = ConStrAccess
    BrokerConn.Open

    On Error GoTo CloseConnection

    With BrokerData
        .ActiveConnection = BrokerConn
        .Source = "SELECT * FROM xxxxx;"
        .LockType = adLockReadOnly
        .CursorType = adOpenForwardOnly
        .Open
    End With

    On Error GoTo CloseRecordset

    Dim selectedWorksheet As Worksheet

    'If no name is given it will select the active one
    If sheetName = vbNullString Then
        Set selectedWorksheet = ThisWorkbook.ActiveSheet

    'If the sheet with this name does not exist, it will be created and activated
    'For checking if it exists: 
    ElseIf WorksheetFunction.IsErr(Evaluate("'" & sheetName & "'!A1"))    Then        
        Set selectedWorksheet = ThisWorkbook.Sheets.Add()
        selectedWorksheet.Name = sheetName
        selectedWorksheet.Activate

    'Simply actives the sheet   
    Else
        Set selectedWorksheet = ThisWorkbook.Worksheets(sheetName)
        selectedWorksheet.Activate

    End If

    For Each BrokerField In BrokerData.Fields
        ActiveCell.Value = BrokerField.Name
        ActiveCell.Offset(0, 1).Select
    Next BrokerField

    Range("A1").Select
    Range("A2").CopyFromRecordset BrokerData
    Range("A1").CurrentRegion.EntireColumn.AutoFit

CloseRecordset:
    BrokerData.Close

CloseConnection:
    BrokerConn.Close