i've been struggling around trying to get my VBA to work & i'm at a loss since i'm extremely fresh using VBA or coding in-general.
What i've got is basically a Navigation Main Form that uses tabs to open up different forms for ease of access. On one of these subforms there is a button that is supposed to work as a "SaveAsPDF" option. it's basically supposed to work by opening up a folder you want to save it in, & exporting the Report version as a pdf to the location. The weird thing is that it works perfectly when you have the actual form open & not the form open in the navigation menu, so i'm at a loss now.
If anyone is able to help, it's much appreciated & you'll be saving alot of hair from the floor. What i've got is below
Private Sub SaveAsPDF_Click()
Dim fd As FileDialog
On Error goto ErrorHandler
Set fd = Application.FileDialog(msoFileDialogSaveAs)
With fd
.InitialFileName = MAFNO & ".pdf"
End With
If fd.Show Then
DoCmd.OutputTo acOutputReport, "RptMAFPrint", acFormatPDF, _
fd.SelectedItems(1), True
End If
Exit sub
ErrorHandler:
Msgbox "An Error occurred, please try again", vbinformation, "Could not save document"
Exit sub
End Sub
As far as it running on it's own when you open the actual form up, it works perfectly & hasn't had a single error, but when opening it up from the Navigation Menu Tab it immediately has an error & tries to save the entire workbook.
Error below
https://imgur.com/a/rSynDic
Longpast on this post, but Kostas had the answer & I was easily able to edit the vba to make it work. Thank you thank you kostas, if I could actually put yours as the answer, I would.
VBA is below if anyone would ever need it. I'll probably go back at some point & see if I could re-write it better, but it gets the job done for the most part.
This does work perfectly for a MS Access Navigation form though & it does not close the current active tab at the end of the VBA.
Private Sub ButtonSaveAsPDF_Click()
Dim fd As FileDialog
On Error GoTo ErrorHandler
DoCmd.Save
DoCmd.RefreshRecord
'==== Initial Check ====
If IsNull(Me.TxtMAFNumberTop) Then
GoTo Leave
ElseIf Not IsNull(Me.TxtMAFNumberTop) Then
GoTo Start
End If
'==== SaveAs PDF Start ====
Start:
Set fd = Application.FileDialog(msoFileDialogSaveAs)
With fd
.InitialFileName = TxtMAFNumberTop & ".pdf"
End With
If fd.Show Then
DoCmd.OpenForm "FrmMAF", acNormal, , "[ID] = " & ID, , acHidden
DoCmd.OutputTo acOutputReport, "RptMAFPrint", acFormatPDF, _
fd.SelectedItems(1), True
DoCmd.Close , "FrmMAF"
End If
Exit Sub
Leave:
Exit Sub
ErrorHandler:
MsgBox "An error occurred trying to print your MAF. Please try the following
below & try again" & vbCrLf & _
vbCrLf & _
"1) Verify current MAF information & fields are correct" & vbCrLf & _
"2) Cycle Records & try again " & vbCrLf & _
vbCrLf & _
"If this problem occurs again please contact your local Administrator", _
vbCritical + vbRetryCancel, _
"[Critical] ERROR : SaveAsPDF "
If vbRetry Then
GoTo Start
ElseIf vbCancel Then
Exit Sub
End If
End Sub
Related
Using Microsoft Access: there is a form. On the form is a textbox containing a name. There is a button on the form which, when clicked, runs vba code that looks at the name on the form then opens the like named folder. The database and folder reside in the same directory. Two users have reported that, instead of the folder opening, Internet Explorer opens for them (to their default webpage).
Code for the button:
Private Sub cmdNewOpenFolder_Click()
'Uses the OpenFolderMod module to open the folder for the active record in file explorer, and create
'one if it doesn't yet exist
On Error GoTo Err_Handler
If Me.chkComplete = True Then
MsgBox "This folder has been moved to the archive"
Exit Sub
Else:
Call OpenFolder(Me.FullName)
End If
Exit_Handler:
Exit Sub
Err_Handler:
If err.Number = 94 Then
MsgBox "Please add the name of the fugitive in the 'Name' text box in order" & vbCrLf & _
"for a folder to be created."
Else
MsgBox "Error " & err.Number & ": " & err.Description
End If
Resume Exit_Handler
End Sub
The Open Folder code:
Public Sub OpenFolder(fldName As String)
Dim strStartFilePath As String
Dim strEndFilePath As String
Dim Continue As String
On Error GoTo err
strStartFilePath = strBEPath & "\" & fldName
strEndFilePath = Dir(strStartFilePath & fldName & "*", vbDirectory)
Application.FollowHyperlink strStartFilePath & strEndFilePath
err:
If err.Number = 490 Then
Continue = MsgBox("There is no folder yet, do you want to create one?", _
vbYesNo, "Create Folder")
If Continue = vbYes Then
Call MakeFolder(strBEPath & "\" & fldName)
Application.FollowHyperlink strStartFilePath & strEndFilePath
Else: Exit Sub
End If
End If
End Sub
strBEPath is a constant that is the backend database location on a shared server. It looks like "\\{name of server}\{otherfoldername}\{otherfoldername with a space in the name}\etc." (there are five subfolders in all.)
Interestingly, there is a similar button which opens the "Project Folder" the folder with the database and subfolder and it works just fine:
Public Sub OpenProjFolder()
Application.FollowHyperlink strBEPath
'Debug.Print strBEPath
End Sub
I looked over the machines where this is happening and nothing looks out of the ordinary. Both users have all the right reference libraries and so on.
Any ideas as to why Internet Explorer is opening?
I have a MainMenu where the user can enter a SchoolID in a search bar (txtSearchBar) and when they click on the SearchBySchoolID button, it opens the form, SchoolForm, based on the SchoolID. Sometimes the user clicks the SearchBySchoolID button without entering anything in the txtSearchBar so when the code below is executed, SchoolForm still opens but it is all blank.
What can I add to my code below so that a message box saying "No SchoolID found" pops up instead of bringing the user to a blank SchoolForm when they type nothing into my search bar?
Private Sub SearchBySchoolID_Click()
Dim txtSearchBar As String
On Error GoTo ErrorIDSearch
DoCmd.OpenForm "SchoolForm", , , "SchoolID = " & ("""" &
Me.txtSearchBar.Value & """"), acFormReadOnly
ExitErrorIDSearch:
Exit Sub
ErrorSIDSearch:
If Err.Number = 3075 Then
MsgBox "Please enter a valid SchoolID."
Else
MsgBox "The following error has occured:" & vbCrLf & vbCrLf & _
"Error Number: " & Err.Number & vbCrLf & vbCrLf & _
"Error Description: " & Err.Description & vbCrLf & vbCrLf & , _
vbCritical, "An Error has Occured!"
Resume ExitErrorIDSearch
End If
End Sub
You have two choices
Either put your event handling in the OnOpen event of the form named SchoolForm (and maybe use OpenArgs or an invisible textbox to set some kind of Status on that form so it knows where it was opened from, and why)
or simpler:
Check for existence of the SchoolID in the table before attempting to open SchoolForm
Could use a DLookup or a DCount
e.g.
If DCount("SchoolID", "YourTableOrQueryForSchools", "SchoolID=" & """" & Me.txtSearchBar.Value & """") = 0 Then
MsgBox "Please enter a valid SchoolID.", 64, "Try Again"
Me.txtSearchBar = ""
Me.txtSearchBar.Setfocus
Else
DoCmd.OpenForm "SchoolForm", , , "SchoolID = " & """" & Me.txtSearchBar.Value & """", acFormReadOnly
End If
I'm familiar with VBA but I am not a programmer so any help I can get in this matter is greatly appreciated. I have a report object that is mailed as a .pdf file. This portion of the code works fine but I would like to be able to save a copy of this file to a specific location with a unique name that includes the date and time the file was created. The first set of code is the SendObject that works the second set of code does not work, it is a separate procedure I have been testing to save the object. Once I can get it working I was going to integrate it into first. I would appreciate any help.
Private Sub Command21_Click()
DoCmd.SetWarnings (False)
Dim mailto As String
Dim ccto As String
Dim bccto As String
mailto = "Safety-RiskGroup#bargeacbl.com"
ccto = ""
bccto = ""
emailmsg = "The attached document is the updated Case Log." & vbNewLine
& "Please review the report, contact me and you find any discrepancies. "&vbNewLine & vbNewLine & "Thank You, " & vbNewLine & vbNewLine & vbNewLine & "Cary S. WInchester" & vbNewLine & "American Commercial Barge Line" & vbNewLine & "Safety Department"
mailsub = "Updated Case Log Report"
On Error Resume Next
DoCmd.SendObject acSendReport, "rpt_CaseLog-CurrentYear", acFormatPDF, mailto, ccto, bccto, mailsub, emailmsg, True
DoCmd.SetWarnings (True)
End Sub
This is the second set of code to attempt to save the object to a specific path with a unique name.
Private Sub Command23_Click()
On Error GoTo Command23_Click_Err
Dim filePath As String
filePath = "C:\Work\ACBL\Access Dbase\DayCount" & "CaseLog" _
& Format(Date, " yyyy/mm/dd") _
& Format(Time, " hh:MM:ss") & ".pdf"
DoCmd.OutputTo acOutputReport, "rpt_CaseLog-CurrentYear", _
"PDFFormat(*.pdf)", filePath, _
False, "", , acExportQualityPrint
Command23_Click_Exit:
Exit Sub
Command23_Click_Err:
MsgBox Error$
Resume Command23_Click_Exit
End Sub
Thanks Bit Accesser but that was not the problem, the code was laid out as it should be; however, the Date and Time formats were using characters that could be used for a file name, specifically, the colons and the backslashes were causing it to fail. Below is the corrected code. There are a few other spots I tweaked but this works great.
Private Sub Command25_Click()
On Error GoTo Command25_Click_Err
Dim filePath As String
filePath = "C:\Work\ACBL\Access Dbase\DayCount\Reports\"
DoCmd.OutputTo acOutputReport, "rpt_CaseLog-CurrentYear", acFormatPDF, _
filePath & " Case Log Update" & Format(Now(), " dd-mm-yyyy hhmmss") & ".pdf"
Command25_Click_Exit:
Exit Sub
Command25_Click_Err:
MsgBox Error$
Resume Command25_Click_Exit
End Sub
I was getting a Permission denied error when trying to export a query. The reason why is because sometimes a user leaves the file open. So I decided to try some error handling and make it so that if the Permission Denied error occurs, then it should display a MsgBox explaining what to do. If there is no permission denied error, then it should just continue and not display the MsgBox. However, it is always displaying the MsgBox.
VBA:
Private Sub Command360_Click()
Dim myQueryName As String
Dim myExportFileName As String
myQueryName = "qry_A"
myExportFileName = "J:\blah\Spreadsheet_" & Me![Combo353].Value & ".xlsx"
If Len(myExportFileName) > 0 Then
On Error GoTo Err_Msg
Kill myExportFileName
End If
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, myQueryName, myExportFileName
Application.FollowHyperlink myExportFileName
Err_Msg: MsgBox "You must close the spreadsheet in order to export.", vbOKOnly
End Sub
I figured it out, but I'm open to hearing any critiquing in order to improve this solution.
Err_Msg: If (Err.Number = 70) Then MsgBox "Error: (" & Err.Number & ")" & Err.Description & ". You must close the spreadsheet in order to export.", vbOKOnly Else Resume Next
All I needed to do was add an If statement to the Err_Msg line where the condition was based on the exact error I wanted to handle.
I am trying to make this msoFileDialogOpen allow the user to select multiple files. Is there a better way to do this:
Public Sub Function3_FileExplorer()
' Start File Explorer to select file containing data (simple GUI, much
' easier than coding vFileName)
vuserChoiceDataFileNumber = InputBox("Enter the number of files you want to select.")
With Application.FileDialog(msoFileDialogOpen)
Select Case IsNumeric(vuserChoiceDataFileNumber)
Case True
If VarType(vuserChoiceDataFileNumber) = 2 Or 3 Then
iuserChoiceDataFileNumber = CInt(vuserChoiceDataFileNumber)
End If
Case False
MsgBox (vuserChoiceDataFileNumber & " is not an integer.")
.AllowMultiSelect = False
End Select
.Show
End With
Exit Sub
On Error GoTo ErrorHandler
.AllowMultiSelect = True
ErrorHandler:
MsgBox "Error detected" & vbNewLine & "Error" & Err.Number & ": " & _
Err.Description, vbCritical, "Error Handler: Error " & Err.Number
MsgBox "If you want to force the program to run, go to the line below and " & _
"insert a ' mark to comment the line out." & vbNewLine & _
"On Error GoTo ErrorHandler", vbCritical, "Error Handler: Error " & Err.Number
End Sub
Yes, you can make this much simpler by not asking the user how many files they want to open--just let them select as many as they want.
Public Sub Function3_FileExplorer()
' Start File Explorer to select file containing data (simple GUI, much easier than coding vFileName)
With Application.FileDialog(msoFileDialogOpen)
.AllowMultiSelect = True
.FilterIndex = 2
If .Show Then
Dim file As Variant
For Each file In .SelectedItems
' do something with the file, for example, open it:
Application.Workbooks.Open (file)
Next file
End If
End With
End Sub