I have an application written in VBA for Excel that takes in a live data feed. Whenever there is a change in the data, various events are triggered within VBA.
I also have some UserForms with ComboBoxes on them. My problem is that when I click the down arrow on the ComboBox and try to make a selection, the moment I get an update from the data feed, the ComboBox resets. What I would like to do is pause the events while I am making my selection in the ComboBox and then unpause it when I am done. How do I generate this functionality?
Try this to turn off:
application.enableevents = false
And this to turn back on:
application.enableevents = true
To pause and show a message and to keep working on something during the pause. finally press button
Public Ready As Boolean
Private Sub Command1_Click()
Ready = True
End Sub
Private Sub Form_Load()
Me.Show
Ready = False
Call Wait
Label1.Visible = True
End Sub
Public Function Wait()
Do While Ready = False
DoEvents
Loop
End Function
Maybe you can put a flag to bypass the update event on your combobox until a selection is made.
Private bLock as boolean ' declare at module level
' When a user clicks on the combobox
Private Sub DropDownArrow_Click() ' or cboComboBox_Click()
bLocked = True
End Sub
' This procedure is the one that does the updating from the data source.
' If the flag is set, do not touch the comboboxes.
Private Sub subUpdateComboBoxes()
If Not bLocked then
' Update the comboboxes
End If
End Sub
' When the selection is made, or the focus changes from the combobox.
' check if a selection is made and reset the flag.
Private Sub cboComboBox_AfterUpdate() ' Or LostFucus or something else
if Format(cboComboBox.Value) <> vbNullString Then
bLocked = False
End If
End Sub
Hope that helps.
Related
Just wanted to ask, Is there a form_closing event equivalent in VB6? (.bas). the reason I ask is that I wanted to prevent first closing the application if there's an open sub-window.
something like this.
Private Sub MainForm_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
If hasSubWindow Then
MessageBox.Show("You currently have active sub-window(s)")
e.Cancel = false
End If
End Sub
There are three events: Form_QueryUnload(Cancel As Integer, UnloadMode As Integer), Form_Unload(Cancel As Integer) and Form_Terminate().
Form_QueryUnload fires before the Form_Unload where setting Cancel to any value other than 0 cancels the unload and UnloadMode indicates the cause of the unload event.
See https://learn.microsoft.com/en-us/previous-versions/visualstudio/visual-basic-6/aa445536(v=vs.60)?redirectedfrom=MSDN
Form_Unload takes an integer that if set to any value other than 0, cancels the Unload.
The Unload event procedure is where programmers usually put cleanup code. The Unload event fires after the QueryUnload event. The Unload event procedure takes a single parameter, the Cancel parameter. Unload's Cancel parameter works the same as QueryUnload's Cancel parameter.
The Terminate event happens when the instance of the form has been completely unloaded and all the form's variables have been set to Nothing. The Terminate event happens only when you explicitly set the form to Nothing in your code during or after the Unload event procedure.
Source: https://www.freetutes.com/learn-vb6-advanced/lesson6/p5.html
In your case, you probably want to put code into Form_QueryUnload or Form_Unload that checks if there are any other open forms.
Private Sub Form_Unload(Cancel As Integer)
If hasSubWindow = True Then
MsgBox "You currently have active sub-window(s)", vbInformation, "Confirm"
Cancel = 1
End if
End Sub
Ok, after searching for an hour, I still haven't found the right answer for this. All I want is to disable the right click on my button because it's creating a bug, according to our tester. I don't know if VB6 can't do this, but if VB6 can't do this, is there any possible way? Ok, just to be more specific, here is my example...
'I found this somewhere...
Private Sub cmdExportCSV_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single)
If Button = vbRightButton Then
'Do Nothing
End If
End Sub
'Then I have here
Private Sub cmdExportCSV_Click()
'Some logic here
End Sub
But when I click the right button on my mouse, the cmdExportCSV_Click() still executing the code inside.
How about something like this then (based upon your code):
Private m_mouseButton As Integer
Private Sub cmdExportCSV_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single)
m_mouseButton = Button
End Sub
Private Sub cmdExportCSV_Click()
If m_mouseButton = vbRightButton Then
'Do Nothing
Exit Sub
End If
'Some logic here
End Sub
I didn't run this or anything, but it should work.
I have resolved my own problem.
From this..
Private Sub cmdExportCSV_Click()
If m_mouseButton = vbRightButton Then
'Do Nothing
Exit Sub
End If
'Some logic here
End Sub
To this..
Private Sub cmdExportCSV_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single)
If Button And vbRightButton Then
Exit Sub
End If
'Some logic here
End Sub
That's it! VB6 won't directly allow you to disable the mouse right and mouse left button. My solution is just to exit event whenever the user click the mouse right button.
Anyway, I'm sorry as I found out that the system is using asImageCommand not CommandButton, so when you declare an event like this "Private Sub cmdExportCSV_Click()", the asImageCommand control will trigger when you click the mouse-right and mouse-left button. But if you are using CommandButton, it will only trigger when you click the left-button, and won't allow you to use the right-button of the mouse.
I think I have to update the title of my question.
I'm in the process of converting some outlook VBA macros to an Add-in. I am having difficulty with my macros that create emails based on a template. I decided to code a simple button to create and display a new email with the subject test.
Everything is working up to displaying the email which doesn't happen.
Private Sub ButtonGenEmail_Click(sender As Object, e As EventArgs) Handles ButtonGenEmail.Click
Me.Close()
Dim objApp As Outlook.Application
Dim objMail As Outlook.MailItem
objApp = Globals.ThisAddIn.Application
objMail = objApp.CreateItem(Microsoft.Office.Interop.Outlook.OlItemType.olMailItem)
objMail.Subject = "test"
objMail.Save()
objMail.Display(False)
End Sub
At one point I added msgbox "Done" after objMail.Display(False) and the message never appears.
Thanks in advance
This should obviously work. I'm not so skilled in Outlook but I guess the problem here is that you run it from a form (I see the Me.Close)
Isn't then Outlook blocking to display the mail because the form is still open (I guess modal = ShowDialog())?
I think you will have to either change the form to be not modal (use Show() instead of ShowDialog()) or handle the event after the form is closed, something like
All code below written from top of my mind, so I may miss something
A method from where you initialize the form
Dim frm as new YourForm()
frm.ShowDialog()
if frm.MyState = TheyClickOnButton Then
' Run your mailItem code here
End If
in the form code
Public Enum State
Unknown = 0
TheyClickedOnButton
End Enum
Public Property MyState as State
Private Sub ButtonGenEmail_Click(sender As Object, e As EventArgs) Handles ButtonGenEmail.Click
MyState = TheyClickedOnButton
Me.Close()
End Sub
I have a local sub that allows the user to move a row of a datagridview, triggered by a button click. The sub works fine in debugger but when it exits control is transfered to the calling form, i.e. the current form is closed. This also happens when no row is moved, i.e. when one of the abort conditions on entrance are met. Simply: exiting this sub will close the form!?!
Private Sub btnMove_Click(sender As Object, e As EventArgs) Handles btnMove.Click
Dim rowToGo As DataGridViewRow
Dim rtgIndex As Integer = 0
If (dgvAuftrag.RowCount <= 1) or (dgvAuftrag.CurrentRow Is Nothing) Then
Beep()
Exit Sub
End If
rowToGo = dgvAuftrag.CurrentRow
rtgIndex = rowToGo.Index + 1
If (rtgIndex >= dgvAuftrag.RowCount) Then rtgIndex = 0
Try
dgvAuftrag.Rows.Remove(rowToGo)
dgvAuftrag.Rows.Insert(rtgIndex, rowToGo)
Catch ex As Exception
IssueErrorMessage(ex)
End Try
End Sub
All other local subs and functions work normal, just this one behaves strange. Any ideas how to fix/avoid this bug?
This is not a solution of the problem but a functioning workaround based on the sugestion of Hans. I have introduced a global boolean var named OKtoExit which is intialized to false.
private OKtoExit as boolean = false
Then I have a new FormClose event handler that checks that var. If OKtoExit is false then e.Cancel = true and the handler exits. The regular Exit functions (Save and Quit) set OKtoExit to true, any other code leaves the values unchanged.
Private Sub Current_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
If Not exitOK Then
e.Cancel = True
Exit Sub
End If
End Sub
As I said, this is just a workaround that has the same effect as a normal functioning VB-Code. I would appreciate if somebody could present a real solution!
After many months I discovered the true reason for the problem and I must give all credits to Hans Passant: I had a button on one of the first forms that had the Dialog Result property set to Cancel. This was a really beautyful button so many other buttons in the appliaction were a copy of this first button where I just modified the label. Thus they all led to the unwanted behavior that a form was closed as soon as a user clicked one of them no matter what the label said... After months I discovered that just by chance. Thanks to Hans again, I obviously overlooked his last hint "And look at the button's DialogResult property."!
validation on textbox in vb 6.0
i tried
Private Sub Text1_KeyPress(KeyAscii As Integer)
If Not (KeyAscii = vbKeyBack Or KeyAscii = vbKeyDelete Or KeyAscii = vbKeySpace Or (KeyAscii >= Asc("1") And KeyAscii <= Asc("9"))) Then
KeyAscii = 0
End If
but now i want that paste option should disable when i right click on textbox
If you want to prevent right-click menu items from being used on the textbox you can create your own context menu.
Then, using API calls you need to unhook the default menu from the textbox and hook up the custom menu.
(I'm not aware of other APIs which only let you disable/hide items in the existing context menu)
The downside off course is that any menu item you want to keep such as copy or delete you need to write the code for yourself.
You can find a very good explenation on how to do this here Disable right click menu inside a textbox and here Weird reaction on a popup menu
What next,.. what is if the user uses CTRL+V to paste? Or what if the user has paste mapped to different key combinations, other than CTRL+V?
Validate the data instead?
You can end up writing a lot of code trying to prevent data entry. Why not save that work and instead let the user enter what they like and use the validate event to validate the data?
I wrote a sample on another site on using the validate event of a textbox here: Validate Value Is Numeric. That link also has a vb6 demo project I put together attached in the post.
The type of validation is irrelevant I suppose, it simply demonstrates using the validate event allows you to focus on validating the data, rather than trying to code every single possible way you can think of trying to prevent data to be entered in the first place.
The Validate event is triggered before lostfocus and before the next control's getfocus.
Only if the validate event is not told to cancel the action, will the lostfocus event and any subsequent event be executed.
The Validate event is intended to be used to ensure the control's value is validated before executing any other event.
Private Sub Text1_Change()
If Text1.Tag <> Text1.Text Then
Text1.Text = Text1.Tag
Text1.SelStart = Len(Text1.Text)
End If
End Sub
Private Sub Text1_KeyPress(KeyAscii As Integer)
Text1.Tag = Text1.Text & Chr(KeyAscii)
End Sub
Old problem but still relevant with legacy projects.
The solution proposed by Sam Sylvester is interesting but doesn't allow you to delete characters (use backspace) and appends the 22 ASCII character (Ctrl + V) in the textbox (which is bad).
This solution I found worked for me (prevents paste using Ctrl + V and also using the context menu):
Dim preventPasteFlag As Boolean
Private Sub Text1_Change()
If preventPasteFlag Then
Text1.Text = Text1.Tag
preventPasteFlag = False
Else
Text1.Tag = Text1.Text
End If
End Sub
Private Sub Text1_KeyPress(KeyAscii As Integer)
If KeyAscii = 22 Then
preventPasteFlag = True
End If
End Sub
Private Sub Text1_MouseDown(Button As Integer, Shift As Integer, X As Single, Y As Single)
If Button = 2 Then
preventPasteFlag = True
End If
End Sub
this is quite similar:
Private Sub Text1_Change()
Dim i As Long, sTemp As String
For i = 1 To Len(Text1)
If InStr(1, "0123456789", Mid$(Text1, i, 1)) > 0 Then sTemp = sTemp & Mid$(Text1, i, 1)
Next
Text1 = sTemp
End Sub