VBA Listbox becomes unresponsive after first use - vba

I have a VBA (Excel 2010) system which involves selecting an item from a listbox and then displaying it in another form. Here is a very simplified version of what happens.
' Part of frmForm1 code module
sub lstListbox_Click
dim MyEvent as string
dim i as integer
i=me.lstListbox.listindex
MyEvent=me.lstlistbox.list(i)
' Now show the item in the second form
Load frmForm2
me.hide
ThisWorkbook.LoadDataIntoForm2 (frmForm2, MyEvent)
frmForm2.show
unload frmForm2
me.show
end sub
The listbox accepts the click, and first the event (the event handler is giver above). Key parts of the event handler are:
Load the second form (to display the detail data)
Pass the second form as a UserForm parameter to a procedure (LoadDataIntoForm2)
Hide the host form (frmForm1) and show the second form (frmForm2)
When the second form processes an Exit click, the code looks like this:
' Part of frmForm2 code module
sub cmdExit_Click
me.hide
end sub
The first time round it works fine - but when I return to frmForm1 (in the tail end of the lstListBox_Click procedure), even though the rest of the form is operative, the listbox remains stubbornly unresponsive.
I've managed to abstract this down to a little demo system if that would help - the same behavior is seen there. (It's regular .xls file, but that seems not to be easily acceptable as an upload)
Has anyone seen this before? And does anyone have any ideas how I might get this to work the way I want it to?
Thanks,
Tony

The default for the .Show method is to make the form modal. Explicitly set it to modeless:
Sub lstListbox_Click
...
Me.Show vbModeless
End Sub

Related

How can i make or not make particular Tabs visible by loading a form in Access with VBA?

Question
How can i make or not make particular Tabs visible by loading a form in Access with VBA?
Explanation:
I have a Acess Database with 4 forms containing buttons. Today i started to create ribbons to get rid of those in the forms so everything is sorted and easy to overview. I want the Tabs in my Access Database to be unvisible until i open a form from my main form.
Main Form (no tabs showed) --> Switching to another form by clicking a button in my main Form (now i want to show a particular tab after opening the form)
I created my Ribbons with "Ribbon Creator 2019" for Office 2019.
Problem:
I cant solve it ... i tried so many things until i found a excel worksheet having a function by swithing sheets to display particular tabs. Its exactly what i want but i can't get it to work for my access.
By getting the name of the active form i cant get it to work and in my opinion this would be tha fastest way.
My approach:
I set "StartFromScratch" in my XML to 'true' and gave my tabs names like this: "CustomTagValue1:=xstart".
Code for my tabs (Module):
Sub GetVisible(control As IRibbonControl, ByRef visible)
' Callbackname in XML File "getVisible"
' To set the property "visible" to a Ribbon Control
' For further information see: http://www.accessribbon.de/en/index.php?Downloads:12
' Setzen der Visible Eigenschaft eines Ribbon Controls
' Weitere Informationen: http://www.accessribbon.de/index.php?Downloads:12
Select Case control.ID
Case "tab_3"
' Tab: tab_3
visible = False
Case "tab0"
' Tab: tab0
visible = False
Case "tab1"
' Tab: tab1
visible = False
Case Else
visible = True
End Select
End Sub
Code from another Module to declare my tabs:
Option Compare Database
Option Explicit
'**************************************************************************
' About this Code:
'
' This Code checks if a Formular is in active use by his 'Name'. Simple.
'**************************************************************************
Dim MyTag As String
'Callback for customUI.onLoad
Sub RibbonOnLoad(ribbon As IRibbonUI)
Set Rib = ribbon
End Sub
Sub GetVisible(control As IRibbonControl, ByRef visible)
If control.Tag Like MyTag Then
visible = True
Else
visible = False
End If
End Sub
Sub RefreshRibbon(Tag As String)
MyTag = Tag
If Rib Is Nothing Then
MsgBox "Fehler RBC1018, bitte starten Sie das Programm neu."
Else
Rib.Invalidate
End If
End Sub
Code in the Form onLoad:
Private Sub Form_Load(ByVal Sh As Object)
Select Case Screen.ActiveForm
Case "frmVerteiler": Call RefreshRibbon(Tag:="xverteiler")
Case Else: Call RefreshRibbon(Tag:="")
End Select
End Sub
Help:
I want it to work as in this excel Dokument: https://www.rondebruin.nl/win/s2/win012.htm
It is far less work and significant more easy to just create a custom ribbon for each form, and that way you don't have to write all kinds of code to hide show tabs on the ribbion. So just specify the correct ribbon for the given form, and no code is required.
I also suggest that you do NOT use call backs in the ribbon. If you adopt this approach, then the ribbon can directly call your EXISTING button code. So the code, buttons you now have can be transferred to the ribbon for that form, and you don't have to setup ribbon call backs, and all of your existing button code can remain "as is" and be called directly from the ribbon - and the ribbon will run the button code that is and remains in the form.
All you need to do is to declare any function you want called as a public function.
You then set the on action as follows:
=MyPublicFunctionName()
Note CAREFULL how we have = and () (you must have these), and they must be under the quotes.
Eg for the xml we have:
onAction="=MyDelete()"
Note how the above is DIFFERENT then a call back for a ribbon (and callbacks use sub, where this is a function). Even better is the above means you do NOT have to place the code in a standard code module, but can place the function it in the current form. So, no macro needed, no callback, and the code can go in the current form (just like it does for a command button). And bottoms to dollar, in 9 out of 10 cases, the code you need for particular form and button belongs in that particular forms code module anyway. In fact it's a very bad programming practice to start taking code that belongs in a form and placing that code in a standard public code module. The reason is for many, but all kinds of issues can crop up if you have multiple instances of that same form which is allowed in access. Furthermore when copying forms between applications, or even making a copy of the form within the same application means that you have outside code dependencies that we normally as access developers do not expect (we assume for the most part is that the code we're using for the form belongs in the forms code module and I 100% agree). I am open to the idea that this does go against the well known concept of moving UI and code apart but this is "HOW" access works. So the access way does go against trends in our industry.
Keep in mind the above function call idea is the same format we can and would have been using since near day one with menu bars in previous editions of access. So, if you are wanting to change menu bar code to ribbon, use the above idea. Also, if you have several buttons that runs code in a given form, then again the above syntax allows one to KEEP the code in the current form and simply declare the button code as a public function (you can thus real easy move buttons from a form to a ribbon if you do this).
If the function name you specified in the menu or ribbon was named as public in the form's code module, then the CURRENT FORM with the CURRENT FOCUS is where the function will be first looked for to execute. This is SIGNIFICANTLY important because it means you can use one custom menu bar for five different forms, but each of the five different forms will run a custom delete routine for example (no messing with screen.Activeform). And, you don't have to use a bunch of messy case statements as you do with a call back. In fact, all of the code stays in the form where it likely was or belongs in the first place, and that is in the forms code module.
So, if you have specific and specialized delete code that might be required for the given form that has the focus, then that's forms function code in the forms module will be run when it is called from the on action in the menu bar, or now ribbon.
This means if you set the on action to =MyDelete()
Then in each form you have, you simply declare a public functions such as
CODE
Public function MyDelete()
Code here to delete the record
End function
However it turns out for probably more then half or even close to 90% of your forms, it's entirely possible that you want a general catchall delete routine that works for all forms that don't need specialized custom deleting code. In this case you simply place the function in a standard code module (and again as public). If the current form does not have that function, then it is run from a standard code module (again, ideal behavior, and again this is how the onAction worked before ribbon).
Also, note that you also pass values directly from the ribbon.
So, ribbon xml might be:
CODE
<button id="MyDelete" label="Delete Record"
imageMso="Delete" size="large"
onAction="=MyDelete('Staff','tblStaff')"
supertip="Delete this record"
/>
In the above, I passed the table name, and a prompt text of Staff.
And the public catch all function in a standard code module will be:
CODE
Public Function MyDelete(strPrompt As String, strTable As String)
Dim strSql As String
Dim f As Form
Set f = Screen.ActiveForm
If MsgBox("Delete this " & strPrompt & " record?", _
vbQuestion + vbYesNoCancel, "Delete?") = vbYes Then
etc....
Note again how I passed two parameters to the delete routine (the text must be under single quotes). The prompt part so the msgbox command will say "Delete this staff ?". And, then I also pass the table name. What the above means is that for ten forms, if you don't specify a public function inside of the form, when the menu button is clicked on is selected, the catchall general routine in an standard code module (non forms code module) will run.
And for the few forms that have specialize deleting code, the function inside of the forms code module will run. That code might look like:
CODE
Public Function MyDelete(s1 as string, s2 as string)
' check for history
....
lngHistory = Nz(DLookup("ContactId", "NHistory", "ContactID = " & Me.ContactID), 0)
If lngHistory > 0 Then
Beep
MsgBox "You cannot delete a person with past history bookings!" & vbCrLf & vbCrLf & _
"You should simply check the 'Do NOT INCLUDE in mailings' to remove from" & vbCrLf & _
" future mailings.", vbExclamation, "Rides"
Exit Sub
End If
...code here with sql to delete record....
So a few things:
I would just create a ribbon for the given form (take your xml for the given tab, and create a whole new ribbon). Now, if you have 2 or 5 forms open, then the ribbon will automatic flip and change for you. If you try and use tabs, then a simple change of focus to another form will require you to hide+show given tabs - it becomes a real mess rather quick.

How to stop Access from prompting "Do you want to save changes to the layout of query"

How can I stop Access from prompting "Do you want to save changes to the layout of query" when I try to close a form that has a subform in datasheet view?
I have a form with a subform in Datasheet view with the .SourceObject set to a temporary pivot / crosstab query (no actual form object). If the user changes the width of a column and closes the window with the built-in Access close button, the user (and annoyed developer) is always presented with the "Do you want to save changes to the layout of query" prompt.
I am able to avoid this prompt by setting MySubform.SourceObject = "" in the click of my Close button but anyone clicking the [x] button or pressing CTRL+F4 or CTRL+W gets the prompt.
I have put breakpoints in the Form_Close and Form_Unload events but this prompt appears before they fire.
I want to clarify further that this subform object is Unbound and not based on a form object. I am building a dynamic Crosstab SQL statement, creating a QueryDef with the SQL, and then setting MySubform.SourceObject = "query.qry_tmp_Pivot" This is a neat technique for a crosstab/pivot query because the columns can vary and I don't think a form object would support that.
I am able to use the Watch window on the MySubform object and I can see that a MySubform.Form object exists. It has a Controls collection containing a control for all of the columns in my query. I have an optional routine that I can run that will loop through all of the controls and set their .ColumnWidth = -2, which will auto-size the column width based on the widest data of the visible rows in the datasheet. When this routine was running I was noticing that every time I closed the form (not using my Close button) I was getting the save prompt. I have disabled this routine for debugging but a user will still get the prompt if they manually adjust any column width.
I feel like I need to explain this extra detail so you realize this is not an Access 101 issue. You probably know that if you've read this far. Here's another thought I had: Maybe I could trap the Unload event in the subform control before the prompt happens. Because there is no true Form object to put test code in, I created a class object and passed MySubform to it. The class uses WithEvents and creates events like OnClose and OnCurrent on the class module's mForm object. Sample class code is below.
Private WithEvents mForm As Access.Form ' This is the form object of the Subform control
Public Sub InitalizeSubform(Subform As Access.Subform)
Set mForm = Subform.Form
Debug.Print Subform.Name, mForm.Name, mForm.Controls.count
' Create some events to intercept the default events.
mForm.OnClick = "[Event Procedure]"
mForm.OnClose = "[Event Procedure]"
mForm.OnUnload = "[Event Procedure]"
mForm.OnCurrent = "[Event Procedure]"
End Sub
Private Sub mForm_Click()
Debug.Print "Clicking " & mForm.Name
End Sub
Private Sub mForm_Current()
Debug.Print "On Current " & mForm.Name, "Record " & mForm.CurrentRecord & " of " & mForm.RecordsetClone.RecordCount
End Sub
Private Sub mForm_Unload(Cancel As Integer)
Debug.Print "Unloading " & mForm.Name
End Sub
Private Sub mForm_Close()
Debug.Print "Closing " & mForm.Name
End Sub
The VBE Watch window shows my new events on the mForm object but unfortunately they never fire. I know the class works because I used it with a bound subform and all of the events are intercepted by the class. I'm not sure what else to try.
Events on the subform never fire because it's a lightweight form (without a module). See this Q&A and the docs. Lightweight forms don't support event listeners, but do support calling public functions from an event, e.g. mForm.OnClick = "SomePublicFunction()"
Note that the workaround described in this answer also opens up the possibility of displaying a crosstab query in a form without saving it at all.
Alternatively, you could try capturing the event on your main form, and suppress saving there.
I gave answer credit to #ErikA for this question. He directed me to an answer to a somewhat related question here which is what I ended up implementing and it works. His instructions were very straightforward and easier to implement than I first anticipated.
The answer to my question seems to be that it may not be possible to avoid the save prompt when using a lightweight form object. If someone comes along with a solution I'd still like to hear it.
What I learned from this experience:
An unbound subform that has its .SourceObject set to a table or query will not have a code module. This considered to be a lightweight object.
Public functions can be added to event properties on lightweight forms but they don't seem to fire before the save prompt appears as the parent form is closing.
Binding a pivot query or temp table to a real form object that has 254 controls on it is the only way I found that doesn't prompt to save design changes when the parent form closes. Mapping the query/table columns to the 254 datasheet controls is super fast.
A class is a nice way to intercept events if you're not using a lightweight object. A class also lets you open multiple instances of the same object.
I ended up not implementing my solution without using a class because there were no events I needed to capture. At this point I don't need my frmDynDS to be used for other purposes and I'd like to keep the object count down (this is a large app with 1400+ objects).
I put the following code in a function that gets called when the subform is loaded or refreshed.
With subCrosstab
' Set the subform source object to the special Dynamic Datasheet form. This could be set at design time on the Subform control.
.SourceObject = "Form.frmDynDS"
' Run the code to assign the form controls to the Recordset columns.
.Form.LoadTable "qry_tmp_Pivot" ' A query object works as well as a table.
' Optional code
.Form.OnCurrent = "=SomePublicFunction()"
.Form.AllowAdditions = False
.Form.AllowEdits = False
.Form.AllowDeletions = False
.Form.DatasheetFontHeight = 9
End With
I can now resize the columns and never get a prompt to save layout changes no matter how I close the parent form.

