My global variable is not transferring to Dialog Form when called from Report - vba

Update 3/15/19 to add new declaration code in General Declarations section:
Option Compare Database
' Access global variables definition
Global bInReportOpenEvent As Boolean
Option Explicit
I am getting error:
"The expression On Open you entered as the event property setting produced the following error: Constants, fixed-length strings, arrays, user-defined types and Declare statements not allowed as Pubblic members of object modules."
Update 3/15/19 to add declaration code. Still bInReportOpenEvent value lost on call to Dialog form.
Option Compare Database
Dim bInReportOpenEvent As Boolean
Function IsLoaded(strNme As String) As Boolean
IsLoaded = CurrentProject.AllForms(strNme).IsLoaded
End Function
I am creating an Access Report that calls a Dialog Form to prompt for specific record to display in report. The report uses a query as the record source. I am setting a global field in the Report Open module so that the Dialog Form cannot be executed on it's own. If the Dialog Form is called and the global field set by the Report is not set, then I want to exit out with a message. My Report Open module looks like this:
Public Sub Report_Open(Cancel As Integer)
Dim outCome1 As String
' Set public variable to true to indicate that the report
' is in the Open event
bInReportOpenEvent = True
MsgBox (bInReportOpenEvent)
' Open Appt Query Dialog
DoCmd.OpenForm "craid CMM Client Report Dialog", , , , , acDialog
' Cancel Report if User Clicked the Cancel Button
If IsLoaded("craid CMM Client Report Dialog") = False Then Cancel = True
MsgBox ("Is Dialog Form Loaded?")
MsgBox (IsLoaded("craid CMM Client Report Dialog"))
'outCome1 = (Reports("CMM Client Status Report").Controls("googleoutcome").Value)
'MsgBox (outCome1)
' Set public variable to false to indicate that the
' Open event is completed
bInReportOpenEvent = False
End Sub
My Form Open for my Dialog Form looks like this:
Private Sub Form_Open(Cancel As Integer)
If Not bInReportOpenEvent Then
MsgBox ("In Not bInReportOpenEvent Logic")
MsgBox (bInReportOpenEvent)
' If we're not called from the report
MsgBox "For Use From CMM Client Status Report Only", _
vbOKOnly
Cancel = True
End If
End Sub
Any ideas on why? Any help appreciated.

My question was answered. Solution is to put declaration of global variable in VBA code module.

Related

The expression On Click you entered as the event property setting produced the following error: Sorry, an unexpected error occurred

The error message continues with:
"*The expression may not result in the name of a macro, the name of a user-defined function, or [Event Procedure]."
"*There may have been an error evaluating the function, event, or macro."
This database was written by an employee who retired years ago and unfortunately I am now stuck with it. It was working last week and of course when it stopped working today. I am not sure where to even start looking or how to debug in VBA. When a user enter data in the fields and click on Print button, I believe the data gets populated in the data source and then it will print a report/receipt. The print button call the cmdPrintReceipt_Click() procedure. Can someone give me some pointers or how to debug in VBA? Much appreciated and happy holidays!
Pasting the code here:
Option Compare Database
Option Explicit
Dim OkPass As Integer, message As String, Response As Integer
Dim nAmount As Integer
Dim Conn As New ADODB.Connection
Dim RS2 As ADODB.Recordset
Dim Total As Long 'Hold receiptNumber for ReceiptLine
Private Sub cmdNoAdd_Click() 'close window without adding a new reacord
'Use the msgbox function to see if user wants to exit this form w/o adding new receipt
Dim Msg, Style, Title, respons
Msg = "Close this window without saving this receipt?"
Style = vbYesNo + vbQuestion + vbDefaultButton2 'Define buttons of message box
Title = "Exit without adding a receipt?" 'Title of the message box
respons = MsgBox(Msg, Style, Title)
If respons = vbYes Then 'User chose Yes DO NOT ADD the Record
DoCmd.Close
Else 'User chose No close the message box and leave frmReceipt Open
End If
End Sub
Private Sub Form_Load()
'Clear Total
Total = 0
End Sub
'****************************************************************************************
' Main procedure for the form, check first all required fields filled in
' then Add new records and print receipts.
'****************************************************************************************
Private Sub cmdPrintReceipt_Click()
'Check if all filled in, then
'Just call the AddReceipt Function
DoNotClose 'function
If OkPass <> 9 Then
Response = MsgBox(message, vbOKOnly, "Information Missing")
'return focus to the frmReceipt
txtFirstName.SetFocus
Exit Sub
Else
' Add the new Receipt record
Me.lblNoAdd.Visible = False
Me.cmdNoAdd.Visible = False 'you can't escape after printing receipt.
AddAReceipt ' call AddReceipt function
MsgBox "Please confirm the information you entered is correct", vbOKOnly
ShowPrint3Button
'cmdPrint3Button print 3 copies of receipt
End If
Exit Sub
End Sub
If it worked for years without errors before, I doubt debugging will help.
The db might be corrupted. Try the following steps:
see if VBA compiles
compact and repair the db
if not successfull, create a new blank db, and imort all objects from the old one.
Also, when you get the error message, you can press Ctrl+Break and arrive on the exact line that causes the error. Good luck ;-)

