简体   繁体   中英

Importing data from access into an open excel spreadsheet? (Excel VBA)

I am trying to make an application that has the feature to import data from access into excel. I am starting with a table named ""1301 Array"" before I give user control over which table. The problem is I get the error "Cannot modify table structure. Another user has the table open", assuming because of the excel sheet I am writing in. Is there a work around to use TransferSpreadsheet for this?

Sub Importfromaccess()
Dim accappl As Access.Application
Dim strpathdb As String
Dim strpathxls As String

strpathdb = Application.GetOpenFilename("Access DataBase (*.accdb),*.accdb")

strpathxls = ActiveWorkbook.FullName

Set accappl = New Access.Application

accappl.OpenCurrentDatabase strpathdb
Dim Page As Worksheet
Dim lRow As Long, LCol As Long
Dim fullrange As String
Dim PageName As Variant

accappl.DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, "1301 Array", strpathxls, True

accappl.Quit

End Sub

The solutions I have found online mostly use sql, but I have no idea how to write in that, or how they got sql to work in excel vba. The solution below seems to do something similar to what I need, but I'm not sure how to tweak to import a table into a new sheet and give it the same name.

Sub Workbook_Open()
          Dim cn As Object, rs As Object
          Dim intColIndex As Integer
          Dim DBFullName As String
          Dim TargetRange As Range

       DBFullName = "D:\Tool_Database\Tool_Database.mdb"



        Application.ScreenUpdating = False

        Set TargetRange = Sheets("Sheet1").Range("A1") '1301 Array after creating it?

        Set cn = CreateObject("ADODB.Connection")
        cn.Open "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & DBFullName & ";"

        Set rs = CreateObject("ADODB.Recordset")
        rs.Open "SELECT * FROM ToolNames WHERE Item = 'Tool'", cn, , , adCmdText

          ' Write the field names
        For intColIndex = 0 To rs.Fields.Count - 1
           TargetRange.Offset(1, intColIndex).Value = rs.Fields(intColIndex).Name
       Next

          ' Write recordset
       TargetRange.Offset(1, 0).CopyFromRecordset rs


End Sub

Update: Am going to try and use this method

Sub AccessToExcel()

'Declare variables.
Dim dbConnection As ADODB.Connection
Dim dbRecordset As ADODB.Recordset
Dim dbFileName As String
Dim strSQL As String
Dim DestinationSheet As Worksheet
'Set the assignments to the Object variables.
Set dbConnection = New ADODB.Connection
Set dbRecordset = New ADODB.Recordset
Set DestinationSheet = Worksheets("Sheet2")

'Define the Access database path and name.
dbFileName = "C:\YourFilePath\Database1.accdb"
'Define the Provider for post-2007 database files.
dbConnection.Provider = "Microsoft.ACE.OLEDB.12.0;Data Source=" _
& dbFileName & ";Persist Security Info=False;"

'Use SQL's SELECT and FROM statements for importing Table1.
strSQL = "SELECT Table1.* FROM Table1;"

'Clear the destination worksheet.
DestinationSheet.Cells.Clear

With dbConnection
'Open the connection.
.Open
'The purpose of this line is to disconnect the recordset.
.CursorLocation = adUseClient
End With

With dbRecordset
'Create the recordset.
.Open strSQL, dbConnection
'Disconnect the recordset.
Set .ActiveConnection = Nothing
End With

'Copy the Table1 recordset to Sheet2 starting in cell A2.
'Row 1 contains headers that will be populated at the next step.
DestinationSheet.Range("A2").CopyFromRecordset dbRecordset

'Reinstate field headers (assumes a 4-column table).
'Note that the ID field will also transfer into column A,
'so you can optionally delete column A.
DestinationSheet.Range("A1:E1").Value = _
Array("ID", "Header1", "Header2", "Header3", "Header4")

'Close the recordset.
dbRecordset.Close
'Close the connection.
dbConnection.Close

'Release Object variable memory.
Set dbRecordset = Nothing
Set dbConnection = Nothing
Set DestinationSheet = Nothing

End Sub

The first version won't work because you are attempting to write to the Excel file that you currently have open.

Changing to the following line (of the 2nd code) will copy the data to another worksheet:

Set TargetRange = Sheets("WhateverName").Range("A1")    'or 
Set TargetRange = Sheets(2).Range("A1")
'..if you know it is the 2nd sheet that 
'you want to copy to. Then,

Worksheets(2).Name = "1301 Array"

You could, alternatively, create a new sheet:

Dim wsData As Worksheet

Set wsData = Worksheets.Add
wsData.Name = "1301 Array"
Set TargetRange = wsData.Range("A1")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM