UserForm vanishes when clicking ComboBox - excel

First I’m a novice. I’ve been reading, experimenting, and Googling to get this far, but haven’t found anything that helps me understand this.
I’m trying to build a UserForm to collect range data. It’s part of a data centralization effort to add data to “history” workbooks, processing them to track changes and update current interpretations if they’ve changed. The sources vary, but are large and consistent enough to be worth the effort to automate.
Also, I work on am isolated (closed) network so I’ve retyped my code, hopefully (mostly) correctly here.
My UserForm code is:
Private Sub UserForm_Initialize()
Dim wb as Workbook, lastwb as Workbook
For Each wb in Application.workbooks
comboBox1.addItem wb.name
next
ComboBox1 = ActiveWorkbook.name
End sub
Private Sub ComboBox1_Change()
If ComboBox1 <> "" then Application.Workbooks(ComboBox1.Text).Activate
Label1.Caption = "": RefEdit1 = ""
End sub
Private Sub RefEdit1_Change()
Label1.Caption = ""
If RefEdit1.value <> "" then
Label1.Caption = "[" & ComboBox1 & "]" & Replace(refEdit1, "!", "'!")
End sub
I’m calling it with
Private Sub addToHistory()
Dim range1 as range
Dim … 'other variables and code
With New Userform
.Show
range1 = .label
.Hide
Unload Userform1
Debug.Print range1
… 'other code to close/save my workbooks
End Sub
Whenever I try to click on my combo box it vanishes. Even marking every line in the UserForm code for debugging, it simply vanishes leaving me with no clue what happened or how to prevent it.

Related

VBA - Using go back button shows data from first sheet

I have an Excel that functions as a sort of decision tool, where questions are being asked and one needs to navigate through the workbook with buttons.
I have made a macro to function as a "go back" button, which activates the previously active sheet and hides the one you are on now. It works, but it keeps showing the navigation buttons from the first sheet. The text from the correct sheet does appear. If I go to another sheet and back, the data appears correct.
Is there a way to refresh the sheet so the correct information shows up, or is this a problem to do with the buttons and the macros behind them?
The macro I have used for the go back button:
(in workbook):
Sub Workbook_SheetDeactivate(ByVal sh As Object)
LastSheet = sh.Name
End Sub
(in module):
Global LastSheet As String
Sub goback()
Sheets(LastSheet).Visible = True
Sheets(LastSheet).Activate
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
With ws
If .Name <> "BM" Then
.Range("H9:R31").Font.Color = RGB(255, 255, 255)
End If
End With
Next ws
Sheets(LastSheet).Visible = False
End Sub
Even though there are no calculations, I did try including ActiveSheet.EnableCalculation but that did nothing.
Any help would be greatly appreciated.
Maybe I am reading this incorrectly but is the issue that the buttons are not dissapearing? if so this may help:
Sub hidebutton()
Dim sh As Shape
For Each sh In Sheet1.Shapes
If sh.Name = "Button 1" Then
sh.Visible = True
End If
Next
End Sub

Set a variable name to a Workbook selected from a VBA ComboBox

I will always have Workbook SQ_Macro_v1 as my main DB.
Two named Workbooks old_wk and new_wk will have different names, as I will choose them among the currently active WB on my computer.
I am going for a VBA ComboBox listing it all to a choice of mine, but in the end I am not able to store the name of my chosen WB.
Sub Macro1()
Dim main_wk, old_wk, new_wk As Workbook
Set main_wk = Workbooks("SQ_Macro_v1.xlsm")
Set old_wk = Workbooks(old_chosen) 'also tried UserForm1.ComboBox1.Value
Set new_wk = Workbooks(FileName_New) '
main_wk.Sheets("Main_DB").Range("C4").Value = old_wk.Worksheets("Sheet 1 Synthese").Range("C35").Value
As I run the UserForm code below, the old_chosen variable I set as empty in the main Sub. It seems that as I close the UserForm after it runs, nothing remains stored. Any clues to keep that variable saved after I close the UserForm?
Option Explicit
Public Sub UserForm_Activate()
Dim vWorkbook As Workbook
ComboBox1.Clear
For Each vWorkbook In Workbooks
ComboBox1.AddItem vWorkbook.Name
Next
End Sub
Public Sub CommandButton1_Click()
If ComboBox1.ListIndex <> -1 Then
Call YourMacro(ComboBox1)
End If
End Sub
Public Sub YourMacro(vWorkbookName As String)
Dim old_chosen As String
old_chosen = Me.ComboBox1.Value
MsgBox "You choose: " & Workbooks(vWorkbookName).Name
End Sub
The MsgBox pops up but no value is stored afterward:
Public Sub YourMacro(vWorkbookName As String)
Dim old_chosen As String
old_chosen = Me.ComboBox1.Value
MsgBox "You choose: " & Workbooks(vWorkbookName).Name
End Sub
You have declared the variable at procedure level and hence it is not visible after the userform is closed.
To make this variable available to all procedures in the project, precede it with the Public statement. Insert a module and paste this there
Public old_chosen As String
Having said that, I would recommend moving Macro1 inside the userform and handle the code from there after declaring the variable at module level