Turn off "The record source specified on this form does not exist" warning

how can I turn off/disable "The record source specified on this form does not exist" warning message? I created GUI that uses subforms, but the tables that are resource for these are generated in the process. So it means that GUI does not have any resource after opening the database and shows the error "The record source specified on this form does not exist". How can I turn it off/disable it? I tried to add DoCmd.SetWarnings False
but this has no effect on the error message.
You could leave the RecordSource empty or assign it some (empty) dummy record.
When you set the RecordSource to its actual value, the subform will automatically requery.
You need to look at Application.DisplayAlerts
Sub Example()
'do stuff
Application.DisplayAlerts = False
'Code that fires the warning message
Application.DisplayAlerts = True
'do stuff
End Sub
Instead of disabling alerts you can just assign some unrelated table to this form/subform.
Another solution - disable only this exact error if you have an error number (I guess it is 7874) like that:
Private Sub Form_Error(DataErr As Integer, Response As Integer)
If DataErr = 7874 Then
Response = acDataErrContinue
Else
Response = acDataErrDisplay
End If
End Sub

Is there code that i can use to eliminate a runtime error?

In my database (access 2010) there is a "Main menu" form that opens up an event form sourced by the event table after a search from an unbound textbox. Up until the most recent Windows update on 4/10/19 the code was working perfectly to create a new record in the event form. Now I get run-time error 2427 (You entered an expression that has no value). What change in code should be implemented to remove the error?
The debugger breaks in Private Sub Form Load() of the event form in the first If statement which is referencing a true/false control.
I have tried with no luck 1. changing the values to (True/False), 2. adding Me. to the beginning of the if statement, 3. removing the if statements from the form load altogether and setting focus to another control on the form and 4. adding a form current event with the code that was previously in the form load event.
This code closes the "Main Menu" form and opens the events form in add mode.
Private Sub cmdAddEvent_Click()
cmdAddEvent.SetFocus
cboEvent.Value = ""
blnAddEvent = True
On Error GoTo Err_cmdAddEvent_Click
DoCmd.Close
' wipe out event variables when finding or adding another event
strSaveYearCode = "": strSaveProjectCode = "": strSaveActivityCode = "":strSaveProposalCode = ""
g_strEventYear = "": g_strEventProject = "": g_strEventActivity = "": g_strEventProposal = ""
' end of wipe-out
DoCmd.OpenForm "frmEvents", , , , acFormAdd
'DoCmd.GoToRecord , , acNewRec
Exit_cmdAddEvent_Click:
Exit Sub
Err_cmdAddEvent_Click:
MsgBox Err.Description
blnAddEvent = False
Resume Exit_cmdAddEvent_Click
End Sub
This is the code in from the events form that the debugger breaks at before the run-time error appears.
Private Sub Form_Load()
If proContentApprove = -1 Then ---This line
proDescription.Locked = True
proAudience1.Locked = True
Else
If proContentApprove = 0 Then
proDescription.Locked = False
proAudience1.Locked = False
End If
End If
When an record is already in the source table the event form opens without incident. I expect the events form to open as it normally does when trying to add a new record as well.

