Arvin, thank you for your response. It worked, except I am now having
another problem.
It works once per Access session. I run the code, and the spreadsheet
col. is formatted as it should be. Then, when I run the routine again,
I get the ol' "Object variable or With block variable not set" error.
If I quit Access, it works again, but only once until I quit Access
again. I suspect that the user might want to run the routine more
than once with different parameters without quitting each time...
I've tinkered with it, and it looks like if I comment out just the line
"Selection.NumberFormat = "0.00%", I can run the procedure again and
again with no error without quitting and restarting Access. But of
course, I need that line to properly format my column.
It seems like I am not closing some variable/object or something, but I
can't see where.
Here's a code snippet- edited for simplicity, I hope:
Dim objXLApp As Excel.Application
Dim objXLSheet As Excel.Worksheet
Dim rsTIS As ADODB.Recordset
Set objXLApp = New Excel.Application
objXLApp.Workbooks.Add
Set rsTIS = New ADODB.Recordset
strSql = "SELECT parent_commodity, commodity, VL, costs " & _
" FROM tis " & _
" WHERE " & strWhereString & _
" ORDER BY parent_commodity, costs desc, commodity "
strPrevParentComm = "xyz"
rsTIS.Open strSql, CurrentProject.Connection
rsTIS.MoveFirst
Do Until rsTIS.EOF
strCurrParentComm = rsTIS.Fields("parent_commodity")
If strCurrParentComm <> strPrevParentComm Then
' total costs for current commodity for all VLs
dblCommTotal = DSum("costs", "TIS", strWhereString & _
" AND parent_commodity = """ & strCurrParentComm & """")
' start a new sheet within the workbook
Set objXLSheet = Nothing
Set objXLSheet = objXLApp.Worksheets.Add
objXLSheet.Name = Left(strCurrParentComm, 23) & "- Impact"
End If
' write out the current row MINUS the costs field- need to manipulate
the cost field before writing it
For lngColumn = 0 To rsTIS.Fields.Count - 2
objXLSheet.Range("A" & lngNumRows).Offset(0, lngColumn).Value =
rsTIS.Fields(lngColumn).Value
Next lngColumn
' NOW, write the cost field as a pct of the whole commodity cost
objXLSheet.Range("A" & lngNumRows).Offset(0, 3).Value =
rsTIS.Fields(3).Value / dblCommTotal
' format column D (the cost field) as a pct.
objXLSheet.Range("D" & lngNumRows).Select
Selection.NumberFormat = "0.00%"
strPrevParentComm = strCurrParentComm
rsTIS.MoveNext
Loop
rsTIS.Close
objXLApp.Visible = True
Exit_b_report_click:
DoCmd.Hourglass False
Set rsTIS = Nothing
Set objXLSheet = Nothing
Set objXLApp = Nothing
Exit Sub
b_report_click_ERR:
MsgBox Err.Number & "- " & Err.Description
Resume Exit_b_report_click
End Sub