Dynamically Setting userform Label ForeColor - excel

I have a userform display that is Dynamic and updates itself as I enter in information on a separate worksheet.
What I would like it to do, is set forecolor to red for any negative values that occur under the Deadlift section. I have tried using this code and a few others, but, so far, I do not get errors, nor do I get the font to change color
Sub updateForm2()
Dim lLoop As Long
For lLoop = 163 To 312
If myForm.Controls("Label" & lLoop).Value < 0 Then
myForm.Controls("Label" & lLoop).ForeColor = RGB(255, 0, 0)
Else
myForm.Controls("Label" & lLoop).ForeColor = RGB(0, 0, 0)
End If
Next
End Sub
I have an updateForm, that dynamically updates all the labels as positions change based on the amount lifted
Sub updateForm()
Dim wks As Worksheet
Set wks = Sheets("DeadGenerator")
'Update label values here
myForm.Label1.Caption = wks.Range("c4").Text
myForm.Label2.Caption = wks.Range("c5").Text
to
myForm.Label162.Caption = wks.Range("f41").Text
Then labels
myForm.Label163.Caption = wks.Range("g12").Value
to
myForm.Label312.Caption = wks.Range("k41").Value
are the labels that correspond to the 5 columns under the Deadlift Heading
Any help is appreciated, I am still very new to using Userforms
Thanks

Hope this Help. I replied your form in a really easy way. Just added 3 Labels and linked the caption to cells A1,B1 and C1 (those values are 0,-1,-2).
Ok, First of all, to make this work, you must select ALL the labels you want to have the chance of getting a red backcolor. Then, once you have selected all, use the property TAG (read more here)(in my example, I selected just Label2 and Label3 tho have this chance of red backcolor. Label1 will never ever be red even if caption is below 0). Tag value must be "RedOne" (or adapt the code and tag value to your needs)
Ok, now the code. This code will check EVERY control in your userform. And then, if the TAG value is "RedOne" it will check the caption. And if the caption is below 0, then it will make the backcolor red.
Dim MyLabel As control
For Each MyLabel In Me.Controls
If MyLabel.Tag = "RedOne" Then
If MyLabel.Caption < 0 Then
MyLabel.BackColor = vbRed
Else
MyLabel.BackColor = vbWhite
End If
End If
Next MyLabel
And now, let's test it. Note that only label2 and 3 are red because values are both below 0.
Let's test it with Label1.Caption below 0 also. But Label1.Tag is blank, so backcolor will remain the sam, even with values below 0.
And last test. Let's make Label2 value below 0, but label3 value is over 0. Now, only Label2 gets red backcolor, because it's the only label that meets both conditions (Tag="RedOne" and Value<0).
Hope this helps, and I hope you can adapt it to your needs.
Just 1 advice. To set the Tag value, just select ALL the labels you want (Labels under deadlift section) and then type the Tag Value. You don't need to select one by one and type the Tag value one by one.
Let me know if this worked.

Related

Repopulate Excel data to report specific information whenever a validation list option is switched

