docmd.TransferSpreadsheet Access --> Excel //// specify destination worksheet AND range

StackOverflow https://stackoverflow.com/questions/21630581

  •  08-10-2022
  •  | 
  •  

Question

I have to write some Access VBA to export data from an Access query into a specific range of cells in an Excel document that has several worksheets.

I am having trouble finding the right way to specify the worksheet AND range.

Here is what I have so far:

docmd.TransferSpreadsheet(TransferType:=acExport, SpreadsheetType:=acSpreadsheetTypeExcel8, TableName:=qry_Main, _
    FileName:="c:\test.xlsm", _
    HasFieldNames:=False, _
    Range:="Main!J9:J10")

The broken piece is Range:="Main!J9:J10"

What's the proper way to make this reference?

Était-ce utile?

La solution

You can use CopyFromRecordset and automation:

Sub XLTrans()
''Reference: Microsoft ActiveX Data Object x.x Library
Dim rs As New ADODB.Recordset
Dim xl As Object ''Excel.Application
Dim wb As Object ''Workbook

Set xl = CreateObject("Excel.Application")

''Pick one
''1. New book
Set wb = xl.Workbooks.Add

''2. Existing book
Set wb = xl.Workbooks.Open("z:\docs\book1.xlsx")

''Connection relevant for 2007 or 2010
rs.Open "MyTableOrQuery", CurrentProject.AccessConnection

wb.Sheets("Sheet1").Cells(4, 5).CopyFromRecordset rs

xl.Visible = True

End Sub

Note that this will not include column headings, but you can add them as well, for example:

For i = 0 To rs.Fields.Count - 1
    Worksheets("Sheet1").Cells(3, i + 5) = rs(i).Name
Next

Autres conseils

http://msdn.microsoft.com/en-us/library/office/ff844793.aspx http://msdn.microsoft.com/en-us/library/office/aa141565(v=office.10).aspx

You cannot use RANGE for exporting: " Range Optional Variant. A string expression that's a valid range of cells or the name of a range in the spreadsheet. This argument applies only to importing. Leave this argument blank to import the entire spreadsheet. When you export to a spreadsheet, you must leave this argument blank. If you enter a range, the export will fail.

"

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top