Access.2007.VBA.Bibl..

(John Hannent) #1
Check for the template in the selected template folder, and exit if not found:

strTestFile = Nz(Dir(strTemplateFileAndPath))
Debug.Print “Test file: “ & strTestFile
If strTestFile = “” Then
MsgBox strTemplateFileAndPath _
& “ template not found; “ _
& “can’t create worksheet”
GoTo ErrorHandlerExit
End If

strWorksheetPath = GetWorksheetsPath
Debug.Print “Worksheet template and path: “ _
& strTemplateFileAndPath

Set a reference to the workbook and worksheet, and activate the worksheet:

Set bks = appExcel.Workbooks
Set wkb = bks.Add(strTemplateFileAndPath)
Set wks = wkb.Sheets(1)
wks.Activate

Set a reference to the query:

Set dbs = CurrentDb
Set rst = dbs.OpenRecordset(“qryContacts”, _
dbOpenDynaset)
rst.MoveLast
rst.MoveFirst
lngCount = rst.RecordCount
If lngCount = 0 Then
MsgBox “No contacts to export”
GoTo ErrorHandlerExit
Else
strPrompt = “Exporting “ & lngCount _
& “ contacts to Excel”
strTitle = “Exporting”
MsgBox strPrompt, vbInformation + vbOKOnly, strTitle
End If

Go to the first data cell:

Set rngStart = wks.Range(“A4”)
rngStart.Activate

Loop through the recordset, importing each record to a cell in the worksheet:

With rst
Do Until .EOF

Part II Writing VBA Code to Exchange Data between Office Components

Free download pdf