I have a big macro which basically processes some columns and spits out results based on some cross-checking with an access 2003 database. It works absolutely fine - no hitches at all.
However, I recently had to make a modification to it. It was literally changing an '8' to a '9' in one line of the code. But next time I ran it, it threw the 1004: Method 'Range' of object '_Global' failed error. Excel 2003 is a funny thing - I once scratched my head for hours over this, trying to find offending lines of code that could be causing the error, but alas to no avail. I did something that I didn't expect to trigger anything:
Starting with the original macro (100% confirmed working), if I just open the code up, and then save it so the 'last updated' metadata will update to reflect the save, though absolutely nothing has changed, it will throw that error again on opening.
It's as if it's so fragile that saving the macro as is will break it. Any ideas?
Update: here's what I changed that initially brought about the issue
iOutputCols = 9 'this was changed to 9 from 8
ReDim Preserve sOutputCols(iOutputCols)
sOutputCols(0) = "Policy No"
sOutputCols(1) = "Client"
sOutputCols(2) = "Trans"
sOutputCols(3) = "Effective Date"
sOutputCols(4) = "ClosingRef"
sOutputCols(5) = "Gross"
sOutputCols(6) = "Comm"
sOutputCols(7) = "Net Due"
sOutputCols(8) = "Risk" 'this line was added
Making the change here, while originally causing the error, doesn't seem special - I did small changes like the above elsewhere in the code and in other modules, one time I even did something as testval = "test" and even that redundant line will produce the error. The most minimalistic way to cause it? Simply open it up, save it without changing anything, and on next use the error occurs.
The error occurs at this line, in a completely different code section which is part of a form:
If strErr <> "" Then MsgBox strErr, vbInformation + vbOKOnly, "Action Error"
Application.ScreenUpdating = True 'error occurs here, message box which shows me the error right above
End Sub
Update 2
Removing the error handling throws the error on this line
Case "> Send Next Period Reminder" 'error on line below
Call ReplaceText(wordApp, "[office_address]", Range("Address_" & Worksheets("UserParms").Range("F6").Value).Value) 'error this line
Call ReplaceText(wordApp, "[office_address2]", Range("Address2_" & Worksheets("UserParms").Range("F6").Value).Value)
'more of the same replacetexts below
For context, this is when an option is selected for "Send Next Period Reminder", which pulls a word .dot template from a static folder and populates it based on the data selected within the sheet (Hence the replace texts). This is in a different module and has never been touched before.
Try properly qualifying your Range method calls. You have lines like this:
Call ReplaceText(wordApp, "[office_address]", Range("Address_" & Worksheets("UserParms").Range("F6").Value).Value) 'error this line
Call ReplaceText(wordApp, "[office_address2]", Range("Address2_" & Worksheets("UserParms").Range("F6").Value).Value)
While it may not be obvious, there are cases, both environmental and code-based, where these unqualified uses of Range could fail. Change the references like Range("Address... to something like yourTargetWS.Range("Address...
Related
I have inherited a hideous Excel VBA application, written by a guy who apparently didn't like functions and comments. Opening the source code is like staring into an abyss of madness, with 9 levels of hell indentation awaiting to trap the unwary.
First, the setup.
In the process of debugging an intermittent issue, I have identified a particular line in the primary function as its location. Since the exception is not easy for me to fix, I gave this line, and only this line, an error handler that displays a custom message.
' Lots of stuff cut out
On Error GoTo TechReleaseBuildError
lb_Err1 = BuildDirectories(gj_TechBld.mt_TechRlsOutDir)
On Error GoTo 0
' Lots of stuff cut out
Exit Sub
TechReleaseBuildError:
MsgBox "Error building tech release. Pause the synchronization software and try again."
Stop
Resume
End Sub
The Stop and Resume are only there to help debugging, since the normal error messages that pop up don't have an option to debug the error.
Within the BuildDirectories function, I have identified one line that was causing the error that was being kicked up to primary function. I have placed error handlers in this function as well.
' Lots of stuff cut out
Exit Function
TEST:
Stop
Resume
SynchroRetry:
Dim CurrentError As ErrObject
CurrentError = Information.err
SynchroRetryCounter = SynchroRetryCounter + 1
Debug.Print "Synchro Error, retrying #" + SynchroRetryCounter
Stop
If SynchroRetryCounter > 5 Then
Stop
Information.err.Raise CurrentError.Number, CurrentError.Source, CurrentError.Description, CurrentError.HelpFile, CurrentError.HelpContext
Else
Application.Wait Now + #12:00:03 AM#
Resume
End If
End Function
At the very beginning of BuildDirectories I have placed an On Error GoTo TEST statement as a catch-all error handler so I can identify what lines they are coming from, and also used the SynchroRetry handler for the one line that I already know causes an issue, which I immediately reset back to the TEST handler. The SynchroRetry handler just waits for 3 seconds and retries, failing after the 5th retry.
' For some reason, this line (and only this line so far) causes problems when synchronization software is running.
' The error handler waits for a few seconds then tries again a few times.
Dim SynchroRetryCounter As Integer
SynchroRetryCounter = 0
On Error GoTo SynchroRetry
lj_FSO.CopyFile Source:=lt_RPOFilePath & lt_RPOFileName, Destination:=lt_VinRposDir & "\" & lt_RPOFileName, OverWriteFiles:=True ' Trouble line
On Error GoTo TEST
I have verified with Find that these are the only 3 On Error statements in the function (the only ones in the module, even). The top-level function also has no On Errors other than the two shown.
In brief summary, the top-level function has an error handler on only one line, and the function it encloses also has two error handlers inside it, one for one of its known troublesome lines and a general one that should be encompassing the entire function.
The problem is that some error is occurring that is causing my "Error building tech release." message to display, but does not seem to be triggering the TEST or SynchroRetry error handlers. I cannot imagine how this is possible. I'm relatively new to VBA's monstrosity of an error handling model, but I don't believe I did anything wrong. Did I miss some subtlety here? How is an exception able to bypass my handlers and bubble up the stack like this? I do not believe the assignment or passing of the function value could cause the problem, since their just a Boolean and String value. The problem is also intermittent, and only appears when we have file synchronization software active on the directory this program is copying files to.
So a couple hours after I posted this, I managed to figure it out.
The reason that the Debug button wasn't on the error boxes is because in Options the Error Trapping was set to "Break on Unhandled Error". Changing it to "Break in Class Module" brought the button back.
The reason the exceptions were bypassing my error handlers is because they were happening in my SynchroRetry error handler. In particular, I had to change the first few lines from this:
Dim CurrentError As ErrObject
CurrentError = Information.err
SynchroRetryCounter = SynchroRetryCounter + 1
Debug.Print "Synchro Error, retrying #" + SynchroRetryCounter
to this:
Dim CurrentError As New ErrObject
Set CurrentError = Information.err
SynchroRetryCounter = SynchroRetryCounter + 1
Debug.Print "Synchro Error, retrying #" + CStr(SynchroRetryCounter)
Note the additions of New, Set, and CStr.
Problem solved.
I have a Word .dot file which works in older versions of Word but fails with error 432 when run in Word 2013.
When I debug the code I have the line:
Load customerForm
And VBA shows the error:
Run-time error '432': File name or class name not found during Automation operation
The project "pennyscode" includes "Module1" which contains the function being debugged, "ThisDocument" and a form called "customerForm".
I have tried changing the name to "pennyscode.customerForm" but this doesn't make any difference.
This code is being called from a Sub function which is called from Document_New().
Updates
I can place a breakpoint on the Load customerForm line and demonstrate that it is the line that is causing the problem. If at this point I mouse over the word "customerForm" VBA comes up with
customerForm = <Object variable or With block variable not set>
If I delete/skip the Load line then the next line is customerForm.Show and that produces the same error.
If I just open the .dotm file and then use Alt-F11 to open VBA, I can look at the code for selectCustomer, list properties/methods and customerForm appears in the list.
Additional Note
I believe that within the Load function it must be calling GetObject and it is this that is failing. It is as if VBA can't find the customerForm object even though it appears in the project.
I've posted the full code of the function being called from Document_New below.
Sub selectCustomer()
Dim Doc As Document
Set Doc = Application.ActiveDocument
If Doc.CustomDocumentProperties.Item("Customer") = "Nothing" Then
Load customerForm
customerForm.Show
Unload customerForm
Doc.Fields.Update
a$ = Doc.CustomDocumentProperties.Item("InvoiceNumber")
a$ = customerForm.pathBox.Value + "\" + a$
Doc.SaveAs (a$)
End If
End Sub
I've also posted the full .dotm (Excel 2013) and .dot (previous excel) and some sample data (.xls) here:
Dropbox/Public/Invoice 2015-16.dotm
Dropbox/Public/Invoice 2015-16.dot
Dropbox/Public/data.xls
Update
I've not had much luck making progress on this question. Can anyone suggest an approach to investigating this? Or how I might improve the information on the question?
I finally managed to fix this, and I have a few learnings.
Firstly the debugger shows the error as occurring on the Load customerForm line, but this is actually not the case.
The customerForm has an _Initialize function which loads data into it before it is displayed. This function was failing with but the debugger stops on the wrong place.
I was able to debug this more effectively by putting a breakpoint on the start of the _Initialize sub and then stepping through the code.
Once I had discovered this I realized that the code was failing to find the XLSX file due to a wrong path, thus causing the run-time error.
Once I'd fixed up all the paths, I then hit a second error: runtime error '9' which is a subscript problem. This also reported on the Load customerForm line and was also due to a problem with the _Initialize function.
This was the true source of the problem, and demonstrated a functional change between Office 2013 and previous versions of Office.
My code was opening an XLSX file and attempting to read data from it:
Dim myXL As Object
Dim myWS As Object
Set myXL = GetObject("C:\Test\data.xlsx")
myXL.Application.Visible = True
myXL.Parent.Windows(1).Visible = True
Set myWS = myXL.Application.Worksheets("Customers")
The run-time error 9 was due to the index of the Windows property, as their were no windows. In previous versions of Office, there was a single window, with 2013 the array is empty.
After much messing about I tried adding this line:
myXL.Activate
before accessing the Windows() array. Once that was executed Windows(1) existed and the code worked as before.
Hope this can help someone else struggling with similar problems.
So I have tons of data in my workbook that I need to pass on to my users in a way that allows them to interact with the workbook..., but also limits what they can actually do. So I have made it so they can access certain pages to Add needed data, then I've given access to a menu page so they can run a report.
This report I have found is best if it's an html page.
To that end, I have tried several different ways, save as...and publish. I like the publish version, but I can not for the life of me get this working. All the samples I see, appear to be the same. Here is the line of code in question:
ActiveWorkbook.PublishObjects.Add(xlSourceSheet, ActiveWorkbook.Path & ".htm, "Sheet1", "", xlHtmlStatic, "", "Report Title").Publish True
Every time I get a run time error '1004':
Method 'Publish' of object 'PublishObject' failed
I have the above line of code in a sub, am I missing something? Do I need to set up the publish differently? Thanks for any ideas.
I have had a similar mysterious problem that sometimes it (.Publish) works and sometimes it doesn't, when I try publish.
However, I think the problem might be, in cases when it doesn't work right off the bat, to first save the relevant region as a webpage so that it exists already on the server. After that region has been saved at least once (manually or else maybe with .SaveAs .. see below), then the publish might work.
Here is an example of how I get this to work more consistently, something to convey the structure that works for me:
wkb=ActiveWorkbook.Name 'save wb for later access
url="http://a.com/b.htm" 'save to Internet
sheetname="c"
Sheets(sheetname).Range("d1:e2").Select 'activating sheet may be necessary
On Error Resume Next 'anticipate error to handle it
'Now comes the publish line the first time... which may work.. or not
ActiveWorkbook.PublishObjects.Add(xlSourceRange,url,sheetname,"d1:e2",xlHtmlStatic,"blah","moreblah").Publish (True) 'may fail to create page on website if page didn't already exist
theerr=Err.Number
On Error GoTo 0 'back to default error handling (none)
If theerr <> 0 Then 'if here perhaps because page nonexistent
'msgbox "maybe add warning here [FYI]"
Sheets("dummysheetwithlittleornodata").Copy 'will create workbook
On Error Resume Next
ActiveWorkbook.SaveAs url 'may fail to create webpage first time
ActiveWorkbook.saveAs url 'twice needed for some reason sometimes. [works for me]
On Error GoTo 0
'with fresh dummy html page created, now publish should hopefully work.. let's try again
ActiveWorkbook.Close savechanges:=False 'clean up and avoid popup
Workbooks(wkb).Activate 'get back to correct wkb
Sheets(sheetname).Range("d1:e2").Select
ActiveWorkbook.PublishObjects.Add(xlSourceRange,url,sheetname,"d1:e2",xlHtmlStatic,"blah","moreblah").Publish (True) 'hopefully if failed first time, now it succeeded ! good luck.
End If
The above code structure has allowed me to solve several publish problems I was having. All the techniques together have been enough so far to allow me to save a range from a sheet as a webpage (to server I have write access to) without having to do anything manually (like a manual save or even click on popup). Good Luck.
[The different non-obvious techniques include activating a range before trying a range publish, using the error handling approach and anticipating failure at certain points, the 2x saveas to compensate for mysterious inconsistent failures when using one saveas only, closing and getting back to original workbook cleanly, and using saveas to "guarantee" page exists in form that will make publish to succeed more consistently.]
I have a VBScript that errors when I try to get Excel's status bar string. See comments in code below. I tried putting objExcel.DisplayStatusBar = True in above the erroneous line, but then that line errors. That tells me something about objExcel is going wrong(?). If I put in a msgbox just prior to the erroneous line, it hangs the entire vbs (expected). This vbs runs in the morning so when I see the msgbox popup and click OK all systems have already completed except the vbs that is hanging because of the msgbox. I click OK on the msgbox and I get no error. The reason I am waiting with a timed loop is because macro CreateModel has some Application.OnTime calls in it back to CreateModel, which is necessary for reasons that are beyond this question. The VBScript doesn't 'know' that I have OnTime calls so if I don't 'wait' it will proceed with the rest of the vbs code and mess things up for other reasons. So I have to wait and I use the statusbar to know when all is finished. I can't do a purely timed wait because the processing time of CreateModel and its associated OnTime calls varies quite a bit.
It is a little confusing. Looking for debug suggestions and/or solutions if you have any.
EDIT: if someone knows how to create the error "call rejected by callee" for line sStatus = objExcel.StatusBar, that would help me debug this.
EDIT2: Here is a picture of the error. The script is a .vbs file. I had to grey out the path for my clients protection:
VBScript:
Dim objExcel, wMn, r, wT
Set objExcel = CreateObject("Excel.Application")
Set wMn = objExcel.Workbooks.Open("Z:\path\Model_*.xlsm")
objExcel.Application.Visible = True
objExcel.Run "'Z:\path\" & wMn.Name & "'!CreateModel"
'wait until model is finished
'have to do this because Application.OnTime is called in CreateModel and vbs doesn't wait
Dim sStatus
Dim dteWait
Do
dteWait = DateAdd("s", 600, Now()) '60 = 60 secs, 600 = 10 mins
Do Until (Now() > dteWait)
Loop
'objExcel.DisplayStatusBar = True '<-- if I include this line I get the same error, but for this line
'msgbox objExcel.StatusBar '<-- when I include this line no error occurs, see notes at top
sStatus = objExcel.StatusBar '<-- main error/issue
Loop While not sStatus = "Model Finished"
'more code below, but omitted for clarity
I would designate a cell, give it a named range value ("macroDoneCheck", for example), and have the macro load a "done" value that you can check for in your VBS. The loop for waiting/checking this cell value in your VBS is something like:
Do
WScript.Sleep(30000) 'wait 30 seconds
isDone = objExcel.Range("macroDoneCheck")
Loop While not isDone = "Complete"
Or something like that. You may need to specify the sheet as well, like:
isDone = objExcel.Sheets("Sheet1").Range("macroDoneCheck")
I credited n8. with the best answer because it is a better approach, but this answer is less work and it worked fine.
From my original code/question, wrap sStatus = objExcel.StatusBar like this:
on error resume next
sStatus = objExcel.StatusBar
on error goto 0
Again, just an alternative to the answer n8. provided. It works because for some reason accessing the statusbar while CreateModel is still running produces and error, but in my case the while loop continues to loop because the while condition has not been met. I knew the while condition would eventually be met, even if accessing the statusbar produces an error some of the time, because when I hang the vbs with the msgbox (see notes in code in original question) everything works with no issues if I let it hang long enough. This may be a specific issue that others may not experience, so take it for what it is worth.
I have a macro, which is called on event SelectionChange. This macro have to check, what template is attached to the document. It is possible, that attached template doesn't exist on computer that is opening the document. I need to know, when this occurs, so I can't use ActiveDocument.AttachedTemplate (it would show simply Normal.dot, when template doesn't exist). So, I use:
Application.Dialogs(wdDialogToolsTemplates).Template
And that works fine.
But, when I try to find something in document by ctrl+F, selection is changed while searching and event fires. Macro is called, but on the line above I get an error:
This method or property is not available because the find and replace dialog box is active
So, the question is - is there a way to use this property, while the find and replace dialog box is active...? Or mabe - is there a way to check, if find and replace dialog box is active?
As I suggested in comment you could try to use On Error Resume Next to get rid of the error you have. However, I made some tests and that could be interesting for you what I have found out. You could add error handling in two ways which will have different outcomes.
'1st attempt will keep Find-Replace window and it will omit error
On Error Resume Next
Debug.Print Application.Dialogs(wdDialogToolsTemplates).Template
On Error Goto 0
'2nd attempt will close Find-Replace window and will return template name
On Error Resume Next 'this seems to be unnecessary anyway
Dim tmpDialog As Dialog
Set tmpDialog = Application.Dialogs(wdDialogEditFind)
'Find-Replace window will be closed at this stage
Debug.Print Application.Dialogs(wdDialogToolsTemplates).Template
Tried and tested for Office-Word-2010.