Macro terminates inside the code without error - vba

After the new document is created (documents.add), the macro pass ends.
I tried the documents.add with parameter (visible:=false) but no effect.
Sub beispiel()
Dim objDokQuelle As Document
Dim objDokZiel As Document
On Error GoTo FEHLER
Set objDokQuelle = ActiveDocument
Set objDokZiel = Documents.Add 'This is the last line to be processed; then the macro terminates
'The following lines are not processed
objDokQuelle.Activate
Selection.WholeStory
Selection.Copy
objDokZiel.Activate
Selection.Paste
FEHLER:
If Err.Number <> 0 Then
MsgBox Err.Description, vbCritical + vbOKOnly, "Error ..."
End If
End Sub
I don't understand what is wrong in this Code, so the macro terminates at the commented line. There are no error Messages.
Thanks for help.

Related

Handling erros for Application.Workbooks without using Error handlers

I am trying to assign an opened workbook to an workbook object. If that workbook is not already opened, then it throws an error. I am handling the errors using an Error Handler.
This works for me:
On Error GoTo OpenWorkbookError
Set Uwk = Application.Workbooks(WbkName)
OpenWorkbookError:
If Err <> 0 Then
Err.Clear
MsgBox ("Please Open the Required Workbook")
Exit Sub
End If
But is there a way to avoid using the error handlers in this situation.
One way to do it is check each workbook name, but what's wrong with the functions in the link that #SJR gave?
In your provided code you've kept the error handler within the main body of code - it should appear between the Exit Sub and End Sub at the end of the procedure.
Something like this would work without an error handler, but it's slower as it needs to check each workbook:
Sub Test()
Dim Uwk As Workbook
Dim WbkName As String
WbkName = "PERSONAL.XLSB"
For Each Uwk In Workbooks
If Uwk.Name = WbkName Then
Exit For
End If
Next Uwk
If Not Uwk Is Nothing Then
MsgBox Uwk.Name & " found!"
Else
MsgBox "Not found."
End If
End Sub
Your version of the code should have the error handler outside the main body:
Sub Test1()
Dim WbkName As String
Dim UWk As Workbook
WbkName = "PERSONAL1.XLSB"
On Error GoTo OpenWorkbookError
Set UWk = Workbooks(WbkName)
TidyExit:
'Close anything that needs closing and Exit.
Exit Sub '<< End of main body of procedure.
OpenWorkbookError:
Select Case Err.Number
Case 9 'Subscript out of range.
MsgBox "Please open the required workbook."
Resume TidyExit
Case Else
MsgBox "Error " & Err.Number & vbCr & _
Err.Description, vbOKOnly + vbCritical
Resume TidyExit
End Select
End Sub '<< End of procedure.

How to trace a 400 error in VBA?

I can't find where the error is. A similar code to pull dynamic file name worked in another tab.
Sub MonthlyBCRCPL()
Dim filePath As String
Dim CardsRCPLWb As Workbook
Set CardsRCPLWb = ActiveWorkbook
filePath = CardsRCPLWb.Sheets("BCRCPL").Range("A1").Value
'Optimize Code
Call OptimizeCode_Begin
Const FlashFolder As String = "\\apacdfs\SG\GCGR\GROUPS\ASEAN\Dashboard\Cards\Flash\"
Flashname = Format(CardsRCPLWb.Sheets("ASEAN - CARDS, RCPL").Range("C2").Value, "YYYYMMDD")
Flashname = "ASEAN SD Regional Dashboard - " & Flashname & ".xlsx"
Flashpath = FlashFolder & Flashname
Dim FlashWb As Workbook
Set FlashWb = Workbooks.Open(Flashpath)
If FlashWb Is Nothing Then MsgBox "SD Flash File does not exist": Exit Sub
Consider handling the error in the subroutine and have it raise a message. Then, properly continues/skips/exits rest of code even releasing objects from memory caught during the exception. This is a best practice in VBA (and generally in programming).
I suspect the path cannot be found which looks to be a network UNC, file naming is not valid such as use of special characters, or workbook does not exist when trying to open:
Sub MonthlyBCRCPL()
On Error Goto ErrHandle:
...code...
ExitSubBlock:
Set CardsRCPLWb = Nothing
Set FlashWb = Nothing
Exit Sub
ErrHandle:
Msgbox Err.Number & " - " & Err.Description, vbCritical, "RUNTIME ERROR"
Goto ExitSubBlock
' Resume Next
End Sub

