Excel Userform/VBA Combine CheckBox & TextBox into a single cell string - excel

A little background about what I'm trying to do:
My userform is going to be used to grade employee training with the results being added to an excel spreadsheet. The checkboxes in my form are representative of the different kinds of mistakes they can make and each mistake ideally has a quantity box that will specify how many times each mistake was made if its box is checked. I need both in one cell, as each row is 1 test for each employee. Here is an example of my userform:
Mistakes Screen Shot
All checkboxes and textboxes share the same number and I've already programmed them to automatically insert a 1 quantity if the box is checked/empty if unchecked. (Of course the quantity must be editable in case a mistake type is duplicated.)
So far I was able to use a loop with a string to get the checkboxes to put their captions into the single cell using this code:
Dim CheckBox As Control
Dim Mistakes As String, delimiter As String
For Each CheckBox In Me.Frame_Mistakes.Controls
If TypeOf CheckBox Is MSForms.CheckBox Then
If (CheckBox.Value) Then
Mistakes = Mistakes & delimiter & CheckBox.Caption
delimiter = " | "
End If
End If
Next
With Sheet1
.Cells(emptyRow, 4).Value = Mistakes
End With
However, so far I have been unable to figure out how to get the quantity to be added at the end of each mistake preceding the delimiter. I would prefer it if I could get the string to be in this format: Mistakes Format in Excel
If my intentions are unclear, I apologize. I am incredibly new and honestly surprised I was able to make it this far. Please and Thanks!

So, if I understand you correctly, You want the output of the Mistakes cell to read
[Caption of checked box](x[Number in Text Box])|[Caption of checked box](x[Number in Text Box])...
If that is so, you simply need to add a snippet of code to the end of your 'Mistakes' variable so that it reads:
Mistakes = Mistakes & delimiter & Checkbox.Caption & "(x" & TextBox.text & ")"
Where things get difficult is that you will need to differentiate between text boxes so that only the one that applies to the relevant checkbox is being used. You could do this in a number of ways, such as passing the Textbox as an argument, or with a switch case to name a few.
Another problem is making sure that the textbox only uses numbers. The way that I accomplish this is with a combination of the IsNumeric() and Val() functions. You first check if the value is numeric, then store it in an int using the Val() function. Since you only need it for a string, though, using the IsNumeric() function alone should be fine.
If you need more specific clarification, I would need to know exactly what you are looking for.

Related

Filling a range of cells with the same value using drop-down list

We all know that Excel has some counter-intuitive behaviours and it is, I believe, one of them:
When you select a range of few cells, starting your selection with the cell with data validation list and choose value from drop-down list: only one cell changes (the one containing drop-down list) instead of all selected.
Sometimes a few magic keyboard shortcuts such as CTRL+d, or combination of CTRL+' and CTRL+ENTER can fix this behaviour, but from my experience clients doesn't like to learn some new hacks, they just want to work everything in as simple way as possible.
I found even similar questions on SO e.g. here:
Adding same drop-down value to multiple cells simultaneously
I know that this is very simple code, but following few lines of code make my life easier, and I am sure this will help somebody too. Code in Worksheet module of course:
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
' MACRO FILLS THE WHOLE SELECTED RANGE
' WITH THE SAME VALUE USING DROP-DOWN LIST
' IN JUST ONE ACTIVE CELL
' change to false if all selected cells should be filled with value
Const FILL_VISIBLE_CELLS_ONLY As Boolean = True
' detecting if dropdown list was used
'
' I am using very clever solution by JvdV from SO
' ~~~~> stackoverflow.com/questions/56942551/
'
' If after edit we're in the same cell - drop-down list was used
' I know that may be also drag&drop or copy-paste
' but it seems no matters here.
' Warning! Should be add one more check if someone used
' 'accept OK character' next to formula bar, not implemented here.
'
If ActiveCell.Address <> Target.Address Then Exit Sub
' preventing error which sometimes occurs
If IsEmpty(ActiveCell.Value) Then Exit Sub
' fill a range or visible range with activeCell value
If FILL_VISIBLE_CELLS_ONLY Then
Selection.Cells.SpecialCells(xlCellTypeVisible) _
.Value = ActiveCell.Value
Else
Selection.Value = ActiveCell.Value
End If
End Sub
When you select a Range of more than one Cell, is is important to distinguish between the Active Cell (the single highlighted cell) and the Selection (the entire selected range, including the Active Cell).
Then:
Any Content (such as Values or Formulas) that you enter into the Formula bar is input into the Active Cell only, not the entire Selection.
Any Formatting changes you make are applied to the entire Selection, not just the Active Cell.
An exception is when entering an Array formula which applies to the Selection.
Since in this case you are making a change to content not formatting, it is applied to only the Active Cell.
When considering the above, it is not counterintuitive but entirely consistent with the design and operation of the software.
However, from a UX experience this may seem counterintuitive simply because it defies your expectation. This is kind of like a "customer is always right" type situation, which can be very frustrating for programmers, but is essential that it be understood. You can read more about the concept in a series of well-written articles on the topic at https://www.joelonsoftware.com/2000/04/10/controlling-your-environment-makes-you-happy/ (disclosure: the author of these articles happens to be integral to the development history of both Excel and SO, but it is linked here on merit). It was written more than 20 years ago and is still every bit as relevant today.