Code keeps running after modeless userform is opened

When a modeless userform gets loaded, the code in it (except for the Userform_Initialize sub) sometimes does not execute and the main code which calls the userform continues running.
I had it solved, somehow, but this was in the latest update of my program which unfortunately got corrupted.
Sub start() 'shortened drastically, but accurate
'....
If UBound(rs.GetRows(1000000), 2) + 1 < 6 Then
.Close SaveChanges:=False
ThisWorkbook.Sheets("Start").Range("DA1").Value = "1"
ThisWorkbook.Sheets("Start").Range("DA2").Value = MachineNr
UserForm1.Show vbModeless
GoTo ExSub
End If
'...
ExSub:
End Sub
And in the userform module:
Private Sub UserForm_Initialize()
Dim wb As Workbook
If ThisWorkbook.Sheets("Start").Bijwerken = "ja" Then
Me.CommandButton2.Caption = "Cancel"
Me.Label1.Caption = "Select a file to update"
bestand = ""
With Me.ComboBox1
For Each wb In Application.Workbooks
If Not wb.Name = ThisWorkbook.Name Then
For Each sht In wb.Sheets
If sht.Name = "AssetTypeTask" Then
.AddItem wb.Name
Exit For
End If
Next sht
End If
Next wb
End With
Else
bestand = ""
With Me.ComboBox1
For Each wb In Application.Workbooks
If Not wb.Name = ThisWorkbook.Name Then
.AddItem wb.Name
End If
Next wb
End With
End If
End Sub
The code runs through the Userform_Initialize sub without issues, but the userform does not appear at the front of the screen and the code continues at GoTo ExSub which then ends the code execution. The userform stays open but closes as I press one of the commandbuttons on it.
"Code execution will also continue in the background while a modeless
form is shown."
This is what brought me back on my feet. I knew this but had forgotten about it as I firmly believe and still believe that in previous versions of my program I had a modeless UF running that DID interrupt the code.
I ended up solving the issue of the running code by adding a simple loop to check the state of the UF
Do Until Userform1.Visible = False
DoEvents
Loop
This is a slight drawback for the CPU of course, so not ideal, but since this is not a very intensive part of the program, it will do.
The UserForm I use in this instance has to be modeless, because the user needs to be able to scroll through the userform to make sure what they are populating the controls in the UF with is correct. This is not programmable.
If anyone has any other ways of achieving this, please let me know.

Using VBA userform to select ranges on multiple sheets - sheet changes back to original activesheet

