Bugs in Excel's ActiveX combo boxes? - excel

I have noticed that I get all sorts of annoying errors when:
I have ActiveX comboboxes on a worksheet (not an excel form)
The comboboxes have event code linked to them (eg, onchange events)
I use their listfillrange or linkedcell properties (clearing these properties seems to alleviate a lot of problems)
(Not sure if this is connected) but there is data validation on the targeted linkedcell.
I program a fairly complex excel application that does a ton of event handling and uses a lot of controls. Over the months, I have been trying to deal with a variety of bugs dealing with those combo boxes. I can't recall all the details of each instance now, but these bugs tend to involve pointing the listfillrange and linkedcell properties at named ranges, and often have to do with the combo box events triggering at inappropriate times (such as when application.enableevents = false). These problems seemed to grow bigger in Excel 2007, so that I had to give up on these combo boxes entirely (I now use combo boxes contained in user forms, rather than directly on the sheets).
Has anyone else seen similar problems? If so, was there a graceful solution? I have looked around with Google and so far haven't spotted anyone with similar issues.
Some of the symptoms I end up seeing are:
Excel crashing when I start up (involves combobox_onchange, listfillrange->named range on another different sheet, and workbook_open interactions). (note, I also had some data validation on the the linked cells in case a user edited them directly.)
Excel rendering bugs (usually when the combo box changes, some cells from another sheet get randomly drawn over the top of the current sheet) Sometimes it involves the screen flashing entirely to another sheet for a moment.
Excel losing its mind (or rather, the call stack) (related to the first bullet point). Sometimes when a function modifies a property of the comboboxes, the combobox onchange event fires, but it never returns control to the function that caused the change in the first place. The combobox_onchange events are triggered even when application.enableevents = false.
Events firing when they shouldn't (I posted another question on stack overflow related to this).
At this point, I am fairly convinced that ActiveX comboboxes are evil incarnate and not worth the trouble. I have switched to including these comboboxes inside a userform module instead. I would rather inconvenience users with popup forms than random visual artifacts and crashing (with data loss).

I don't have a definitive answer for you, but I can tell you that I stopped using ListFillRange and LinkedCell for ActiveX controls about 10 years ago. I don't recall what particular problems I encountered. I just remember coming to the conclusion that whatever little time they saved me isn't worth the brain ache of trying to track down the bugs. So now I populate the controls through code and deal with output in the events.

My active-x combo box works fine when my Dell is docked but resizes to a larger font each time it is clicked when the Dell is undocked - very strange. I added resizing code which works when undocked, but both .height and .scaleheight fail when docked and when triggered programmatically (even stranger).
Sheet2.Shapes("cb_SelectSKU").Select
Selection.ShapeRange.Height = 40
Selection.ShapeRange.ScaleHeight 0.8, msoFalse, msoScaleFromTopLeft
I then added my own enableevents-like switch so that the resizing only occurs when a user selects a combobox value, not when anything is affected while a macro is running.
Select Case strHoldEvents
Case Is = "N" 'Combobox resizing fails with error when triggered programatically (from SaveData)
Call ShowLoadShts
Sheet2.Shapes("cb_SelectSKU").Select
Selection.ShapeRange.Height = 40
Selection.ShapeRange.ScaleHeight 0.8, msoFalse, msoScaleFromTopLeft
Case Else
End Select
Finally that seems to work, whether docked or undocked, whether triggered by the user or during a procedure. We'll see if it holds...