Simple vba program in Excel

Sub TEST()
If cells(i, "R").Value <> "UK" Then
cells(i, "R").Interior.ColorIndex = 3
End If
End Sub
If I run this program it throws application defined error \
I am new to Excel (beginner)
How to correct this error!!!
Thanks In advance
I think the issue is "R" that I know of the cells method takes 2 parameters one is rows the other is columns (in that order) but this is done by number not letter so if you change it to cell(1,18) then the code above works fine.
This link may also be useful to learn more, among other things it describes how you would normally select a range first as I believe your code above will assume the currently selected page, however you might want to run in on a button click from another page or as soon as the spreadsheet opens.
http://msdn.microsoft.com/en-us/library/office/ff196273.aspx
The problem is that the variable i has not been assigned a value. VBA assumes that it is zero. Since i is used to determine the row of the cell, Excel throws an exception because there is no row 0!
First you have to define i variable
for example: Dim i as variant

Excel VBA Custom Function giving "Reference Not Valid" Error

I've attempted to track down and solve this error for hours now and I just can't figure it out. Here's the setup.
I have one excel workbook which has two sheets in it: "Input" and "Calculations". I've written in a few custom functions to calculate certain things. These functions are used in the "Calculations" sheet, but reference cells in the "Input" sheet. Now if I'm just using the sheet itself everything works perfectly fine and the functions work.
However, I have a second excel workbook which interacts with the first. I have a macro in the second workbook which attempts to define values in the "Input" sheet of the first workbook. However, when it does this, suddenly the functions don't work. When I attempt to trace the error of the cell in the "Calculations" sheet, and attempt to go to the cell in "Input" sheet, it claims the reference is invalid.
I have no idea what the problem is. At first I thought it maybe had something to do with the name of the first workbook (which was "Log K Calculator 7.0.0.xlsm") but I've tried changing that and I get the same problem. Here is the macro in the second sheet which attempts to change the values in the first:
Sub macro()
Dim logK As String
Dim this As String
logK = "Log K Calculator 7.0.0.xlsm"
this = ThisWorkbook.Name
Workbooks(logK).Activate
Workbooks(logK).Sheets("Input").Cells(11, 4).Value = Workbooks(this).Sheets(1).Cells(1, "B").Value
Workbooks(logK).Sheets("Input").Cells(12, 4).Value = Workbooks(this).Sheets(1).Cells(2, "B").Value
Workbooks(logK).Sheets("Input").Cells(14, 4).Value = Workbooks(this).Sheets(1).Cells(3, "B").Value
End Sub
I know this thread is 4 years old but, just in case anybody is still searching for the answer like I was, for me this error was caused not by my code but by the fact that I was running the procedure by clicking on a textbox which I had copied from another workbook. I had attached the procedure/macro to the textbox but had forgotten that there was already a hyperlink assigned to the same textbox. Removing the hyperlink fixed the issue.
You might want to check how Excel is treating whatever value is sitting in your external workbook. E.g. is it treating the numbers as text? You could check this by entering, say '10000, '300 and '600 manually in the input sheet (forcing it to treat them as text but display numbers), and see if you get the same ref error.
If you do, then casting the value into a typed variable (Long, Decimal, you name it) would probably fix the issue. Or at least make VBA choke on the incorrectly formatted ones (e.g. some have spaces in them, which might explain the apparent inconsistency)

Creating a custom hyperlink function in excel

