VBA SAP occasional error Control ID Not Found - vba

In the below code I am extracting data from SAP. In a few SAP reports I am running, occasionally data is not available, in which a pop up box appears, displaying
No Data Exists For Chosen Selection
I've implemented the below error handling strategy, which works fine when debugging and stepping into the code, but running in totality I receive this error on the asterik denoted line:
The Control Could Not Be Found By ID
session.findById("wnd[0]/tbar[1]/btn[8]").press
On Error GoTo ResumeInterCompany
**If session.findById("wnd[1]/tbar[0]").Text = "No data exists for chosen selection" Then**
GoTo TroubleShootInterCompany
End If
Any suggestions. I can provide more relevant code if need be.

My workaround is as follows:
session.findById("wnd[0]/tbar[1]/btn[8]").press
On Error Resume next
myText = "x"
err.clear
myText = session.findById("wnd[1]/tbar[0]").Text
if err.number <> 0 then myText = ""
on error goto 0
If myText = "No data exists for chosen selection" Then
GoTo TroubleShootInterCompany
End If
Regards,
ScriptMan

Related

Skip code if no error occurs by using an "if statement" in VBA

I need some input, since I'm quite new to VBA.
I have a part of a code that is looking for a file in three different path location. The code tries path 1, if error, it will continue to the next path (that's perfect)
My problem is, if the file path is working for code "test 2" and "test 3", It will always run until last one (i.e. "test 3") instead of jumping to next part of code. If the location path works for example for test 1 or test 2 location, I don't need to run the following lines after.
How can I make my code skip that part?
'Test 1 location path
On Error GoTo Err1:
sFldr = "Path1"
Err1:
Resume Next
'Test 2 location path
On Error GoTo Err2:
sFldr = "Path2"
Err2:
Resume Next
'Test 3 location path
On Error GoTo Err3:
sFldr = "Path3"
Err3:
Resume Next
'next part of big code
more code here
If I understand correctly, you need to progressively try values for (in this contrived example) sFldr, and the operation might error. Instead of using On Error Goto, just test the Err object for an error directly:
On Error Resume Next
sFldr = "Path1"
If Err.Number <> 0 Then
Err.Clear
sFldr = "Path2"
If Err.Number <> 0 Then
Err.Clear
sFldr = "Path3"
End If
End If
On Error GoTo 0 'Or resume your normal error handling.
'next part of big code
Call it like this:
If GetFldrValue = vbNullString Then
'whatever you need to do if all 3 fail.
End If
'next part of big code
Another option is to extract the whole thing into its own function (which might not be a bad idea - the comment "next part of big code" indicates that the routine might be doing too much). If you do that, you can just turn error handling off entirely and return the first valid value found:
Function GetFolderValue() As String
On Error Resume Next
GetFolderValue = "Path1"
If Err.Number <> 0 Then Exit Function
GetFolderValue = "Path2"
If Err.Number <> 0 Then Exit Function
GetFolderValue = "Path3"
End Function
One Procedure = One Error Handler.
Simple as that.
Make sure the error-handling subroutine only ever runs in an error state.
I can't really give you a more concrete answer than that, because the code you're showing us does literally nothing; assigning a string literal to a string variable is never going to raise an error, ...and a workflow that jumps around up and down from one line to another in the "normal" execution path isn't sane - you need to restructure things. I'd love to help, but I've no idea what your code does.
To put it shortly, you should have small procedures that look like this:
Private Sub DoSomething()
On Error GoTo CleanFail
'procedure code here
CleanExit:
'cleanup code here
Exit Sub
CleanFail:
'error-handling code here
Resume CleanExit
End Sub
Option 1: Wrap in Function
It would be best to wrap this in a function that is responsible for retrieving the value of sFldr.
Option 2: GoTo Statement - not recommended
Perhaps add a GoTo if the value of sFldr is not null
'Test 1 location path
On Error GoTo Err1:
sFldr = "Path1"
If(sFldr <> "") Then Goto ContinueFunc
Err1:
Resume Next
'Test 2 location path
On Error GoTo Err2:
sFldr = "Path2"
If(sFldr <> "") Then Goto ContinueFunc

Excel VBA error handling not working for second error

In the below code Errorhandler correctly takes care of first error when I enter a workbook that is not open or any random string. But when I click on retry and again enter a random name I get "Subscript out of Range" error # Workbooks(workbookname). Activate.
Can anyone help me why it is happening and how can I make it work. I have tried a lot of things. But nothing is working. This code is part of a larger program.
Sub test()
Dim workbkname As String
On Error GoTo Errorhandler
Retry:
workbookname = InputBox("Enter workbook name:", _
"Name Enrty")
If StrPtr(workbookname) = 0 Then
MsgBox ("Aborting Program")
End
End If
Workbooks(workbookname).Activate
Exit Sub
Errorhandler:
Response = MsgBox("Workbook " & workbookname & " not found", vbRetryCancel)
If Response = 4 Then
GoTo Retry
End If
End Sub
The issue here is that the VBA Error Handler does not clear the error once given a directive like GoTo. As a result, the code thinks that it has encountered an error within your error handling routine and thus throws the error up the stack.
In order to clear the error, you must either call Resume with a place to resume (either Resume alone to run the erroneous code again, Resume Next to resume the line of code following the error, or Resume can be called followed by a label, as below:
Sub ErrTest
On Error Goto ErrHndl
For i = 0 to 5
a = 1/i
nextiLabel:
Next i
Exit Sub
ErrHndl:
Resume nextiLabel
End Sub
You can also use Err.Clear() to remove the error, but that is less recommended.
See here for more info: Error Handling in Excel

VBA MsgBox causes an erro

In my VBA project I have the occasional MsgBox pop up to notify the user something has 'Completed' or 'Updated' after a subroutine has run.
It seems to run okay without the MsgBox, but inserting one seems to give me an error.
Not sure if it's necessary to display the entire code here as it's quite big but at the end of a subroutine I simply want ...
MsgBox ("Completed")
which is followed by the End Sub
However when I run this and then click on OK on the Msgbox, I get a runtime error which on clicking DeBug, it highlights the End Sub.
Is there any reason why having this would throw up such an error?
Am I missing something from it?
Many thanks
Some of the code here
'Add unique data to new location
For i = 1 To UnqArray1.Count
rCell(i, 1) = UnqArray1(i)
Next
'Move Split Array into a new array
Set rTable2 = rCell
rng2() = rTable2.Value
'Filter into unique items
On Error Resume Next
For Each b In rng2
UnqArray2.Add b, b
Next
'Clear location
rCell.Clear
'Add new array to location
For i = 1 To UnqArray2.Count
rCell(i, 1) = UnqArray2(i)
Next
'Find the end of the category list
lastrow = Worksheets("CatMatch").Range("Q100000").End(xlUp).Row
'Sort alphabetically
Worksheets("CatMatch").Range("Q1:Q" & lastrow).Sort key1:=Range("Q1"), order1:=xlAscending, Header:=xlNo
'Copy it to CatMatch
Worksheets("CatMatch").Range("Q1:Q" & lastrow).Copy Destination:=Worksheets("CatMatch").Range("B15")
MsgBox "Completed"
End Sub
I can't reproduce your error, but you are almost certainly incorrect that it runs okay without the MsgBox. The problem is that the problem with your code is being hidden by On Error Resume Next in the fragment:
'Filter into unique items
On Error Resume Next
For Each b In rng2
UnqArray2.Add b, b
Next
Two comments:
1) Why not use the RemoveDuplicates method if that is what you are trying to do?
2) Your code is using the fact that a collection throws an error if you try to add a duplicate key. This is a valid use of On Error Resume Next -- but only if you turn it off when you are done adding keys to the collection. Something like:
On Error Resume Next
For Each b In rng2
UnqArray2.Add b, b
Next
On Error GoTo 0
A good habit to get into is to consider On Error Resume Next and On Error GoTo 0 as defining a block of code, perhaps even indenting the code inside the block as I did above. An even better habit is to not assume that only 1 type of error can happen. The above code is expecting that error 457 might arise (this is the error number corresponding to trying to add a duplicate key -- you need to search documentation to find it, or just run your code without the error handling and see how it crashes). Anything else indicates some other problem. To be maximally safe you can do something like:
On Error Resume Next
For Each b In rng2
UnqArray2.Add b, b
If Err.Number > 0 And Err.Number <> 457 Then
MsgBox "Unhandled error: " & Err.Number
Exit Sub
End If
Next
On Error GoTo 0
Doing this won't solve your problem, but should make your actual problem more apparent.

