Can I call a dialog, while other dialog is opened? - vba

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.

Related

SAP status message error captured to automatically close

I am new SAP GUI scripting. I have a question regarding to how to stop SAP GUI script running if there's any status messages captured.
I recently create SAP GUI script recording and Excel macro for automation, so far, everything works very well if there's any data collected. However if there's no data collected and will have status bar then the script will become error.
So I tried to find a way to create some code if the status error show up, the script will automatically close, but seems like I only can make it work if the error is only for "No items selected (see long text)". However there are also other few status error will shown up as well, so I'm thinking to make the status bar captured the whole error if possible.
Hopefully you guys can help me regarding this in SAP GUI scripting,
thanks.
If session.findById("wnd[0]/sbar").Text = "No items selected (see long text)" Then
Exit Sub
End If
You can check for the messagetype of the status bar. If it is E then you've got an error.
Instead checking for the text like in your code you check for the messagetype
If session.findById("wnd[0]/sbar").MessageType= "E" Then
' Whatever code is needed here
Exit Sub
End If

How do I fix Error 432 when loading a form in Word VBA?

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.

Publish an excel worksheet as an HTML file using a command button

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.]

VBA error when opening shared file - reading tags is treated as attempt to modify

I have come across a strange error and am looking for some insights.
Scenario:
A powerpoint file on a shared drive is opened by user A. User B now wants to open the same file, and is presented with a "open as read only?" dialog. User clicks "OK".
The file is opened, and an add-in runs (whenever a file is opened) to check for certain tags on slides, indicating presence of confidential material. This causes an error in the following function:
Function taggedSlide(tagName As String)
' find the slide which is tagged with tagName
Dim oSl As Slide
Set oSl = Nothing
For Each oSl In ActivePresentation.Slides
If Len(oSl.Tags(tagName)) > 0 Then <<<<<<<<<<<<<<< this is the line that causes error
Set taggedSlide = oSl
Exit Function
End If
Next oSl
Set taggedSlide = Nothing
End Function
The function ostensibly loops over all slides in the presentation, looks for a tag called tagName, and returns the slide (or Nothing). It looks like this only involves "read" operations, but the code throws an error at the indicated line.
To make things more interesting, the behavior is different if I simply mark a file as "read only", save it, and open it. The difference seems to be that I can modify the file in that case - I just can't save it. But this file cannot be edited at all, even if I don't save it. And the above "read" operation is treated as a "modification"...
I have the following questions:
Is there a document property that I can read in VBA to tell me this is a "cannot modify" file? I am looking for something akin to ActivePresentation.ReadOnly, but that is set for a "read only" file, and this is different.
Why does the line If Len(oSl.Tags(tagName)) > 0 Then get treated as a "modifying file" operation?
It was difficult to reproduce this error, because I really needed to have two users open the same file (saving the file as read-only was not enough) to make it happen. Looking forward to your insights / comments / answers!

Method 'range' of object _global failed when doing nothing

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...