Programming VBA in an Outlook form

I created my own Outlook form to use it as standard surface to enter certain orders instead of the normal message form. The creation, editing and sending works perfectly fine and in the next step I want to insert some code via VBA.
My problem is that I can´t access the objects of my form in the VBA editor. E.g. I want to show a message box when a certain checkbox is checked. According code would be:
Sub example()
If CheckBox1.Value = True Then
MsgBox("Checkbox 1 is checked.")
End If
End Sub
When I run the code I get the error that the object could not be found. The same goes for every other object, like textboxes or labels etc.
I guess the solution is pretty simple, like putting Item. or sth. like that in front of each object. But so far I wasn't able to find the solution.
I´m using Outlook 2010.
I know this is a year too late but you'll want to do something like this example below. It's kinda a work around but you can get whatever value was selected.
Sub ComboBox1_Click()
Set objPage = Item.GetInspector.ModifiedFormPages("Message")
Set Control = objPage.Controls("ComboBox1")
MsgBox "The value in the " & Control.Name & _
"control has changed to " & Control.Value & "."
End Sub
You should be able to get the value, just get a handle on the object you want using the Inspector
The following is an excerpt from here
When you use a custom form, Outlook only supports the Click event for
controls. This is a natural choice for buttons but not optimal for
controls like the combo box. You write the code by inserting it into a
form’s VBScript editor. You need to have the Outlook form open in the
Form Designer and click the View Code button found in the Form group
of the Developer tab.
Sub CheckBox1_Click()
msgbox "Hello World"
End Sub
The code page is fairly minimal with no syntax highlighting. I just tried this now and it does work. Dont forget to Publish your form to pick up the new changes.
I know this is almost 6 years late but, in VB and VBA, simply start with the form name. (And if that doesn't work, just keep going up a parent object and you'll get there.) So, your code becomes:
Sub example()
If MYFORMNAME.CheckBox1.Value = True Then
MsgBox("Checkbox 1 is checked.")
End If
End Sub
Of course, after typing "MYFORMNAME." you'll know if it will work because typomatic will kick in when the system recognizes "MYFORMNAME" after you hit the period.

Treeview behaving differently when tapped than when clicked