I have a partial reply for the Dell users, and for your formatting problem
The formatting and display problem is another known-but-undocumented issue in Excel.
Many flat-panel monitors (including laptop displays) are unable to render fonts correctly in textbox controls on an Excel spreadsheet: you've got a mild version of this problem.
Our company has recently upgraded to new (and much larger!) monitors, and I can at last use textboxes, labels and combo boxes in worksheets. Our old Samsung screens displayed text controls correctly, but any manual or VBA-driven updates resulted in an illegible jumble of overlapping characters.
Listboxes don't have the problem: it's the 'textbox' part of your combo box that has the issue. Try manipulating a listbox in VBA event procedures: it's a kludge but it works.
In-Cell dropdowns from Data Validation lists don't have the problem. If you set up a validation list for a cell, then set the data validation error messages to empty strings, you can enter free-form text in the cell; the drop-down list is advisory, not a mandatory limit-to-list.
The problem is sometimes ameliorated (but never completely fixed) by using the Terminal or System fonts in your Active-X control.
The problem is sometimes ameliorated (but never completely fixed) by using a VBA event to nudge or resize your Active-X control by 0.75 mm.
Check if your laptop manufacturer has released an upgrade to the display drivers.
...And that's everything I know about the font rendering problem. If Mike (with his Dell laptop) is reading this: Good luck with those workarounds - to the best of my knowledge, there's no real 'fix'.
The stability problem was a major headache for me until Excel 2003 came out: using any Active-X control in the sheet was a source of instability. The Jury's still out on Listbox controls embedded in a sheet, even in Excel 2003: I still avoid using them.

So I was facing the same issues. I had a file with drop down lists on which I had superimposed the combobox to fight the issue of illegibility when zooming out too much. This was what my code looked like INITIALLY:
'=========================================
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim str As String
Dim cboTemp As OLEObject
Dim ws As Worksheet
Set ws = ActiveSheet
On Error GoTo errHandler
If Target.Count > 1 Then GoTo exitHandler
Set cboTemp = ws.OLEObjects("ComboBox1")
On Error Resume Next
If cboTemp.Visible = True Then
With cboTemp
.Top = 10
.Left = 10
.ListFillRange = "Treatment"
.LinkedCell = Target.Address
.Visible = False
.Value = ""
End With
End If
On Error GoTo errHandler
If Target.Validation.Type = 3 Then
'if the cell contains a data validation list
Application.EnableEvents = False
'get the data validation formula
str = Target.Validation.Formula1
str = Right(str, Len(str) - 1)
With cboTemp
'show the combobox with the list
.Visible = True
.Left = Target.Left
.Top = Target.Top
.Width = Target.Width + 15
.Height = Target.Height + 5
.ListFillRange = ws.Range(str).Address
.LinkedCell = Target.Address
End With
cboTemp.Activate
'open the drop down list automatically
Me.ComboBox1.DropDown
End If
exitHandler:
Application.ScreenUpdating = True
Application.EnableEvents = True
Exit Sub
errHandler:
Resume exitHandler
End Sub
'====================================
'Optional code to move to next cell if Tab or Enter are pressed
'from code by Ted Lanham
'***NOTE: if KeyDown causes problems, change to KeyUp
'Table with numbers for other keys such as Right Arrow (39)
'https://msdn.microsoft.com/en-us/library/aa243025%28v=vs.60%29.aspx
Private Sub ComboBox1_KeyDown(ByVal _
KeyCode As MSForms.ReturnInteger, _
ByVal Shift As Integer)
Select Case KeyCode
Case 9 'Tab
ActiveCell.Offset(0, 1).Activate
Case 13 'Enter
ActiveCell.Offset(1, 0).Activate
Case Else
'do nothing
End Select
End Sub
'====================================
I was facing all sorts of issues but as primarily mentioned on this thread, the LinkedCell issue was the biggest. My selection from the drop down menu would go wherever on the sheet I had clicked last, instead of the cell I had chosen the drop down box from, and in process, also disturbing the code of wherever the selection would go. I used a simple ONE LINE code to make sure my program in ActiveX runs only when its a drop down menu. I used this before the LinkedCell command ran:
If Target.Validation.Type = 3 Then
'... all the normal code here...
End If
So my code now looks like this:
'... Code as before
If Target.Validation.Type = 3 Then
' NEW CODE LINE ABOVE
If Target.Count > 1 Then GoTo exitHandler
Set cboTemp = ws.OLEObjects("ComboBox1")
On Error Resume Next
If cboTemp.Visible = True Then
With cboTemp
.Top = 10
.Left = 10
.ListFillRange = "Treatment"
.LinkedCell = Target.Address
.Visible = False
.Value = ""
End With
End If
End If
' End of the new If
Unbelievably, this worked. And now my excel sheet isn't misbehaving anymore. Hope this helps.

