Detailed QueryTables Error Handling - sql

Good Afternoon,
I am looking for a way to handle QueryTable Errors. I have looked at other questions on google and stackoverflow, however they do not appear to answer the specific question i am trying to ask.
Basically, is there a way to determine what the specific error was when handling a QueryTables error?
Code:
On Error Goto queryError
With Activesheet.QueryTables...
....
End With
queryError:
Msgbox("There was an error with the QueryTables. The reason for the error was: " & myError)
Is there a way to set myError to give more details specific to what the problem was, even if it means selecting some sort of status code? eg
QueryTables.StatusCode...
or something?
Thanks in advance.

How to handle errors:
Excel VBA doesn't supportTry Catch Finally. Instead, it uses On Error GoTo
For full control over error-handling in Excel you must use labels (which always end in a colon).
In this example, the two labels are:
tryAgain:
queryError:
Assume that the Query Table being created is from a text file that looks something like:
When you first run the routine, the user is prompted for three inputs:
Filepath
New Table Name
Cell (i.e. Range) to paste into
If an error occurs on any of these inputs, the code will immediately go to the label queryError:
So, say the user didn't enter in a valid filepath, it would look something like this:
If the user clicks Yes (to try again), then Resume tryAgain will take the code back up to that label and go through it all over.
Pay attention to the Select Case at the end. This is how you can control how you want to handle specific errors.
Here is the code to paste in a module:
Option Explicit
Sub CreateQueryTable()
'Assign values to these variables by prompting user with Input Boxes
Dim filepath As String
Dim qryTableName As String
Dim startCellForTable As Range
'These variables are used in the error handling prompts
Dim Msg As String
Dim Ans As Integer
'If an error occurs, code will go to the label `queryError:`
On Error GoTo queryError
tryAgain:
'Prompt user for the filename of the .txt file to use as QueryTable Source
filepath = InputBox("Please enter filepath of text file to use as the source")
'Prompt user to name the new Query Table
qryTableName = InputBox("Please enter name of Query Table")
'Prompt user for the cell to put table at
Set startCellForTable = Application.InputBox(Prompt:="Please select a cell where you would like to paste the table to", Type:=8)
'If user hits OK, check to see that they at least put something as a value
If filepath <> "" And qryTableName <> "" And startCellForTable <> "" Then
'format filepath variable so can pass it as argument to QueryTables.Add
'Trim any leading or trailing spaces from qryTableName
filepath = "TEXT;" & filepath
qryTableName = Trim(qryTableName)
End If
'Create QueryTable at Range("A1")
With ActiveSheet.QueryTables.Add(Connection:=filepath, Destination:=Range(startCellForTable.Address))
.Name = qryTableName
.Refresh BackgroundQuery:=False
End With
'If there are no errors, exit the procedure (so the `queryError:` code won't execute)
Exit Sub
queryError:
Msg = ""
'Say that an error occured
Msg = Msg & "An error occurred with the Query Table. " & vbNewLine & vbNewLine
'Use Excel's built-in Error object (named `Err`) to show error number and description of error
Msg = Msg & Err.Number & ": " & Error(Err.Number) & vbNewLine & vbNewLine
Select Case Err.Number
'Type mismatch
Case 13
'Object required
Case 424
Msg = Msg & vbNewLine & "Please check that a valid range was selected" & vbNewLine
'Application defined or Object defined error
Case 1004
Msg = Msg & vbNewLine & "Please check that this filepath is correct: " & vbNewLine & vbNewLine & filepath & vbNewLine
Case Else
End Select
'Prompt user to Try Again
Msg = Msg & vbNewLine & vbNewLine & "Try again?"
Ans = MsgBox(Msg, vbYesNo + vbCritical)
'If user says Yes, clear the error, and resume execution of code at label `TryAgain:`
If Ans = vbYes Then Resume tryAgain
End Sub

Related

VBA Access 2010 DIR results in empty string