VBA Word Macro to Allow User to Select and Copy Text Multiple Times

I am working on a VBA script with Microsoft Word that allows the user to select text that will be be copied to the clipboard so that it can exported to an Excel file. The user will make a number of selections and finally indicate he/she is done when the contents of the clipboard will be copied to a template Excel file.
There are two forms: the first (UserForm1 in the code below) queries the user for the Word filename. The filename variable is passed to the second form. The second form (frmModeLessForInput) is a modeless form. The behavior I need is that program control goes to the second form with two buttons "Continue" and "Done".
The user is allowed to navigate the document and place the cursor anywhere in the document. Then when "Continue" is pressed the form will call a subroutine (Highlight_Sentence) to copy the selected text to a "clipboard" variable. When "Done" is pressed control will be passed to called main module which will then copy the clipboard to the Excel file.
Below is the code. I have noted with comments where I am trouble with the code. One problem is the variables defined as Public in the ThisDocument module are not defined in the userforms and their subroutines.
The second problem is in the main module that the frmModelessForInput is supposed to be displayed and control is not supposed to be transferred to next statement {MsgBox "Sentences will now be copied to Excel file"....this is where I will put the code to copy the clipboard to the Excel file.} but the message appears before the frmModelessForInput form is run...thus the clipboard will be empty.
The third problem is that in frmModelessForInput form the statement str_clipboard = str_clipboard + str_clipboard_line is not working. Each time the "Continue" button is pushed str_clipboard loses it previous contents.
Any assistance in resolving these problems is appreciated. As VBA programming is a sideline for me I am still learning.
Note this an updated question Pause VBA Word macro, allow user to make a selection, and restart where it left off adding some more detail on the requirement and the sample code.
MAIN MODULE:
Option Explicit
Public str_clipboard As String
Public txt_active_document As String
Public i_how_many_sentences As Integer
Private Sub Test_master_macro()
UserForm1.Show
i_how_many_sentences = 0
Call DisplayModeless
MsgBox "Sentences will now be copied to Excel file" 'Problem: this msg displays before the frmModelessForInput is displayed
End Sub
Sub DisplayModeless()
Dim frm As frmModelessForInput
Set frm = New frmModelessForInput
With frmModelessForInput
.str_word_doc_filename = txt_active_document
.str_no_copied = "0"
.Show False
End With
Set frm = Nothing
End Sub
USERFORM1: form has field for user entering the document filename to user (str_filename) and a command button to close form (cmd_start_selecting_text)
Private Sub cmd_start_selecting_text_Click()
'User enters filename on form for use in frmModelessForInput subroutine
txt_active_document = UserForm1.str_filename 'Problem: VBA reports txt_active_document as undefined even though it is a Public variable
Unload Me
End Sub
FRMMODELESSFORINPUT: Form displays filename of Word file entered in UserForm1 and how many sentences have been copied to the clipboard
Option Explicit
Private Sub cmdContinue_Click()
Dim str_clipboard, str_clipboard_line As String
Call Highlight_Sentence(str_clipboard_line)
i_how_many_sentences = i_how_many_sentences + 1 'Problem: VBA reports i_how_many_sentences as undefined even though it is a Public variable
frmModelessForInput.str_no_copied = i_how_many_sentences 'Same Problem
str_clipboard = str_clipboard + str_clipboard_line 'Problem: each time I select a new text/sentence str_clipboard does not contain the contents of the previous selection
End Sub
Private Sub cmdDone_Click()
Me.Hide
End Sub
Private Sub UserForm_Activate()
'Position the form near the top-left of the window
'So that the user can work with the document
Me.Top = Application.ActiveWindow.Top + 15
Me.Left = Application.ActiveWindow.Left + 15
End Sub
Private Sub Highlight_Sentence(clipboard As String)
'This sub extends the selection to the entire sentence and copies the selection, the page number on which the selection is contained and the filename to the clipboard variable
Dim txt_sentence, txt_page_no As String
With Selection
' Collapse current selection.
.Collapse
' Expand selection to current sentence.
.Expand Unit:=wdSentence
End With
txt_sentence = Selection.Text
txt_page_no = Selection.Information(wdActiveEndPageNumber)
clipboard = txt_active_document & vbTab & txt_page_no & vbTab & txt_sentence & vbCrLf 'Problem: VBA reports txt_active_document as undefined even though it is a Public variable
End Sub
From what you stated you are running this from the ThisDocument Class Module and unless you fully qualify your references to those Public variables with the Class Name that is why you cannot access them from the UserForms Class Modules.
If you are going to leave your "Main Module" code in the ThisDocument Class Module then whenever you reference those Public variable you need to add ThisDocument.str_clipboard to the command.
I recommend however, to place your Main Module in a general Module such as NewModule and if you need to run it at a Document_Open event that you put a call to the Main Module and its Public variables in the Private Sub Document_Open event of the ThisDocument Class Module.
Your Msgbox is appearing at the wrong time because you are displaying a modeless user form, which means the VBA script thread continues to run after the UserForm is displayed. Move the Msgbox to the UserForm_Activate routine of the second UserForm you are displaying or move it to the Click_Done routine of the first UserForm before you Hide or Unload it.
Finally, you are not really using the Clipboard and using that term makes your code confusing in my opinion. I think you should rename it. Your code also appears to just be building one continuous string of text. Is that really what you want to do? Or, do you really mean to capture each selected text string and ultimately place each into separate cells within an Excel Worksheet? If that is the case, use an Array for the separate text strings.