I have a userform which has multiple RefEdit controls. I need the user to select ranges from multiple sheets and the userform has to be complete before the rest of the code can run.
Issue: The activesheet is "Sheet1" when the userform is initiated. Each time I select a range on "Sheet2" and click into the next RefEdit the visible Excel sheet returns to "Sheet1". I'd like the sheet to remain on "Sheet2", since clicking between the sheets significantly increases the time it takes to select the data.
Because I need the userform to be completed before continuing with my code, using "vbModeless" doesn't appear to work.
I've tried to step through the userform events which appeared to be relevant but none were activated when I entered the RefEdit, selected the data, or left the RefEdit.
Thanks in advance for any help!
Edit: Using some input from the responses and doing some more research I think I've figured out the problem and a work around.
RefEdit events such as Change or Exit (I tried all of them I think) don't appear to trigger when a change occurs in the control. So I couldn't write code to manipulate the activesheet when I changed the control. A workaround found here: http://peltiertech.com/refedit-control-alternative/ uses a textbox and inputbox to simulate a RefEdit control and will actually trigger when changes are made! Code is below. To add other "RefEdit" controls you should repeat the code in the Userform_Initialize event for each control, then add another TextBox1_DropButtonClick and update TextBox1 to the name of the new control. In use when the control updates the workbook jumps to the previous activesheet and then returns the desired activesheet. Not as smooth as I'd like but much better than it was.
Code:
Private Sub CancelButton_Click()
Unload Me
End
End Sub
Private Sub OKButton_Click()
UserForm1.Hide
End Sub
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
End
End Sub
Private Sub UserForm_Initialize()
Me.TextBox1.DropButtonStyle = fmDropButtonStyleReduce
Me.TextBox1.ShowDropButtonWhen = fmShowDropButtonWhenAlways
End Sub
Private Sub TextBox1_DropButtonClick()
Dim ASheet As String ' Active sheet
Me.Hide
'Use input box to allow user to select a range
On Error Resume Next
Me.TextBox1.Value = Application.InputBox("Select the range containing your data", _
"Select Chart Data", Me.TextBox1.Text, Me.Left + 2, _
Me.Top - 86, , , 0)
On Error GoTo 0
'Check if there is a sheet name - if the range selected is on the activesheet the output of the inputbox doesn't have a sheet name.
If InStr(1, Me.TextBox1.Value, "!", vbTextCompare) > 0 Then ' there is a sheet name
ASheet = Replace(Split(Me.TextBox1.Value, "!")(0), "=", "") ' extract sheet name
Else ' there is no sheet name
Me.TextBox1.Value = "=" & ActiveSheet.Name & "!" & Replace(Me.TextBox1.Value, "=", "") ' add active sheet name to inputbox output
ASheet = ActiveSheet.Name
End If
Worksheets(ASheet).Activate ' set the active sheet
Me.Show
End Sub
Have you tried something as simple as:
Sheets("Sheet2").Select
somewhere in the beginning of your form code ?
Since you haven't posted your code, it's hard to provide a good answer.
Hope this helps a little :)
This form module worked for me.
Private Sub CommandButton1_Click() 'Cancel Button
Unload Me
End Sub
Private Sub CommandButton2_Click() 'GO Button
Dim newSheet As Worksheet
abc = Split(RefEdit1.Value, "!")
cbn = abc(0)
Unload Me
Set newSheet = Worksheets(abc(0))
newSheet.Activate
End Sub

Print when Userform1 unloads via CommandButton1

Userform1 ComandButton1 code is similar to this (contains more lines of CheckBox checks):
Sub CommandButton1_Click()
Application.DisplayAlerts = False
Set WB = ActiveWorkbook
If CheckBox25.Value = False Then
WB.sheets("PQC 1025").Delete
Else: CheckBox25.Value = True
End If
Unload Me
End
Application.DisplayAlerts = True
End Sub
The second macro will be a Format/Print macro:
Sub Format_Print()
Dim ws As Variant
For Each ws In Workbook
ActiveSheet.PageSetup.LeftFooter = "" & Format(DateTime.Now(), "yyyyMMdd hh:mm:ss")
ActiveSheet.PageSetup.RightFooter = "Page &P of &N"
Next
For Each ws In Workbook
ActiveSheet.PrintOut Copies:=1, Collate:=True
Next
End Sub
I honestly don't know where to start. I'm not a strong coder and it took me a while to get as far as I did.
I would like this macro to automatically happen when Userform1 unloads after use of CommandButton1 (the Okay button). I do not want this second macro to start automatically when CommandButton2 is used to unload Userform1 (the Cancel button).
Any input on how I might try this would be helpful.
I ended up making a new button on the main form to format/print. I fixed a few of the issues I was having with my initial format/print code, removed all of the dimension and setting and simply said "sheets.select" which was the simple fix to object errors.
I had no check that people selected the correct sheets, so I figured this was a safer approach.

Resources