Error (Run-time error 5) will not raise when "On error resume next" is active

I've provided the actual code I'm using below.
The exact condition I'm trying to handle is the strCurrentRev argument as a zero-length string. (e.g. strCurrentRev="")
If I comment out the error handling statements, trying to execute the ASC method on a zero-length string throws Run-Time Error 5 for "invalid procedure call or argument".
If I then check err.Number it's = 5.
If I try to run the exact same statement with on error resume next active, it will not raise any errors, e.g. after execution err.number is always = 0.
If on error resume next is active, and you try to execute the ASC method from the immediate window (e.g. Type asc(strcurrentrev) and hit Enter) it will throw the run-time error and set the err.number property to 5.
I've never experienced this before. Why would having on error resume next active cause the error not to raise in normal execution???
Function NextRevLetter(strCurrentRev As String) As String
'This function returns the next revision letter given an existing revision letter.
'Declare variables
Dim lngX As Long
Dim strX As String
Dim strY As String
'First, check if we are dealing with rev A-Z or AA-ZZ
If Len(strCurrentRev) <= 1 Then
'Check that we can work with revision letter ***THIS IS WHERE I AM HAVING A PROBLEM!***
On Error Resume Next
Err.Clear
'Procedure call to flag errors with ASC method without changing any values
lngX=Asc(strCurrentRev)
lngX=0
On Error GoTo 0
If Err.Number > 0 Then
Err.Clear
If Len(strCurrentRev) < 1 Then
'No revision specified, assign first revision"
strCurrentRev = "-"
Else
MsgBox "The revision letter specified is not compliant. The next revision letter cannot be determined.", vbOKOnly, "Error: Revision does not follow rules"
'Return the existing revision (no change) and exit function
NextRevLetter = strCurrentRev
Exit Function
End If
End If
'Code continues - not important for this question...
Exit Function
You're not using the right tool for the job. Runtime errors should be handled, not shoved under the carpet (because that's what On Error Resume Next does - execution happily continues as if nothing happened).
You need to try to avoid raising that error in the first place. What's causing it?
lngX=Asc(strCurrentRev)
You already know what's happening:
The exact condition I'm trying to handle is the strCurrentRev argument as a zero-length string.
Well then, the correct way to handle this is to verify the length of strCurrentRev before you pass it to the Asc function, which you know will raise a runtime error #5 if you give it an empty string!
If strCurrentRev <> vbNullString Then
'calling Asc(strCurrentRev) here will not fail!
End If
I was asked to elaborate on a better way to handle the error, and this is the easiest place to do so. I think it's okay, because in a way it does answer the original question as well. However, let me say first that the right thing to do here is to avoid the error entirely, but for the sake of completeness, there is a way to do this cleanly with an error handler.
The idea is to check the error number, handle it by fixing the value, and then resuming the next line of code.
Function NextRevLetter(strCurrentRev As String) As String
'This function returns the next revision letter given an existing revision letter.
On Error GoTo ErrHandler
'Declare variables
Dim lngX As Long
Dim strX As String
Dim strY As String
'First, check if we are dealing with rev A-Z or AA-ZZ
If Len(strCurrentRev) <= 1 Then
'Procedure call to flag errors with ASC method without changing any values
lngX = Asc(strCurrentRev)
lngX = 0
'Code continues - not important for this question...
End If
Exit Function
ErrHandler:
If Err.Number = 5 Then
lngX = 0
If Len(strCurrentRev) < 1 Then
'No revision specified, assign first revision"
strCurrentRev = "-"
Resume Next
Else
MsgBox "The revision letter specified is not compliant. The next revision letter cannot be determined.", vbOKOnly, "Error: Revision does not follow rules"
'Return the existing revision (no change) and exit function
NextRevLetter = strCurrentRev
Exit Function
End If
Else If Err.Number = someOtherExpectedError
'handle it appropriately
Else
' !!! This is important.
' If we come across an error we don't know how to handle, we re-raise it.
Err.Raise Err.Number, Err.Source, Err.Description
End If
End Function
Note that the flow of your program is not interrupted by all of this error handling and we only handle the error that we're expecting. So, if an error is raised, we recover only if we know how to. Otherwise, execution is halted.
I would still prefer just to check to see if the value is = vbNullString though.
I just figured this out. The On Error GoTo 0 statement resets the Err.Number property to 0.
Sorry for wasting anyones time!!!!