I'm working on an Excel financial template that calculates Standard Costs of Manufacturing, and on one tab I need to select from a list (Current, Increase/Decrease, NPI) to tell the calculator to use either a "standard value" or "manual entry", but coming from the same cell.
The Docs saved so that a new WB its set to 'Current' and displays the current 'List Price', 'Bulk Price', and 'Materials Cost' that are called from the 'ROI - Current' to the 'ROI - Target' tab where gross margin is calculated.
However, when you changes through the options, you need to rewrite the called values to whatever it needs to be. When you're doing process improvement, you doing this this a lot just to see how the numbers are moving. So I'm looking for a way to repopulate data a specific way every time a list option is switched.
What I'd like to accomplish is when 'Current' gets selected, the *List Price $(75), Bulk Price $(60), Materials Costs $(18), are called back from the ROI - C tab. (Preferable, nothing would be modifiable unless you changed options, like when using the Validation's error message; but not essential).
Then if Increase/Decrease is selected, List Price and Material Costs populates with the Current $ (but are modifiable fields). Here, Bulk Price is calculated as (CurTabBulk/CurTabList)xIncDecList then used to find the gross margin.
Then when 'NPI' is selected, if only List Price is modified, it calculates bulk price as 0.7 x List Price to assume Material Costs to get gross margin. So as an example of all this:
$75 List x 0.8 = $60 Wholesale X 0.3 = $18 Materials / $60 Wholesale * 100 = 70% Gross Margin (which is the NPI Market Forecast from the ROI - Current Tab building the ROI - Target Tab.)
I can code all this into the cells directly, but whenever you enter your own value, the code that exists in that cell is overwritten. So, I'm looking for a fast 'n dirty way to repopulate it a specific way every time the option is switched.
Thanks all!
UPDATE: So I made it this far at work today using Alt-F11:
I found this code that I put into the VBA:
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Address = "$G$4" Then
Range("H4:I7").Value = "Select"
End If
End Sub
That will set all validation boxes H4:I7 to "Select" after choosing the Category, but I want each cell to update with the value rather than having to keep selecting them since it's the only value in the list.
I then found this VBA that will reset as I need, but have no idea how to make it work at all...
Sub ResetDropDowns()
Dim rngLists As Range
Dim ListCell As Range
On Error Resume Next
Set rngLists = Sheets("Entry Sheet").UsedRange.SpecialCells(xlCellTypeAllValidation)
On Error GoTo 0
If Not rngLists Is Nothing Then
For Each ListCell In rngLists.Cells
ListCell.Value = Range(Trim(Mid(Replace(ListCell.Validation.Formula1, ":", String(99, " ")), 2, 99))).Value
Next ListCell
End If
End Sub
Also, After the independent Category is chosen, I will need to enter values into the white boxes under Product 1 and 2. These boxes move around depending on what ROI category is selected: Current = No white; Adj/ Price =- List & Costs, NPI = List & GM. So, I'm hoping I can just reassign the code to accomplish calling the 'dependent recalculated Values' to the correct cells as changes are made.
Follow the URL for pictures of the spread sheet. This is the dependent list code that I put into the Validation Source (the result numbers in the image) for Product 1 List Price: =INDEX($E$43:$G$43,,MATCH($G$4,$E$42:$G$42,0))
Thanks all for the help.
https://www.excelforum.com/excel-programming-vba-macros/1387101-auto-populate-dependent-validation-list-with-fist-values-from-list.html
This solves it. Right click the tab to open the Code editor. Copy and past below to the window. Change Sheet1 and the Cells to what ever you need. Create a Macro button using an inserted Icon and right click it and select make macro.
Sub ResetDropDowns()
Dim rngLists As Range
Dim ListCell As Range
On Error Resume Next
Set rngLists = Sheets("Sheet1").Range("G21,H21")
On Error GoTo 0
If Not rngLists Is Nothing Then
For Each ListCell In rngLists.Cells
ListCell.Value = Range(Trim(Mid(Replace(ListCell.Validation.Formula1, ":", String(99, " ")), 2, 99))).Value
Next ListCell
End If
End Sub

Add border/shading to picture when cell has same name as picture - Excel

I have built a heat map of the UK. Is it possible to have a certain county highlighted when a cell has the same name as the county?
The Heat Map is made of individual Pictures per County, which have been overlapped. Ideally this would take effect as soon as you finished putting data into the cell.
I understand that Conditional Formatting is unlikely to work, and this will probably require VBA - also, when I try to apply an outline it is currently around the Picture rectangle instead of just the non-transparent part of the image.
Please ask me any questions if you need more info.
Thanks
Rather than use Line, use Glow or Shadow, with a low-or-zero Transparency. For example the following 2 subs will make a Shape called "Picture 1" on Sheet1 start or stop glowing with 0 transparency, which will hopefully give a suitable outline.
Sub MakeShapeGlow()
With Sheet1.Shapes("Picture 1").Glow
.Color.ObjectThemeColor = msoThemeColorAccent5
.Color.TintAndShade = 0
.Color.Brightness = -0.25
.Transparency = 0
.Radius = 6
End With
End Sub
Sub StopShapeGlow()
Sheet1.Shapes("Picture 1").Glow.Radius = 0
End Sub
However - you probably also want to bring the Shape to the Front, so that the other Pictures don't cover up the outline. (You should be able to use "Record Macro" to get code for this)
You can trigger the change with something like this:
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Value = "Cornwall" Then
MakeShapeGlow
Else
StopShapeGlow
End If
End Sub
(Obviously, a For Each loop that un-glows all shapes and then glows as shape based on name, such as "Pic_Cornwall" would be far more efficient than typing out new Subs and If chains for every county)

Excel-VBA combo box value on form load