I have searched far and wide, but can't find an answer to this simple question. I want to make a custom function in excel which will create a hyperlink.
Excel has a built in hyperlink function that works like this:
=Hyperlink(link_location, display_text)
I want to create a function called CustomHyperlink which takes one parameter, and returns a hyperlink to a google query with that parameter. Just for the sake of the question, lets assume that the passed parameter is a alphanumeric string, with no spaces.
Essentially, calling
=CustomHyperlink("excel")
should be the same as calling
=Hyperlink("http://www.google.com/search?q=excel", "excel")
This seems like such a simple task, but I absolutely cannot find a way to make this function.
Can anyone offer some quick help?
I can offer a partial solution, one that will update an existing hyperlink. This only makes sence if you are using it like, say
CustomHyperlink(A1)
were A1 contains the required serch term
To use,
enter your UDF formula in a cell, eg =CustomHyperlink(A1)
create a hyperlink on the cell (right click, Hyperlink...) . This can be any hyperlink, valid or invalid
put the required search term in the referenced cell, eg in A1 put excel
When the UDF runs it will update the hyperlink to Google the entered search term
Function CustomHyperlink(Term As String) As String
Dim rng As Range
Set rng = Application.Caller
CustomHyperlink = Term
If rng.Hyperlinks.Count > 0 Then
rng.Hyperlinks(1).Address = "http://www.google.com/search?q=" & Term
End If
End Function
In VBA editor you can use
ThisWorkbook.FollowHyperlink Address:=(strWebsite), NewWindow:=True
Which will take you to that specific website, and just build a function around that to navigate you to the site you need.
Nice idea although this isn't possible.
You seem to want to have the formula of the cell as one thing (your custom function call) and yet have the value as another (the hyperlink / URL) which simply isn't possible.
The correct way through VBA to add a hyperlink is to use the Hyperlinks property but it is not possible to call this property, through a Worksheet UDF (because of the reason above).
What is wrong with just using the the built-in =Hyperlink() worksheet function? You could effectively parameterise your URL as follows (where cell A1 = Excel):
=HYPERLINK("http://www.google.com/search?q="&A1)
You can't do this directly for the reasons creamyegg suggests, but there is a way to achieve the functionality albeit with a bit of a performance consideration.
You could use the Worksheet_Change event to track for the presence of your UDF then process the hyperlink addition there.
You would need to set up an empty function to allow this to happen, otherwise Excel will throw an error whenever you entered =CustomHyperlink... in a cell.
The below should work, not really had time to test.
Private Sub worksheet_change(ByVal target As Range)
Dim SearchValue As String
If LCase(Left(target.Formula, 16)) = "=customhyperlink" Then
SearchValue = Mid(target.Formula, 19, Len(target.Formula) - 20)
target.Value = SearchValue
target.Hyperlinks.Add target, "http://www.google.com/search?q=" & SearchValue, , "Search Google for " & SearchValue, SearchValue
End If
End Sub
The performance consideration is of course the volatile Worksheet_Change event as this can really kill large, complex workbooks.

Dynamically Populate Listbox - Exclude Empty cells

I am creating a form in excel (not a userform) and I am populating the listbox using cells. However, these cells are sometimes A1:10 and sometimes they are A1:A4. Is there a way to dynamically change what is shown in the listbox?
Right now, when I use A1:10 and there are only 4 cells populated, I get the list of 4 populated cells followed by 6 blank entries. I'd like to get rid of the 6 blanks when there are only 4.
Unfortunately, this is more of a workaround than a solution. However, it may be able to do what you need it to do. I've been hitting the same wall you are with trying to make ranges dynamic.
Without seeing some code to know exactly what you're doing, try something like this.
Private Sub ListBox1()
x = 1
'Add items to listbox until you reach an empty cell.
Do while Cells(x,1) <> ""
ListBox1.AddItem Cells(x,1)
Loop
I'm not very familiar with listboxes outside of userforms but this should do approximately what you want to do.
Edit your original post with your code so we can try and get a better understanding of what you've tried and what you're trying to do.
You can create a named range using a dynamic formula. Either of the below formulas will work.
=A1:INDEX($A$1:$A$10,MATCH("",$A$1:$A$10,0)-1)
=OFFSET($J$7,0,0,MATCH("",$J$7:$J$32,0)-1)
To create the named range, click ctrl+F3 then click new, insert one of the two options above into the "refers to:" section, then label the new range whatever you would like. in the "row source" section of the listbox simply type in the name you selected for your new named range.

Resources