I have the following code:
Private Sub cmdExportTERNAME_Click()
On Error Resume Next
Me.MsgFld = "Please wait... exporting TERNAME file."
Dim expLoc As String
Dim xFile As String, myFile As String
Dim myFlag As Integer
expLoc = "I:\Investigative Names\" ' PRD
xFile = Dir(expLoc & "NAME - ForUpload.txt", vbDirectory)
myFile = "NAME-ForUpload.txt"
myFlag = StrComp(xFile, myFile)
If myFlag <> -1 Then
Kill expLoc & "NAME-ForUpload.txt"
End If
' Export text files for upload
DoCmd.TransferText acExportFixed, "SpecTERNAME", "qry_TERNAME", expLoc & "NAME-ForUpload.txt"
xFile = Dir(expLoc & "TNAME-ForUpload.txt")
myFile = "NAME-ForUpload.txt"
myFlag = StrComp(xFile, myFile)
If myFlag <> -1 Then
GoTo ContinueProcessing1
Else
MsgBox "The program was not able to export the NAME file for upload." & Chr(13) & Chr(13) & "Please notify IS Department.", vbCritical, "ERROR MESSAGE BOX"
GoTo exitRTN
End If
ContinueProcessing1:
exitRTN:
End Sub
So I have 2 more of these subroutines with different text files which work fine but this block of code doesn't find xFile, it return a empty string which causes the program to display the message box error. I can't figure out why the same code with different text file works before it reaches this code. The weird thing is it sometimes finds the correct xFile name in debug mode but not when run normally. Can someone help me figure this out?
Thanks

VBA error 1004 Sorry, we couldn't find