I have a VBA form which is used to enter data on a sheet. I am currently coding the form so as it will load any data already existing in the sheet back into the form.
For simple text strings it works perfectly.
e.g.
ReqSetup.ReqText = Application.Worksheets("Req Sheet").Range("F11").Value
However, I have some combo boxes, that on the form, when they are selected will enter a number in the corresponding cell.
Fail 1. - Run Time Error 380 - Invalid property value.
ReqSetup.MinPerKgCB = Application.Worksheets("Req Sheet").Range("C27").Value
Fail 2.
Dim MinPerKg As Range
Set MinPerKg = Application.Worksheets("Req Sheet").Range("C27")
ReqSetup.MinPerKgCB = MinPerKg
I'm obviously doing something really simple wrong but I can't work out what it is!!
Kind Regards!
I have some combo boxes, that on the form, when they are selected will
enter a number in the corresponding cell
Then you'd need to do the opposite of your code attempt, i.e.:
Worksheets("Req Sheet").Range("C27").Value = ReqSetup.MinPerKgCB.Value
That you'd better wrap inside a check that any combobox value is actually selected :
With ReqSetup.MinPerKgCB
If .ListIndex <> -1 Then Worksheets("Req Sheet").Range("C27").Value = .Value
End With

From a selected line in a chart, filter a table or pivot table

I am facing a challenge. In a chart with multiple lines, I would like to able when I click on a line or mouse over a line to see the corresponding datapoint in the the table or pivot table...So basically, filtering a table based on the element i click or select on a chart with my mouse.
Do you think that it is achievable ? What would be the methodology ? Is there a VBA code for this ? I have seen examples, but they are working on the oppiste way; click or mouse over an observation and the line is highlighted...
Thanks in advance
saskap
This is really complicated, you have to customize the code for each chart, this example code can be a starting point:
Dim p As Series
Dim pc As Long
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim ch As ChartObject: Set ch = Me.ChartObjects("Chart 1")
With ch
Dim s As Series: Set s = Nothing
On Error Resume Next: Set s = .Chart.SeriesCollection(Target.Value): On Error GoTo 0
If Not p Is Nothing And Not p Is s Then
p.Format.Fill.ForeColor.RGB = pc
End If
If Not s Is Nothing Then
Set p = s
pc = s.Format.Fill.ForeColor.RGB
With s
s.Format.Fill.ForeColor.RGB = RGB(255, 0, 0)
End With
End If
End With
End Sub
The first two rows are global variables that store which Series
object was highlighted last time and what was its original color,
this is needed to restore the original color when a different cell is
selected. Unfortunately global variables in VBA loose their value when the project is reset (e.g. the Stop button is pressed or an error occurs), so it is possible that this code colors a bar and then cannot color it back. If important, these information may be stored in invisible Cells or Chart data but that complicates the code.
The next line means that this is an event handler, a function that is called in response to a certain event, in this case when the selection changes on a certain worksheet (the one on which you insert this - you have to insert this into a worksheet module not a standard code module).
Next we look up the chart based on its name and assign it to a variable, which is of type ChartObject, so early binding will allows us to depend on the support of intellisense (if you type a . it shows members of interfaces).
Then we look up the Series inside the chart based on the name found in the newly selected cell's contents. Since we don't know if the new cell will have a valid name, we have to protect this line with disabling error handling and checking later if the s has a non-nothing value. - This part depends largly on the type of chart and how it represents data, it is possible that you will have to select data based on Series::XValues.
We check if there is a saved value for a previously highlighted bar and if it is different from the current selection, restore its original color.
Finally if the looking up the Series earlier was successful then s is non-null and we save the color of the current bar and highlight it with red fill.

Excel 2007 conditional formatting - how to get cell color?