is it possible for VBA to detect the error and give a prompt that data not available instead of giving error message?

I have created a GUI that will setup the pivot table.
For example, I click button1 it will run and setup the pivot table.
When I click button3, it will have a run time error 1004 because it does not have the value in the data. So is it possible to let VBA accept that error and show a prompt that that data is not available?
By the way, I'm using this
ActiveSheet.PivotTables("PivotTable1").PivotFields("Test").CurrentPage = "Data1"
to setup the pivot table.
There are 3 different variables; Data1, Data2, Data3. If Data3 is not available, it will show the error but I want to have a prompt to show that it is not available.. If you know how to do it, please share it with me! Thank you!
Yes. For that you need to do appropriate error handling. See this sample code.
Sub Sample()
On Error GoTo Whoa
'<Your REST OF THE CODE>
LetsContinue:
Exit Sub
Whoa:
'~~> This gives the exact desription and the error number of the error
MsgBox "Description : " & Err.Description & vbNewLine & _
"Error Number : " & Err.Number
'~~> This part resumes the code without breaking it :)
Resume LetsContinue
End Sub
I would just do this:
On Error Resume Next ' Don't stop execution when an error occurs.
ActiveSheet.PivotTables("PivotTable1").PivotFields("Test").CurrentPage = "Data1"
If Err.Number <> 0 Then ' Can also check for a specific error number instead
'Oops! An error occured.
MsgBox "Data isn't available."
Err.Clear
End If
On Error GoTo 0 ' Go back to stoping execution when an error occurs.