The situation: I have an Access 2010 db that is meant to be deployed on a Windows 8 tablet. The main form of the app contains a Treeview control. Selecting a node on the Treeview sets the visibility of one of several subforms that are used for viewing/editing details of the selected node item. I have a yes/no message box and some basic code on the BeforeUpdate event for each of the subforms. So when the record on the subform is dirty and the user clicks anywhere on the main form (including anywhere in the Treeview control) this code is triggered.
The problem: When the subform record is dirty and the user taps anywhere on the Treeview control, the message box pops up but cannot be interacted with because the app is busy. Doing what, I don't know, but it stays that way until Access is shut down via Task Manager. There is no code attached to the Treeview for anything but the Click event. This happens even when they touch white space in the Treeview below the existing nodes.
If the record is not dirty, everything works fine.
If the record is dirty and the user hits the "Save" button on the subform to trigger the BeforeUpdate event, everything works fine.
If the user taps a different control or in the empty space on the main form, the BeforeUpdate event is triggered and everything works fine.
If you plug a mouse into the tablet and do the same series of steps by clicking instead of tapping, everything works fine.
I've done a ton of searching and haven't been able to find anything relevant to this, so any suggestions or guidance to new places to look for suggestions would be deeply appreciated.
I've attached a sample of the BeforeUpdate code that exists on each of these subforms. It's pretty basic, but maybe there's something in it that tapping and Treeviews just don't like.
Private Sub Form_BeforeUpdate(Cancel As Integer)
'If the form data has changed a message is shown asking if
'the changes should be saved. If the answer is no then
'the changes are undone
On Error GoTo BeforeUpdate_Error
If Me.Dirty Then
'Add PropertyID, LPParentNodeID and TreeNodeID if Record is new
If Me.NewRecord Then
Me.PropertyID = Me.Parent!PropertyID
Me.LPParentNodeID = Me.Parent!txtCurrKey
Me.TreeNodeID = DateDiff("s", Date, Now())
End If
'Display prompt to save the record
If MsgBox("The record has changed - do you want to save it?", _
vbYesNo + vbQuestion, "Save Changes") = vbNo Then
Me.Undo
End If
End If
'If the record is still dirty, then record the change in the Audit table
If Me.Dirty Then
Call AuditTrail(Me, InstanceID, PropertyID)
End If
BeforeUpdate_Exit:
Exit Sub
BeforeUpdate_Error:
MsgBox Err.Description
Resume BeforeUpdate_Exit
End Sub
08/30/2013 Addition: I forgot to mention the debugging behavior in the original question. When I set a breakpoint on the BeforeUpdate Sub of the subform on any line from the actual Sub entry point down to the If statement with the message box, the code window comes up but the app again becomes busy, and I can't interact with either window. Just like before, this behavior is unique to tapping that accursed Treeview control.
What you could do is put a kind of edit/save structure into each of the subforms, whereby controls in the subform are locked until edit is clicked, and re-locked after save is clicked. So:
private sub bEdit()
editMode true
end sub
private sub bSave()
...save logic
editMode false
end sub
private sub editMode(isEdit as boolean)
dim ctl as control
for each ctl in me.controls
if ctl.controltype is actextbox or ctl.controltype is accombobox then
ctl.locked = (not isEdit)
end if
next
end sub
With this approach, it's then a small task to add editmode control for the parent form by adding
me.parent.editmode isEdit
to the end of of the editmode procedure.
In the parent form, editMode will need to be a PUBLIC sub.
In this sub, control whether the tree will do anything when clicked on:
public sub editMode(isEdit as boolean)
tree.enabled = (not isEdit)
end sub

Charts aren't rendered in MS Access forms

I created a form that contains 5 charts. When opening, the cursor changes 5 times, so obviously the data is queried, but the charts aren't rendered and left blank. However, when moving the form outside of the screen and back in, parts of the chart are shown, so it seems that is just a repaint missing.
I tried to execute me.chart1.repaint on several events, but I haven't found the appropriate event and I am not sure if me.chart1.repaint is actually necessary.
Private Sub chart1_Updated(Code as integer)
me!chart1.Visible = True
End Sub
Don't worry if visible already true!
I am using this code as a workaround:
Private Sub chart1_Updated(Code As Integer)
DoCmd.Minimize
[Forms]![myform].SetFocus
DoCmd.Restore
End Sub
Sometimes the form is doing too many things while rendering the graphs, and the actual painting does not have time to finish before processing moves on the next object. You can force Access to "catch a breath" like this:
Private Sub Detail_Paint()
DoEvents
End Sub
Since the Detail section of the form is doing the actual rendering, it has a chance to finish each object before moving on to the next.