For this reason, I use cells with data validation lists when putting combo boxes on a spreadsheet.

Related

Excel VBA: How to dynamically enlarge/expand ActiveCell?

I ran across a question in a facebook group which asked how to expand/enlarge/zoom the active cell in an Excel worksheet.
Normally, I don't like to mess with the Excel UI visually but I guess that the person must have some form of visual impairment or something which requires a clear and bigger view of the contents of the active cell.
I searched in stackoverflow and googled and also in the similar questions box which doesn't show the exact same answer I was searching.
I believe that there are multiple possible approaches to this question.
1.to change the rowHeight and columnWidth of the activecell.
Application.ActiveCell.RowHeight=50
Application.ActiveCell.ColumnWidth=50
2.to change the autofit of the column containing activecell.
Application.ActiveCell.EntireColumn.AutoFit
3.to change the zoom level of activewindow.
ActiveWindow.Zoom 50
4.to assign the activecell contents into a textbox.text property on a modeless userform.
I think methods 1 & 4 are most likely to work and personally, I prefer method4 because it seems less likely to visually disturb the user.
Workbook_SheetSelectionChange "event will be used
Allow me to answer to my own question with the following VBA code.
Please feel free to improve upon this.
'copy paste into ThisWorkbook module
'explicit error checking was not performed - use at users' own risk
Option Explicit
Const increasedColumnWidth = 50'change how large as per requirement
Const increasedRowHeight = 50
'saved properties to restore later
Private saved_ActiveCell_ColumnWidth As Integer
Private saved_ActiveCell_RowHeight As Integer
Private saved_ActiveCell As Range
'can also be placed into individual worksheet modules but used ThisWorkbook to cover newly inserted sheets
Private Sub Workbook_SheetSelectionChange(ByVal Sh As Object, ByVal Target As Range)
'very important that sh must be a worksheet<-not checked here
' If Sh.Name = "Sheet1" Then 'set sheet name here to limit to Sheet1 only or any particular sheet
If Target.Cells.CountLarge = 1 Then 'if .Count, there may be overflow
Application.ScreenUpdating = False 'to reduce flashing
If Target.Value <> "" Then 'or isempty(target.value)
'restoring previous activecell if there's one
If Not saved_ActiveCell Is Nothing Then
saved_ActiveCell.EntireColumn.ColumnWidth = saved_ActiveCell_ColumnWidth
saved_ActiveCell.EntireRow.RowHeight = saved_ActiveCell_RowHeight
End If
'backup
Set saved_ActiveCell = Target 'Application.ActiveCell
saved_ActiveCell_ColumnWidth = Target.ColumnWidth
saved_ActiveCell_RowHeight = Target.RowHeight
'expanding
Target.EntireRow.RowHeight = increasedRowHeight
Target.EntireColumn.ColumnWidth = increasedColumnWidth
Else'if activecell doesn't contain any value, restore previous activecell to previous size
If Not saved_ActiveCell Is Nothing Then
saved_ActiveCell.EntireColumn.ColumnWidth = saved_ActiveCell_ColumnWidth
saved_ActiveCell.EntireRow.RowHeight = saved_ActiveCell_RowHeight
End If
End If
Application.ScreenUpdating = True
End If
' End If
End Sub
Sharing this code doesn't mean that I support messing around with Excel UI manipulation especially those that would disturb the user.
The provided code is just for changing activecell's rowHeight and columnWidth to give the user the visual effect that the activecell is expanded/enlarged.
I've seen other code that would create an image of activecell on-the-fly and gives the user the impression of a zoomed cell here.
The code shared herewith is only for manipulating the rowHeight and columnWidth of the ActiveCell.
The method dealing with a textbox on a modeless userform is still getting improvements and will eventually be available(probably) on my GitHub as a .xlsm file.
Also uploaded a .gif below to clearly display the requirements and the results.
This video .gif contains features not available in the code shared here.