Let's assume i have the following range from (a1:c3)
A B C
1 -1 1 1
2 -1 0 0
3 0 0 1
Now i have selected the following range, and formatted it using Conditional Formatting (using default red yellow green color scale).... now range colors became
A B C
1 Green Red Red
2 Green Yellow Yellow
3 Yellow Yellow Red
Now I want to ask the color of any cell in the range, for example MsgBox Range("A1").Interior.Color
but it does not say that it is Green, why? Plz can you help me?
Range("A1").Interior.Color always returns 16777215
Range("A1").Interior.ColorIndex always returns -4142
(no matter whether the color of A1 is red, blue, green, ...)
Range("A1", "C3").FormatConditions.Count
this one returns always 0, why?
.Interior.Color returns the "real" color, not the conditionally-formatted color result.
#sss: It's not available via the API.
The best you can do is to test the same conditions you used in the conditional formatting.
To avoid this resulting in duplicate code, I suggest moving your conditional criteria to a UDF. Examples:
Function IsGroup1(ByVal testvalue As Variant) As Boolean
IsGroup1 = (testvalue < 0)
End Function
Function IsGroup2(ByVal testvalue As Variant) As Boolean
IsGroup1 = (testvalue = 0)
End Function
Function IsGroup3(ByVal testvalue As Variant) As Boolean
IsGroup1 = (testvalue > 0)
End Function
Then use these formulas in your Conditional formatting:
=IsGroup1(A1)
=IsGroup2(A1)
=IsGroup3(A1)
Then your code, rather than looking at the color of the cells, looks to see if the condition is met:
If IsGroup1(Range("$A$1").Value) Then MsgBox "I'm red!"
You need to refer the <Cell>.FormatConditions(index that is active).Interior.ColorIndex to retrieve the conditional formatting color of a cell.
You may refer to the below link for an example:
http://www.xldynamic.com/source/xld.CFConditions.html#specific
As a follow up to #richardtallent (sorry, I couldn't do comments), the following link will get you a function that returns you the color index by evaluating the conditional formatting for you.
http://www.bettersolutions.com/excel/EPX299/LI041931911.htm
To get the color of a cell in a Range, you need to reference the individual cell inside the array in the form of Range("A1","C3").Cells(1,1) (for cell A1). The Excel help is pretty good if you look up the name of the property you're having issues with.
Also, Excel 2007 uses Integers for its color types, so your best bet is to assign the color index to an integer, and using that throughout your program. For your example, try:
Green = Range("A1","C3").Cells(1,1).Interior.Color
Yellow = Range("A1","C3").Cells(1,3).Interior.Color
Red = Range("A1","C3").Cells(2,1).Interior.Color
And then to switch the colors to all red:
Range("A1","C3").Interior.Color = Red
Again, check the Excel help for how to use Cells([RowIndex],[ColumnIndex]).
If the above doesn't work for you, check to see what .Interior.PatternColorIndex is equal to. I typically leave it set at xlAutomatic (solid color), and it could be set to something else if the color isn't changing.
According to XlColorIndex Enumeration ColorIndex=-4142 means No color
As to why this happens I'm clueless. The returned value seems to be the decimal representation of the RGB value. The improved version of this script to decrypt the value into hex RGB notation
Function RGB(CellRef As Variant)
RGB = ToHex(Range(CellRef).Interior.Color)
End Function
Function ToHex(ByVal N As Long) As String
strH = ""
For i = 1 To 6
d = N Mod 16
strH = Chr(48 + (d Mod 9) + 16 * (d \ 9)) & strH
N = N \ 16
Next i
strH2 = ""
strH2 = Right$(strH, 2) & Mid$(strH, 3, 2) & Left$(strH, 2)
ToHex = strH2
End Function
It doesn't appear that the "Conditional Format"-color is available programmatically. What I'd suggest that, instead, you write a small function that calculates cell color, and then just set a macro to run it on the active cell whenever you've edited the value. For example (sorry for the psuedo-code - I'm not a VBA expert anymore):
Function GetColorForThisCell(Optional WhatCell as String) as Int
If WhatCell="" Then WhatCell = ActiveCell
If Range(WhatCell).value = -1 then GetColorForThisCell = vbGreen
If Range(WhatCell).value = 0 then GetColorForThisCell = vbYellow
If Range(WhatCell).value = 1 then GetColorForThisCell = vbRed
End Function
Sub JustEditedCell
ActiveCell.color = GetColorForThisCell()
End Sub
Sub GetColorOfACell(WhatCell as string)
Msgbox(GetColorForThisCell(WhatCell) )
End Sub
Though you wouldn't be able to use the built-in Excel Conditional Formatting, this would accomplish the same thing, and you'd be able to read the color from code. does this make sense?
since i may have more than three different colors in a time... i didn't find any good way of handling this with conditional formatting's default colors... i did it this way. then whenever i ask the color of the cell, i retrieve the correct color!
for (int t = 0; t < d_distinct.Length; t++ )
{
Excel.FormatCondition cond =
(Excel.FormatCondition)range.FormatConditions.Add(
Excel.XlFormatConditionType.xlCellValue,
Excel.XlFormatConditionOperator.xlEqual,
"="+d_distinct[t],
mis, mis, mis, mis, mis);
cond.Interior.PatternColorIndex =
Excel.Constants.xlAutomatic;
cond.Interior.TintAndShade = 0;
cond.Interior.Color = ColorTranslator.ToWin32(c[t]);
cond.StopIfTrue = false;
}
d_distinct holds all the distinct values in a range... c is a Color[] which holds distinct colors for every distinct value! this code can easily be translated to vb!

Resources