Code for Command Button - error message when other button not yet clicked

Nadine1988

Board Regular
Joined
Jun 12, 2023
Messages
62
Office Version
  1. 365
Platform
  1. Windows
Hello,

i do have a file with two command buttons.
Command Button 1 does check some fields and then save the file.
Command button 2 does send the saved file attached to an email.

I would now need a code that doesn't allow command button 2 to be pressed if the file wasn't saved (so if command button 1 wasn't pressed yet)
So the user has to save the file BEFORE submitting the form.

any ideas on how to set this up correctly? Thanks!
Nadine
 
I think the option to save it as a PDF would actually be better, yes! Good idea!
 
Upvote 0

Excel Facts

Create a Pivot Table on a Map
If your data has zip codes, postal codes, or city names, select the data and use Insert, 3D Map. (Found to right of chart icons).
I think the option to save it as a PDF would actually be better, yes! Good idea!
I have changed it somewhat based upon your code.

Only one button which calls the subProcessForm procedure.
PDF is only created if the checks are successful.
PDF is overwritten if the button is pressed again.
PDF is created from the range specified so that needs to be correct.
Email only sent if the PDF file has been created.
Various comments in the code to consider.

Three functions. All return TRUE if OK to proceed to the next stage.

fncCheckFormData : Checks data entered.
fncSaveRangeAsPDF : Create a PDF file from the data entered.
fncSendEmail : Sends the email with PDF attachment.

VBA Code:
Public Sub subProcessForm()
Dim strPDFFileName As String

    ActiveWorkbook.Save
    
    strPDFFileName = "C:\Testpfad\" & Range("A15").Value & ".pdf"
   
    If fncCheckFormData() Then
    
        ' This range needs to be changed as appropriate.
        If fncSaveRangeAsPDF(Range("A1:K30"), strPDFFileName) Then
            
            If fncSendEmail(strPDFFileName) Then
                
                ' Change this message.
                MsgBox "Email sent.", vbOKOnly, "Confirmation"
            
            Else
            
                ' Change this message.
                MsgBox "Email not sent.", vbOKOnly, "Warning!"
                
            End If
      
        Else
        
                ' Change this message.
            MsgBox "PDF file not created.", vbOKOnly, "Warning!"
        
        End If
        
    Else
    
        ' Change this message or not have one here at all.
        MsgBox "Checks not passed.", vbOKOnly, "Warning!"
    
    End If
    
End Sub

Public Function fncCheckFormData() As Boolean

    ' Function returns FALSE unless all checks are passed.
    
On Error GoTo Err_Handler

    If IsEmpty(Range("A7")) Or Not IsDate(Range("A7")) Then
        MsgBox "Enter date.", vbOKOnly, "Warning!"
        Range("A7").Select
        Exit Function
    End If
    
    If IsEmpty(Range("D7")) Then
        MsgBox "Enter Vizrt sales peson.", vbOKOnly, "Warning!"
        Range("D7").Select
        Exit Function
    End If
    
    If IsEmpty(Range("C9")) Or Not IsDate(Range("C9")) Then
        MsgBox "Enter the start date of your rental.", vbOKOnly, "Warning!"
        Range("C9").Select
        Exit Function
    End If
    
    If IsEmpty(Range("C11")) Or Not IsDate(Range("C11")) Then
        MsgBox "Enter the end date of your rental.", vbOKOnly, "Warning!"
        Range("C11").Select
        Exit Function
    End If
    
    If IsEmpty(Range("A15")) Then
        MsgBox "Please enter a subject line / quote number in cell A15!.", vbOKOnly, "Warning!"
        Range("A15").Select
        Exit Function
    End If
    
    fncCheckFormData = True
    
Exit_Handler:

    Exit Function

Err_Handler:

    Resume Exit_Handler

End Function

Public Function fncSaveRangeAsPDF(rngRange As Range, strFileName As String) As Boolean

On Error GoTo Err_Handler

    If Dir(strFileName) <> "" Then
        Kill (strFileName)
    End If
    
    With Sheets(rngRange.Parent.Name).PageSetup
            .PrintArea = rngRange.Address
            .Zoom = False
            .Orientation = xlPortrait
            .FitToPagesWide = 1
            .FitToPagesTall = 1
    End With

    rngRange.ExportAsFixedFormat Type:=xlTypePDF, Filename:=strFileName
    
    fncSaveRangeAsPDF = Dir(strFileName) <> ""
    
Exit_Handler:

    Exit Function

Err_Handler:

    Resume Exit_Handler

End Function

Public Function fncSendEmail(strFileName As String) As Boolean
Dim xOutlookObj As Object
Dim xOutApp As Object
Dim xOutMail As Object
Dim xMailBody As String
Dim rng As Range
Dim strmsg As String
Dim arrymsg()
Dim i As Long
Dim strDesktopPath As String

On Error GoTo Err_Handler
    
    Set xOutApp = CreateObject("Outlook.Application")
    
    Set xOutMail = xOutApp.createitem(0)
    
        ' Doc.SaveAs2 Filename:=Environ("temp") & "\" & Environ("username"), FileFormat:=wdFormatPDF, AddToRecentFiles:=False
    
    xMailBody = "Please add any special requirements hereFor FOC rentals - please attach Vanessa's approval to your email." & vbNewLine & _
        vbNewLine & _
              "" & vbNewLine & _
              ""
    On Error Resume Next
    
    With xOutMail
        .To = "logisticaustria@vizrt.com"
        .CC = ""
        .BCC = ""
        .Subject = "Demopool Request Form_"
        .Body = xMailBody
        .Attachments.Add strFileName
        .Display   'or use .Send
    End With
    On Error GoTo 0
    Set xOutMail = Nothing
    Set xOutApp = Nothing
    
    fncSendEmail = True
    
Exit_Handler:

    Exit Function

Err_Handler:

    Resume Exit_Handler

End Function
 
Upvote 0
wow... this looks like a lot of work, highly appreciated. unfortunately it's not working. it's returning an error message if the fields are not filled even though they're not empty. I will try to figure out how to combine the codes.
I'm really new to VBA so this is actually really difficult to me - so i do apologize if you don't receive enough information from me. maybe for now i will try to integrate the option which only deactivates the second button.... the file needs to be finished by next week, so I'm a little bit in a hurry. but thanks for all your help!
 
Upvote 0
wow... this looks like a lot of work, highly appreciated. unfortunately it's not working. it's returning an error message if the fields are not filled even though they're not empty. I will try to figure out how to combine the codes.
I'm really new to VBA so this is actually really difficult to me - so i do apologize if you don't receive enough information from me. maybe for now i will try to integrate the option which only deactivates the second button.... the file needs to be finished by next week, so I'm a little bit in a hurry. but thanks for all your help!
I have changed the code to check to see if the values in the cells have a length of zero.

Can you please swop this out with the code that I previously sent you and give it a go.

You could create a new workbook with the code and the form in it instead of swopping the code.

Check to see if it works with all cells filled in first.

VBA Code:
Public Sub subProcessForm()
Dim strPDFFileName As String

    ActiveWorkbook.Save
    
    strPDFFileName = "C:\Testpfad\" & Range("A15").Value & ".pdf"
   
    If fncCheckFormData() Then
    
        ' This range needs to be changed as appropriate.
        If fncSaveRangeAsPDF(Range("A1:K30"), strPDFFileName) Then
            
            If fncSendEmail(strPDFFileName) Then
                
                ' Change this message.
                MsgBox "Email sent.", vbOKOnly, "Confirmation"
            
            Else
            
                ' Change this message.
                MsgBox "Email not sent.", vbOKOnly, "Warning!"
                
            End If
      
        Else
        
                ' Change this message.
            MsgBox "PDF file not created.", vbOKOnly, "Warning!"
        
        End If
        
    Else
    
        ' Change this message or not have one here at all.
        MsgBox "Checks not passed.", vbOKOnly, "Warning!"
    
    End If
    
End Sub

Public Function fncCheckFormData() As Boolean

    ' Function returns FALSE unless all checks are passed.
    
On Error GoTo Err_Handler

    If IsEmpty(Range("A7")) Or Len(Trim(Range("A7"))) = 0 Or Not IsDate(Range("A7")) Then
        MsgBox "Enter date.", vbOKOnly, "Warning!"
        Range("A7").Select
        Exit Function
    End If
    
    If IsEmpty(Range("D7")) Or Len(Trim(Range("D7"))) = 0 Then
        MsgBox "Enter Vizrt sales peson.", vbOKOnly, "Warning!"
        Range("D7").Select
        Exit Function
    End If
    
    If IsEmpty(Range("C9")) Or Len(Trim(Range("C9"))) = 0 Or Not IsDate(Range("C9")) Then
        MsgBox "Enter the start date of your rental.", vbOKOnly, "Warning!"
        Range("C9").Select
        Exit Function
    End If
    
    If IsEmpty(Range("C11")) Or Len(Trim(Range("C11"))) = 0 Or Not IsDate(Range("C11")) Then
        MsgBox "Enter the end date of your rental.", vbOKOnly, "Warning!"
        Range("C11").Select
        Exit Function
    End If
    
    If IsEmpty(Range("A15")) Or Len(Trim(Range("A15"))) = 0 Then
        MsgBox "Please enter a subject line / quote number in cell A15!.", vbOKOnly, "Warning!"
        Range("A15").Select
        Exit Function
    End If
    
    fncCheckFormData = True
    
Exit_Handler:

    Exit Function

Err_Handler:

    Resume Exit_Handler

End Function

Public Function fncSaveRangeAsPDF(rngRange As Range, strFileName As String) As Boolean

On Error GoTo Err_Handler

    If Dir(strFileName) <> "" Then
        Kill (strFileName)
    End If
    
    With Sheets(rngRange.Parent.Name).PageSetup
            .PrintArea = rngRange.Address
            .Zoom = False
            .Orientation = xlPortrait
            .FitToPagesWide = 1
            .FitToPagesTall = 1
    End With

    rngRange.ExportAsFixedFormat Type:=xlTypePDF, Filename:=strFileName
    
    fncSaveRangeAsPDF = Dir(strFileName) <> ""
    
Exit_Handler:

    Exit Function

Err_Handler:

    Resume Exit_Handler

End Function

Public Function fncSendEmail(strFileName As String) As Boolean
Dim xOutlookObj As Object
Dim xOutApp As Object
Dim xOutMail As Object
Dim xMailBody As String
Dim rng As Range
Dim strmsg As String
Dim arrymsg()
Dim i As Long
Dim strDesktopPath As String

On Error GoTo Err_Handler
    
    Set xOutApp = CreateObject("Outlook.Application")
    
    Set xOutMail = xOutApp.createitem(0)
    
        ' Doc.SaveAs2 Filename:=Environ("temp") & "\" & Environ("username"), FileFormat:=wdFormatPDF, AddToRecentFiles:=False
    
    xMailBody = "Please add any special requirements hereFor FOC rentals - please attach Vanessa's approval to your email." & vbNewLine & _
        vbNewLine & _
              "" & vbNewLine & _
              ""
    On Error Resume Next
    
    With xOutMail
        .To = "logisticaustria@vizrt.com"
        .CC = ""
        .BCC = ""
        .Subject = "Demopool Request Form_"
        .Body = xMailBody
        .Attachments.Add strFileName
        .Display   'or use .Send
    End With
    On Error GoTo 0
    Set xOutMail = Nothing
    Set xOutApp = Nothing
    
    fncSendEmail = True
    
Exit_Handler:

    Exit Function

Err_Handler:

    Resume Exit_Handler

End Function
 
Upvote 0
CommandButton1 saves the file; CommandButton2 emails the file. Could you not just call CommandButton1_Click event at the beginning of the CommandButton2_Click event so it saves every time before emailing?
 
Upvote 0
yes - i tried that first, but i couldn't figure out how to set the code up
CommandButton1 saves the file; CommandButton2 emails the file. Could you not just call CommandButton1_Click event at the beginning of the CommandButton2_Click event so it saves every time before emailing?
 
Upvote 0
yes - i tried that first, but i couldn't figure out how to set the code up
Here is a simple illustration on how to set it up. Replace MsgBox with code for each Button.
VBA Code:
Private Sub CommandButton1_Click()

MsgBox "Button 1 pressed."

End Sub

Private Sub CommandButton2_Click()

CommandButton1_Click

MsgBox "Button 2 pressed."

End Sub
 
Upvote 0
Here is a simple illustration on how to set it up. Replace MsgBox with code for each Button.
VBA Code:
Private Sub CommandButton1_Click()

MsgBox "Button 1 pressed."

End Sub

Private Sub CommandButton2_Click()

CommandButton1_Click

MsgBox "Button 2 pressed."

End Sub
How does this work? This is just two codes - one after an other (this is actually how it's set up now). This will still allow to press button 2 before button 1 which leads to sending the email without saving it. Or do i get something wrong here?
 
Upvote 0

Forum statistics

Threads
1,223,885
Messages
6,175,187
Members
452,616
Latest member
intern444

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top