How to allow user to review worksheet using excel vba

My macro generates a series of reports that are 60 columns wide. I want users to be able to review the reports on screen before printing them or going on to another segment of the macro.
it there a way to set a scrollarea, have user review it, and then have the respond to a message box to continue the routine?
I tried this:
Sub reviewdata()
' Application.ScreenUpdating = False
Worksheets("Fin. Stmts").ScrollArea = ""
Application.Goto Reference:="monthlydata"
ActiveCell.Offset(2, 1).Select
ActiveWindow.FreezePanes = True
Worksheets("data. Stmts").ScrollArea = "monthlydata"
If MsgBox("End Review", vbOKOnly) = vbOK Then
End If
ActiveWindow.FreezePanes = False
Worksheets("data. Stmts").ScrollArea = ""
End Sub
the problem is that once the if, then statement is executed the user can not move around the worksheet since the routine needs a response to continue.
any insights are most appreciated.
thanks.
You can Use a Dummy Variable:
Dim dummy As Range
Set dummy = Application.InputBox("Scroll and Check. After That Select Ok!", "This is Specially created so that you can", Default:="A1", Type:=8)
Input Box that Takes in Range Allows you to Scroll in Background. Keep hitting Ok in and nothing will change, code will run as it is running at the moment.
This is a little clumsy but it sort of gets what you want. Instead of using a MsgBox use and InputBox as a range, which will allow the user to click around and scroll, as you describe. Whenever they hit okay/cancel, the macro will continue.
So probably replace your MsgBox line of code with....
Dim boom As Variant
boom = Application.InputBox("When you're done hit ""Cancel""... (""OK"" might lead to problems...)", _
"Scroll around and look at stuff", _
, , , , , 8)
I would recommend doing two macros instead, but this probably does what you need.
You can show that message in a small userform and call that userform in modeless state as shown below.
UserForm1.Show vbModeless
This way you will be able to navigate in the sheet with that message still showing.
You can also put the rest of the code in the button click event as shown below.
Option Explicit
Private Sub CommandButton1_Click()
ActiveWindow.FreezePanes = False
Worksheets("data. Stmts").ScrollArea = ""
Unload Me
End Sub

Allow null input when retrieving data from multiselect listbox

I'm trying to create a simple worksheet-based form that will pull data from the selections into another sheet on the Excel workbook. This is my first time messing with Visual Basic and ActiveX controls and I don't have much programming experience, but with a lot of Googling I've managed to muddle through some so far.
The part in question: I have a couple of multiselect boxes that, with the click of a button, push the data into the spreadsheet, using this code:
Private Sub CommandButton1_Click()
Dim I As Long
Range("A10").Select
Range(Selection, Selection.End(xlToRight)).ClearContents
With Me.ListBox1
For I = 0 To .ListCount - 1
If .Selected(I) Then
Flg= True
txt = txt & "," & .List(I)
End If
Next
End With
If Flg Then
With Sheets("Sheet1")
.Range("A10").Value = Mid$(txt, 2)
End With
End If
txt=""
'Repeat for each listbox'
End Sub
As long as the user has selected at least one item in each listbox, this works fine to pull the data, and from there I can do what I need. But I don't want to require the user to click in each box (that is, I suppose I could force them to click a null selection if they don't want to select something in that box, but it would be easier to just have them not select anything at all). But (understandably) when nothing is selected in a given box, the code I pasted above returns run-time error 1004: No data was selected to parse.
How can I permit the user to make no selection in a box, and have the code just leave the associated cell blank when the data are retrieved?
Wow, after a couple of days of looking I finally found it. This is the code that worked for me:
Private Sub ListBox1_LostFocus()
Dim listItems As String, i As Long
With ListBox1
For i = 0 To .ListCount - 1
If .Selected(i) Then listItems = listItems & .List(i) & ", "
Next i
End With
If Len(listItems) > 0 Then
Range("A2") = Left(listItems, Len(listItems) - 2)
Else
Range("A2") = ""
End If
End Sub
And it came from this page: https://www.mrexcel.com/forum/excel-questions/584437-write-selections-excel-listbox-cell.html ...thanks to 'Marcelo Branco' for providing that answer 7 years ago!
EDIT - This really answers a separate question that I had (about retrieving the data automatically), but it seems to also work for the big question here, since when nothing is selected, the target cell is blank.