excel multiple on error goto

I am trying to get multiple on error statements to work and can't figure it out.
If pdf can be found in local then open, if not then open network location. If there is no PDF in then return msgbox.
Sub Cutsheets()
Application.ScreenUpdating = False
Dim finalrow As Integer
finalrow = Cells(Rows.Count, 1).End(xlUp).Row
On Error GoTo net1
If Not Application.Intersect(ActiveCell, Range("A9:A" & finalrow)) Is Nothing Then
'Local Location
ActiveWorkbook.FollowHyperlink "C:\Local" & ActiveCell & ".pdf"
Application.SendKeys "{ENTER}", True
End If
Exit Sub
net1:
If Not Application.Intersect(ActiveCell, Range("A9:A" & finalrow)) Is Nothing Then
'Network Location
On Error GoTo whoa
ActiveWorkbook.FollowHyperlink "P:\Network" & ActiveCell & ".pdf"
Application.SendKeys "{ENTER}", True
End If
Exit Sub
whoa:
MsgBox ("No cutsheet can be found for this item.")
Application.ScreenUpdating = True
End Sub
Also I don't remember why I put sendkeys in there but it doesn't work without it.
Using multiple On Error Goto XYZ handlers for control flow is over-complicating some easy validation checks you can do and then simply use the error handling for actual errors.
As #Rory pointed out in a comment you can use the Dir function. You can combine the use of Dir with an If...ElseIf...Else...End If construct to control what you code does:
Option Explicit
Sub Cutsheets()
On Error GoTo ErrHandler
Dim strLocalCheck As String
Dim strNetworkCheck As String
'check for files - Dir will return "" if file not found
strLocalCheck = Dir("C:\Local" & ActiveCell.Value & ".pdf")
strNetworkCheck = Dir("P:\Network" & ActiveCell.Value & ".pdf")
'control flow
If strLocalCheck <> "" Then
ActiveWorkbook.FollowHyperlink strLocalCheck
Application.SendKeys "{ENTER}", True
ElseIf strNetworkCheck <> "" Then
ActiveWorkbook.FollowHyperlink strNetworkCheck
Application.SendKeys "{ENTER}", True
Else
MsgBox "No cutsheet can be found for this item."
End If
Exit Sub
ErrHandler:
Debug.Print "A real error occurred: " & Err.Description
End Sub
I am trying to get multiple on error statements to work
Don't.
Imagine you're the VBA runtime. You're executing a procedure called Cutsheets, and you come across this instruction:
On Error GoTo net1
From that point on, before you blow up in the user's face, you're going to jump to the net1 label if you ever encounter a run-time error. So you keep running instructions. Eventually you run this line:
ActiveWorkbook.FollowHyperlink "C:\Local" & ActiveCell & ".pdf"
And when the FollowHyperlink method responds with "uh nope, can't do that" and raises a run-time error, your execution context changes.
You're in "error handling" mode.
So you jump to the net1 label. You're in "error handling" mode. There are certain things you can do in "normal execution mode" that you can't (or shouldn't) do in "error handling mode". Raising and handling more errors is one of these things.
On Error GoTo whoa
You're already handling a run-time error: what should you do when you encounter that statement in an error handler subroutine? Jump to the whoa right away?
When the VBA runtime is in "error handling mode", your job as a programmer is to handle runtime errors and do everything you can to get back to "normal execution mode" as soon as possible - and that's normally done with a Resume instruction, or by leaving the current scope.
Copying a chunk of code from the "normal execution path" and trying to run it (slightly altered) in "error handling mode" isn't handling errors and getting back to normal execution mode as soon as possible.
Error handling or not, copy-pasting chunks of code is poorly written code anyway.
Extract a procedure instead:
Private Sub OpenPortableDocumentFile(ByVal path As String)
On Error GoTo ErrHandler
ActiveWorkbook.FollowHyperlink path
Application.SendKeys "{ENTER}", True
Exit Sub
ErrHandler:
MsgBox "Could not open file '" & path & "'."
End Sub
Now that that's out of the way, clean up your control flow by verifying if the file exists before you pass an invalid path to the OpenPortableDocumentFile procedure.
The best error handling strategy is to avoid raising run-time errors in the first place.

VBA Error 91 after correct execution with for each loop and cell comments

I have the following code that works fine until the end of the MsgBox:
Sub CommentsAsFootnotes(myTemplate As Variant, ByRef footnotespage1 As String, ByRef footnotespage2 As String)
Dim rngTemp As Range
Dim rngComment As Range
Dim footnote As String
Dim i As Integer
On Error Resume Next
Set rngComment = myTemplate.Sheets("Seite 1 ").Range("B14:T35").SpecialCells(xlCellTypeComments)
On Error GoTo 0
i = 1
'If rngComment is Nothing
'Exit Sub
'End If
For Each rngTemp In rngComment
rngTemp.value = rngTemp.value & CStr(i)
rngTemp.Characters(Start:=Len(rngTemp.value), Length:=1).Font.Superscript = True
MsgBox rngTemp.Comment.Text
' error thrown here
Next rngTemp
footnotespage1 = footnote
End Sub
The message box is shown with the correct content.
However, when I click "OK", an error is thrown "Error 91, Object variable or with block variable not set" and the debugger highlights the line with the message box.
Do you have any idea what could cause this error?
It's because that current range doesn't have a comment inside, add an IF when the cell doesn't have any comment inside, like this :
If rngTemp.Comment Is Nothing Then
MsgBox "No Comment found !"
Else
MsgBox rngTemp.Comment.Text
End If

On Error GoTo statement is still executing although there is no error generated [duplicate]

This question already has answers here:
Why VBA goes to error handling code when there is no error?
(5 answers)
Closed last year.
I have my code below, the strange thing is that the Errorhandler procedure is still executing even though there are no errors in the code... What can be the issue?
Running the code without any errorhandlers generates no errors, but still the msgbox under Errorhandler shows up when I include an error handling statement!
Code
Public Sub ExportGraphs(Optional PivotExport As Boolean)
' Exports only graphs on the "Mainwindow" sheet to a new worksheet
Dim wsh As Worksheet: Set wsh = Sheets.Add
Dim source_sht As Worksheet: Set source_sht = Sheets("Mainwindow")
ActiveWindow.Zoom = 70
On Error GoTo Errorhandler
With wsh
If source_sht.OLEObjects("Btn_CurrentTime").Object.Value = True Then
.Name = source_sht.OLEObjects("CombBox_Instruments").Object.Value & " " & source_sht.OLEObjects("DTPicker_FROM").Object.Value _
& "-" & source_sht.OLEObjects("DTPicker_TO").Object.Value
Else
.Name = source_sht.OLEObjects("CombBox_Instruments").Object.Value & " " & "Max_Possible_To" _
& "-" & source_sht.OLEObjects("DTPicker_TO").Object.Value
End If
End With
Dim source_chart As ChartObject
Dim target_rng As Range: Set target_rng = wsh.Range("A1")
For Each source_chart In source_sht.ChartObjects
source_chart.CopyPicture xlScreen, xlBitmap
target_rng.PasteSpecial
Set target_rng = target_rng.Offset(20, 0)
Next
If PivotExport = True Then
Debug.Print "se"
End If
Errorhandler:
MsgBox "An export sheet for this ticker and timeline already exists"
End Sub
#dee provided the correct answer.
The Errorhandler: is just a place holder. It does NOT operate like you think. You are using it like an If... Then... statement:
If Error Then
Show MsgBox
Else
Skip MsgBox
End If
As the Errorhandler is just a placeholder and NOT an If... Then..., the code after the placeholder will run regardless of error or no error. To rectify this issue, add an Exit Sub above the Errorhandler: line:
Exit Sub
Errorhandler:
MsgBox "An export sheet for this ticker and timeline already exists"
End Sub
In this piece of code, ErrorHandler: is what is known as a line label.
Errorhandler:
MsgBox "An export sheet for this ticker and timeline already exists"
End Sub
Line labels are not executable code, but rather just a marker that can tell other code where to jump to via any GoTo Statement. Armed with this knowledge, they are obviously not exclusive to error handlers.
The solution here is to use the Exit Statement to return from the Sub "early".
Exit Sub
Errorhandler:
MsgBox "An export sheet for this ticker and timeline already exists"
End Sub
Others may disagree with me, but I like to build my error handling so that the code always stops execution on Exit Sub. If the code ends its execution on End Sub, something has gone wrong.