ghudson
Registered User.
- Local time
- Today, 15:52
- Joined
- Jun 8, 2002
- Messages
- 6,193
I am using the below code to modify all of the worksheets in an Excel file from Access 2003. I will not always know the names of the worksheets. The below code is working [sort of] but it errors at the end with the runtime error # 91 - Object variable or With block variable not set. My test file has seven worksheets. Each sheet is being formatted but it errors and the file is locked because of the runtime 91 error. Looping and automation with Excel is giving me a headache.
Any suggestions of what needs to be tweaked to fix the runtime 91 error?
Also, is there a way to count the number of worksheets and use the number of worksheets found instead of hard coding the instead of Do While x < 8 [worksheets] I would prefer a count variable like
Do While x < iTotalSheets ?
Thanks in advance for your help!
Any suggestions of what needs to be tweaked to fix the runtime 91 error?
Also, is there a way to count the number of worksheets and use the number of worksheets found instead of hard coding the instead of Do While x < 8 [worksheets] I would prefer a count variable like
Do While x < iTotalSheets ?
Code:
Public Sub TEST()
Modify ("X:\MyFile.xls")
MsgBox "end"
End Sub
Public Sub Modify(sFile As String)
Dim xlApp As Object
Dim xlSheet As Object
Dim x As Integer
Set xlApp = CreateObject("Excel.Application")
Set xlSheet = xlApp.Workbooks.Open(sFile).Sheets(1)
x = 1
With xlApp
.Application.Sheets("SHEET1").Select '1st worksheet but I do not like this
Do While x < 8
.Application.Rows("1:1").Select
.Application.Selection.Replace What:=".", Replacement:="#", LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False
.Application.Cells.Select
.Application.Selection.RowHeight = 12.75
.Application.Selection.Columns.AutoFit
.Application.Range("A2").Select
.Application.ActiveWindow.FreezePanes = True
.Application.Range("A1").Select
.Application.ActiveSheet.Next.Select
x = x + 1
Loop
.Application.ActiveWorkbook.Save
.Application.ActiveWorkbook.Close
.Quit
End With
Set xlApp = Nothing
Set xlSheet = Nothing
End Sub