Excel 2010 command button disappears

I'm developing an Excel 2010 workbook, in a manual formulas calculation mode.
(file -> options -> formulas -> Workbook calculation -> manual)
I have some command buttons in the sheet (ActiveX controls), and I set them to move and size with cells (right click on the button -> format control -> Properties -> move and size with text).
This is since I have some rows filtered out under some conditions, and I want the buttons placed in these rows to appear and disappear as well, according to the display mode of their hosting rows.
It all goes perfectly fine, till I save he worksheet when some of the rows (hence buttons) are filtered out (i.e. not displayed).
When I re-open the file again, and expand the filtered rows, the buttons don't show. When checking their properties I see that their visible property is True, but their height is 0, and this doesn't change when I un-filter their hosting rows.
I want to emphasize again that before saving the file - both filtering and un-filtering the buttons worked well.
Would much appreciate any help here.
OK so I get the same results either with ActiveX or Form Controls. For whatever reason, it seems the control's original height does not persist beyond the save & close.
Another option would be to simply clear the AutoFilter on the Workbook's Close and Save events. However, this probably is not what you want if you like to leave some filter(s) on when you save and re-open the file. It's probably possible to save the filter parameters in a hidden sheet or by direct manipulation of the VBE/VBA, but that seems like a LOT more trouble than it's worth. Then you could re-apply the filter(s) when you re-open the workbook.
Here is what code I suggest
NOTE: I relied on the worksheet's _Calculate event with a hidden CountA formula (setting, changing, or clearing the AutoFilter will trigger this event). I put the formula in E1 just so you can see what it looks like:
Since your application relies on Calculation = xlManual then this approach will not work exactly for you but in any case, the subroutine UpdateButtons could be re-used. You would need to tie it in to another event(s) or functions in your application, as needed.
Here is the code
Option Explicit
Private Sub UpdateButtons()
'## Assumes one button/shape in each row
' buttons are named/indexed correctly and
' the first button appears in A2
Dim rng As Range
Dim shp As Shape
Dim i As Long
Application.EnableEvents = False
'## use this to define the range of your filtered table
Set rng = Range("A1:A6")
'## Iterate the cells, I figure maybe do this backwards but not sure
' if that would really make a difference.
For i = rng.Rows.Count To 2 Step -1
Set shp = Nothing
On Error Resume Next
Set shp = Me.Shapes(i - 1)
On Error GoTo 0
If Not shp Is Nothing Then
DisplayButton Me.Shapes(i - 1), Range("A" & i)
End If
Next
Application.EnableEvents = True
End Sub
Private Sub DisplayButton(shp As Shape, r As Range)
'# This subroutine manipulates the shape's size & location
shp.Top = r.Top
shp.TopLeftCell = r.Address
shp.Height = r.Height
End Sub
Private Sub Worksheet_Change(ByVal Target As Range)
MsgBox "_Change"
End Sub
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
''## Assumes one button/shape in each row
'' buttons are named/indexed correctly and
'' the first button appears in A2
'Dim rng As Range
'Dim shp As Shape
'Dim i As Long
'
''## Uncomment this line if you want an annoying message every time
''MsgBox "Refreshing Command Buttons!"
'
'Application.EnableEvents = False
''## use this to define the range of your filtered table
'Set rng = Range("A1:A6")
'
''## Iterate the cells, I figure maybe do this backwards but not sure
'' if that would really make a difference.
'For i = rng.Rows.Count To 2 Step -1
' Set shp = Nothing
' On Error Resume Next
' Set shp = Me.Shapes(i - 1)
' On Error GoTo 0
'
' If Not shp Is Nothing Then
' DisplayButton Me.Shapes(i - 1), Range("A" & i)
' End If
'Next
'
'Application.EnableEvents = True
End Sub
For Another option See this article. You can re-purpose existing commands with RibbonXML customization. While this article is geared towards C# and Visual Studio it's possible to do it with the CustomUI Editor.
I had a similar problem with buttons disapearing (moving on upper left corner) when removing filters.
A solution I found was to add a row above the columns headers so that buttons were still appearing at the top of the columns but were not touching the row where filters were placed.
Adding / removing filters stop interfering with buttons' positions.
I had a similar problem where form buttons appear to work fine, but then disappear after saving and reopening the workbook. Specifically this happened when the form button where part of hidden rows (done using vba code).
Seems like a real bug, although I don't know where the link is.
By changing the form buttons to ActiveX buttons, the buttons stopped disappearing, but started moving/bunching to the top of the screen when the rows were hidden. I just added some vba to re-position the buttons (e.g. CommandButton1.Top = Range(A12:A12).Top --> moves the ActiveX command button to the 12th row).