I've receive the above error for the following code:
Dim location_results As String
location_results = Worksheets("merging").Range("B1").Text 'absorbing the initial computation results folder
file_results = Dir$(location_results & "\" & "*" & NBDID & "*" & ".*") 'checks if there is a file with NBDID in the "location results folder
If (Len(file_results) > 0) Then
Worksheets("list").Range("D" & i).Value = file_results
Else
MsgBox (NBDID & " result not found")
End If
'problem todoB:
lineD:
Dim shortlocation As String
shortlocation = ThisWorkbook.Path & "\megaresults\" & file_results
On Error GoTo lineD
'Workbooks(shortlocation).Open
Set InputFile = Workbooks.Open(FileName:=shortlocation)
'Set InputFile = Workbooks.Open(location_results & file_results)
Set OutputFile = Workbooks.Open(location_merger & file_merger)
On Error GoTo 0
The error is raised on the line:
Set InputFile = Workbooks.Open(location_results & file_results)
and on the line:
Set InputFile = Workbooks.Open(FileName:=shortlocation)
Now googling that error, nearly everyone has an issue that the file they are trying to open is not in the parents-workbook folder, or that they did not preappend their path to the file specification.
I have done that however, and the path is validated, both manually by me checking whether the file is in the folder, as well as with:
If (Len(file_results) > 0) Then
Worksheets("list").Range("D" & i).Value = file_results
Else
MsgBox (NBDID & " result not found")
End If
, the file exists, and the total path, including file name and extention is 222 characters long. It also contains spaces.
But I can't find any reason for it to return as an error. On top of that, the on error goto lineD does not function, it still pops up with a message that does not allow continuing of the code.
Could someone point out my mistake to me, or give me a solution that would work?
Kind regards.

Access 2016 VBA Run-Time Errors - How to catch?

Apologies in advance - This could be a long one - All Code added in the bottom.
I'm working on a database for tracking support tickets.
I've been trying to clear up the errors that have been popping up with the tracker - so I started working an rebuild - Cleaning code - Changing field names etc - It was an entirely new database that no one had access to. But for some reason, my error code doesn't seem to catch any more. So let me explain everything.
The front end is opened and on open, loads the login form - This utilizes DLOOKUP to check and match passwords - This is fine
After logging in, the ticket entry form loads (Frm_ticket_Entry) this has multiple fields for data and 2 buttons. (I'll only list a few as none are actually mandatory)
Field names:
Ticket_Number - (fairly self explanatory)
Agent - (Agent working ticket)
Return_Team - (if ticket was returned)
Buttons:
New Record - (Adds a new record - Guess you can tell that)
Save Record - (saves record after data changes)
When using Err.raise("error number") - My catcher works as expected
When I turn err.raise off (comment out) and run everything - I sometimes hit "Run-Time Errors" (Such as locked for editing) on my previous DB version - This was caught by my error catcher - and produced the custom output - Now, it does not seem to want to catch the run-time errors - Why not, what is going wrong!?
(apologies for the extensive read - I struggle to describe things accurately, but briefly. - Further info available if required / Requested)
Code for "New Record":
Private Sub btn_NewRecord_Click()
DoCmd.GoToRecord , , acNewRec 'Add a new record
Me.Ticket_Number = "#" ' Change ticket number textbox to "#"
Me.Kickback_Reason = "Pass to next level support" ' - Set Default entry for kick back reason
Me.Agent = User() ' Set "Agent" field to the currently logged in user
Me.Returning_Team = "CSC Service Desk" ' Set default for "Returning Team"
DoCmd.RunCommand acCmdSaveRecord 'Save the record into the table
DoCmd.GoToRecord acDataTable = tbl_Tickets, , acLast ' return to the last saved record
On Error GoTo Error_Handle
' Err.Raise 3314, "btn_New_Record_Click()", "Errored" ' Force error for debug purposes
' Err.Raise 2105, "btn_New_Record_Click()", "Errored"
' Err.Raise 21345, , "Unknown Error Occured"
Exit Sub
Error_Handle:
Call ErrorLogger(Err.Number, Err.Description, Err.Source)
Err.Clear
MsgBox "Error Trapping complete"
Resume Next
End Sub
And code for ErrorLogger:
Function ErrorLogger(ErrNum As Integer, ErrDesc, ErrSrc As String)
Select Case ErrNum
Case 3314 ' You must enter a value in the 'tblKickbacks.Ticket Number' field.
MsgBox "It seems some required fields may not have been completed! " _
& "Please ensure you have filled in 'Ticket Number' / 'Agent' / 'Returning Team' and/or 'Kickback Reason'"
If IsNull(Me.Ticket_Number) Then
Me.Ticket_Number.SetFocus
End If
If (MsgBox("Error " & ErrNum & " occured." & vbNewLine _
& "Details : " & ErrDesc & vbNewLine _
& "Error occured in : " & ErrSrc & vbNewLine _
& "Would you like to send an email error report?" _
, 4 Or 16, "ERROR DETECTED")) = vbYes _
Then
GoTo DevEmail
Else
GoTo Err_Exit
End If
Case 2105 ' You can't go to the specified record.
MsgBox "Error Caught - 2105"
Case 3218 ' Error Description: Could not update; currently locked.
' Need to find and add code here for forcibly unlocking any and ALL locked records
Case Else
MsgBox "Error : " & ErrNum & " -- " & ErrDesc & " " _
& "Not recognised - Sending error email"
GoTo DevEmail
End Select
DevEmail:
Dim oAPP As Outlook.Application
Dim oMail As Outlook.MailItem
' Create the Outlook session.
Set oAPP = New Outlook.Application
' Create the message.
Set oMail = oAPP.CreateItem(olMailItem)
With oMail
' Add the To recipient(s) to the message.
.To = "mwalker53#csc.com"
.Subject = "Tracker V2 Error"
.Body = "Error message as Follows:" & vbNewLine _
& "Error Number: " & ErrNum & vbNewLine _
& "Error Description: " & ErrDesc & vbNewLine _
& "Error Source: " & ErrSrc
.Send
End With
MsgBox "Email has been sent"
Err_Exit:
End Function
Move On Error GoTo Error_Handle at first line.
Private Sub btn_NewRecord_Click()
On Error GoTo Error_Handle
...
End Sub
There's nothing between on error goto errhandle and exit sub you need that line above the code that adds the new record

Message Box referring to cell contents

I cant get the syntax right for a msgbox. I want the box to say:
You have indicated that"
"employee name" (a range reference to a cell the worksheet)
has worked for "hours" (a range reference to a cell the worksheet) doing "job" (a range reference to a cell the worksheet)
Is this information correct?
This is what I have (shortened slightly):
Public confirmation_yes_no()
Dim yesornoanswertomessagebox As String
Dim questiontomessagebox As String
questiontomessagebox = "You have indicated that" & worksheets("dept 1 input").range("g12"),"worked at" & worksheets("dept 1 input").range("g16"), "for" & worksheets("dept 1 input").range("g16"), vbinformation, "Are you sure that this data is correct?"
yesornoanswertomessagebox = MsgBox(questiontomessagebox, vbYesNo, "FlightPlan for Profits PRO")
If yesornoanswertomessagebox = vbNo Then
MsgBox "Return to Data Input to correct error(s)", 0, "FlightPlan for Profits PRO"
Else
MsgBox "Great! Press Enter", 0, "FlightPlan for Profits PRO"
End If
End Sub
I am assuming, of course, that this is possible.
Couple of things with your code,
The opening line of your sub, Public confirmation_yes_no(), what is it, is it a sub, function or what, the way it's written right now it is a global variable declaration.
When combining elements into one like with your string, always use & but be sure to manually put spaces around it, otherwise it is not recognized. &var1 <> & var1
Be cautious when setting the arguments in a variable to be used later and definitely don't set them twice.
If you use a qualifier a lot, like Worksheets("dept 1 input"), consider using a With statement like below, this saves you from having to type the bit on the With statement over and over. Please note that to make use of the with statement, you write . in front of the code..Range(... points to the sheet which is set by the With statement.Range(... points to the sheet which Excel considers to be active.
When combining variables with text, take into account that the variables most likely do not have leading and trailing spaces, and that you'll have to compensate for this in the string bits.
for readability you can add an _ to your code to indicate it continues on the next line instead of having a very, very long line.
You can use a message box directly in an If statement.
Corrected code
Public Sub confirmation_yes_no()
Dim questiontomessagebox As String
With ThisWorkbook.Worksheets("dept 1 input")
questiontomessagebox = "You have indicated that " & .Range("G12") & " worked at " _
& .Range("G16") & " for " & .Range("G16") & "." _
& vbCr & vbCr _
& "Are you sure that this data is correct?"
End With
If MsgBox(questiontomessagebox, vbYesNo, "FlightPlan for Profits PRO") = vbNo Then
MsgBox "Return to Data Input to correct error(s)", 0, "FlightPlan for Profits PRO"
Else
MsgBox "Great! Press Enter", 0, "FlightPlan for Profits PRO"
End If
End Sub
Hi you missed the "&" signs. So i Correct it for you.
questiontomessagebox = ("You have indicated that " & Worksheets("dept 1 input").Range("g12") & " ,worked at " _
& Worksheets("dept 1 input").Range("g16") & " for " & Worksheets("dept 1 input").Range("g16")) & Chr(32) & _
vbInformation & vbNewLine & " Are you sure that this data is correct?"

Excel VBA & VB6 Printer

I have the following code, this code was written in VB6 but i can not open the form or check any references.
Private Sub PopulatePrinterCombo(cmbDestination As ComboBox)
Dim objPrinter As Printer 'a printer in the Printers collection object
'Add the printers to the combo box
For Each objPrinter In printers
cmbPrinter.AddItem objPrinter.DeviceName
Next
'Set current selection to the default printer
cmbDestination.Text = Printer.DeviceName
End Sub
I am currently copying the code onto Excel VBA macro, the problem is the Dim objPrinter As Printer code, i keep getting an error message saying "USER DEFINED TYPE NOT DEFINED", do i need a reference to add on VBA to be able to get the option of declaring a variable as a "Printer" or something?
My second question is that i do not fully understand the "Printers" in the line For Each objPrinter In printers, what is "Printers"? can someone please explain that to me.
Thank you
PART 2
I am now trying to print files, i have the following as my code:
'Initialize values
intDraftsPrinted = 0
If objDraftPaths.Count > 1 Then
Else
intSelectedDraftCount = CountSelectedDrafts
End If
'prompt user to make sure
intMsgBoxResponse = MsgBox("You selected " & intSelectedDraftCount & " part numbers. After removing duplicates" & vbNewLine & "there were " & objDraftPaths.Count & " unique draft files found." & vbNewLine & "Do you want to print these files?", vbYesNo, "TD Printer")
If intMsgBoxResponse <> vbYes Then
intSelectedDraftCount = 0 'So the following for loop will not entered
Else
intSelectedDraftCount = objDraftPaths.Count
End If
For i = 1 To intSelectedDraftCount
booSuccess = False
'open the draft file
Set objDraftDocument = OpenSolidEdgeDraft(objDraftPaths.Item(i))
If objDraftDocument Is Nothing Then
'could not open file
MsgBox "Could not open the following draft file:" & vbNewLine & _
objDraftPaths.Item(i), vbExclamation, "Solid Edge Error"
Else
'Print the draft file
For Each objSheet In objDraftDocument.Sheets
strSheetSize = DetermineSheetSize(objSheet)
If strSheetSize <> "" Then
'Determine orientation
If InStr(1, strSheetSize, "90") <> 0 Then
'Print as landscape
intOrientation = vbPRORLandscape
Else
'Print as portrait
intOrientation = vbPRORPortrait
End If
'Specify Sheet Size
Select Case Left(strSheetSize, 1)
Case "A"
intPaperSize = VBRUN.PrinterObjectConstants.vbPRPSLetter
Case "B"
intPaperSize = VBRUN.PrinterObjectConstants.vbPRPS11x17
Case "C"
intPaperSize = VBRUN.PrinterObjectConstants.vbPRPSCSheet
Case "D"
intPaperSize = VBRUN.PrinterObjectConstants.vbPRPSDSheet
Case "E"
intPaperSize = VBRUN.PrinterObjectConstants.vbPRPSESheet
Case Else
intPaperSize = VBRUN.PrinterObjectConstants.vbPRPSLetter
End Select
'Enable error handling
On Error Resume Next
'Activate the current sheet
objSheet.Activate
If Err Then
'Could not activate sheet
MsgBox "An error occurred while attempting to print: " & vbNewLine & objDraftPaths.Item(i) & vbNewLine & "The error was:" & vbNewLine & "Error Number: " & Err.Number & vbNewLine & "Error Description: " & Err.Description, vbExclamation, "Solid Edge Error"
Err.Clear
Else
'Print to the printer specified by the combo box
objDraftDocument.PrintOut cmbPrinter.Text, 1, intOrientation, intPaperSize, , , , igPrintSelected
If Err Then
'Could not print document
MsgBox "An error occurred while attempting to print: " & vbNewLine & objDraftPaths.Item(i) & vbNewLine & "The error was:" & vbNewLine & "Error Number: " & Err.Number & vbNewLine & "Error Description: " & Err.Description, vbExclamation, "Solid Edge Error"
Err.Clear
Else
booSuccess = True
End If
End If
'Disable error handling
On Error GoTo 0
End If
Next
'Close the file
objDraftDocument.Close False
intDraftsPrinted = intDraftsPrinted + 1
End If
Next i
'Dereference objects
Set objSheet = Nothing
Set objDraftDocument = Nothing
'Set objDraftPaths = Nothing
PrintSelectedDrafts = intDraftsPrinted
Now the problem comes when i hits the line that says: intOrientation = vbPRORLandscape
in excel VBA, it does not recognize "vbPRORLandscape" as well as the next line "vbPRORPortrait". Is there a way to fix that?
Also, i have a feeling that VBRUN.PrinterObjectConstants.vbPRPSLetter and the rest of those lines might not work out as well. It works in VB6 though.
Thank you
It appears the Printers Collection is available in the MS Access VBA environment but I do not believe it is intrinsic to the Excel VBA environment.
I use the WshNetwork object of Windows Script Host to list the available printers. I use the subroutine below to populate a ComboBox with the list of printers that are connected to the system. In order for this code to work you will need to add the "Windows Script Host Object Model" reference to your VBA project. (Menu: Tools > References [Select from list])
I added the (j) loop to alphabetize the list.
Sub populatePrintersList()
Dim nwo As New WshNetwork
Dim i As Integer
Dim j As Integer
Dim bAdd As Boolean
bAdd = True
cmbPrinter.Clear
For i = 0 To (nwo.EnumPrinterConnections.Count / 2) - 1
For j = 0 To cmbPrinter.ListCount - 1
If nwo.EnumPrinterConnections(i * 2 + 1) < cmbPrinter.List(j) Then
cmbPrinter.AddItem nwo.EnumPrinterConnections(i * 2 + 1), j
bAdd = False
Exit For
End If
Next j
If bAdd Then cmbPrinter.AddItem nwo.EnumPrinterConnections(i * 2 + 1): bAdd = True
Next i
cmbPrinter.ListIndex = 0
End Sub
Part 2:
MSDN contains reference material for the Worksheet.PrintOut method: Worksheet.PrintOut
In depth documentation for the methods and properties of the Worksheet.PageSetup object can also be found on MSDN: Worksheet.PageSetup
I suggest using these resources to find a plethora of answers.