Okay, here is some sample code that will get you started. Basically what you
need to do is establish an Excel Object, A Workbook Object, and a Worksheet
Object. Then you can read and write to specific cells in the worksheet.
First, you need to establish the above objects:
'Open Excel
On Error Resume Next ' Defer error trapping.
Set xlApp = GetObject(, "Excel.Application")
If Err.Number <> 0 Then
blnExcelWasNotRunning = True
Set xlApp = CreateObject("excel.application")
Else
DetectExcel
End If
Err.Clear ' Clear Err object in case error occurred.
On Error GoTo LoadAdjustedActuals_Err
DoEvents
xlApp.DisplayAlerts = False
xlApp.Interactive = False
xlApp.ScreenUpdating = False
Set xlBook = xlApp.Workbooks.Open(varGetFileName, 0, True)
xlBook.Worksheets("Actuals_res_export").Activate
****************
The above code calls this sub:
Sub DetectExcel()
' Procedure dectects a running Excel and registers it.
Const WM_USER = 1024
Dim Hwnd As Long
' If Excel is running this API call returns its handle.
Hwnd = FindWindow("XLMAIN", 0)
If Hwnd = 0 Then ' 0 means Excel not running.
Exit Sub
Else
' Excel is running so use the SendMessage API
' function to enter it in the Running Object Table.
SendMessage Hwnd, WM_USER + 18, 0, 0
End If
End Sub
**********************
In this example, I am reading data from cells and populating an Access table:
For intRowCount = 3 To intLastRow
rstAccess.AddNew
For intColCount = 6 To 42
rstAccess.Fields(intColCount - 6) = _
IIf(intColCount < 26, ActiveSheet.Cells(intRowCount,
intColCount), _
Nz(ActiveSheet.Cells(intRowCount, intColCount), 0))
Next intColCount
rstAccess.Update
Next intRowCount
*********************
And finally, it is most important to shut it down correctly; otherwise, you
can end up with an instance of Excel still running. You will not see it in
th Applications tab of task manager, it will show up in the Processes tab.
This can cause the computer to hang up if a user tries to open Excel. You
have to be careful about correctly associating all your Excel objects. If
Access cannot figure out what excel object a workbook, worksheet, or other
object belongs to, it will create a new instance of Excel on its own. Your
code will not know about this instance and not kill it, so it will still be
running and cause problems:
xlBook.Close
Set xlBook = Nothing
'If we createed a new instance of Excel
If blnExcelWasNotRunning = True Then
xlApp.Application.Quit
End If
Set xlApp = Nothing
********************
And lastly, before you start, make sure you have a good supply of aspirin
and Preparation H
Good Luck