Launch a different sheet by Spin button

want to use a Spin button (ActiveX Control) to show a previous or next sheet. When the button is clicked the event is successfully triggered and the desired sheet is activated but it holds some elements (commands, graphs, etc.,) from the original sheet and shows these as an appending picture.
Sample code for Down button event :
Private Sub SpinButton_JumpToWeek_SpinDown()
Dim sh_num As String
Dim tmp_num As Integer
Application.ScreenUpdating = False
Application.EnableEvents = False
SpinButton_JumpToWeek.Value = Range("B27").Value - 1
tmp_num = SpinButton_JumpToWeek.Value
' Activate desired KTx sheet
sh_num = "KT" & tmp_num
Range("F27").Value = "" 'reset to blank
Sheets(sh_num).Activate
Application.ScreenUpdating = True
Application.EnableEvents = True
End Sub
To override this effect I have to manually select (activate) another sheet and then again select the desired sheet. I tried also to automatize this workaround with a macro, but unfortunately it does not work.
It is interesting that this problem do not occur if I execute code in Debug mode (using breakpoint and the stepping line by line).
Surprisingly, I do not have such problem if I try to show the previous/next sheet by writing a value (sheet name index) into a defined cell (i.e. using the Worksheet_Change event). The desired page is correctly shown. See photos.
Sample code for this evententer image description here:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim sh_num As String
Application.ScreenUpdating = False
Application.EnableEvents = False
If Range("F27").Value > 0 Then
' Activate desired KTx sheet
sh_num = "KT" & Range("F27").Value
Range("F27").Value = "" 'reset to blank
Sheets(sh_num).Activate
End If
Application.ScreenUpdating = True
Application.EnableEvents = True
End Sub
I need to use the Spin button because it is faster and allow me to skip some sheets (for example if these do not have data).
The problem occurs in both 32 and 64-bit Excel.
Do somebody an idea why this problem is occurring and a workaround? Do I have to change some settings or system properties in Excel? Any help would be highly appreciated.
#mehow
I append my commenst here due to large number of words.
I followed your suggestion and tried the example of a UserForm with inserted active control “Microsoft Office Spreadsheet”. I found out that this would not be a good solution for my case, because the response of such sheet is relatively slow (even on a fast PC like mine) when user inserts values into cells. Furthermore, this would greatly complicate my fairly simple *.xlsm workbook, which has more than 50 sheets (1 sheet for each week, the contents of these sheets are then linked to a main sheet), and completely meets my basic necessities (with the exception of this spin button of course).
In my opinion there is probably necessary to manipulate some kind of system property (like for e.g. Application.ScreenUpdating trick), but I do not have enough VBA knowledge to find it.
To clearly explain my question I would need to share my sample workbook, but I do not know how to upload it to this forum. Unfortunately, I am not able upload/show images successfully on this forum (due to my low rating), which would also help a lot.
BTW, I cannot see images on other questions of this forum, too. . Could this problem occur due to missing plugins in a web browser?
You can use a simple trick... before the "Application.screenupdating = true" you can insert the two lines:
ActiveWindow.SmallScroll Down:=-100
ActiveWindow.SmallScroll Up:=100

Resources