How to disable a ribbon button in Excel if a particular worksheet exists with VBA

I'm building an Excel add-in which allows users to interact with PowerPoint and export data. The users have an option to insert a template into an existing workbook via a button in the ribbon. When they click this, the button becomes disabled as you can't have two templates in one workbook.
The user may then save their workbook and come back to it at a later point. My issue is that I need to detect that they have the template inserted into an existing workbook and I do this by trying to detect if a named range exists (called LoadedToken).
The issue I have is that both the onLoad function of the Ribbon and the VBA class Auto_Open launch before a large workbook is fully loaded. Therefore I'm not actually detecting if the template exists and can't actually disable the button.
Is there such a thing as events in Excel which can be called at a worksheet level (like worksheet_open) but detected in a class?
My code is:
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' When the Ribbon loads
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Private Sub OnRibbonLoad(ribbonUI As IRibbonUI)
Set MyRibbonUI = ribbonUI
Dim Authenticate As New AuthenticationClass
On Error Resume Next
' Enable/Disable buttons based on authentication status
If Authenticate.Authentify = False Then
Authenticated = False
Debug.Print ("Unauthorized!")
Else
Authenticated = True
Debug.Print ("Authorized!")
End If
' If the template doesn't exist then disable a grouping on the ribbon
If TemplateExists = False Then
Call RefreshRibbon(Tag:="Grouping1")
Else
Call RefreshRibbon(Tag:="Grouping2")
End If
End Sub
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Check if the Template sheet is visible and prevent other buttons from working
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Public Function TemplateExists()
Dim Helpers As New HelpersClass
If Helpers.IsNamedRange("LoadedToken") Then
TemplateExists = True
Else
TemplateExists = False
End If
End Function
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' From the Helpers Class - Check if a named range exists
'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function IsNamedRange(RName As String) As Boolean
Dim N As name
IsNamedRange = False
For Each N In ActiveWorkbook.Names
If N.name = RName Then
IsNamedRange = True
Exit For
End If
Next
End Function
Note: The authentication class is just another class to connect to my API.