Excel VBA Conditional Formatting AND-Function - vba

UPDATE:
I try to use conditional formatting for the following case:
If a cell in column C (starting with C9) Tabelle3.Range(Tabelle3.Cells(9, 3), Tabelle3.Cells(lastcell, 3))
is not empty Cell <>""
AND
fullfills a criteria which is stated in Tabelle4 Cell B2 Tabelle4.Range("B2")
its Interior.Color should be changed to Cellclr and its Font.Color to Fontclr
Start Old Post:
I looked through various posts about conditional formatting but I couldn't find any, that is preciously solving my problem.
I want to apply conditional formatting to a Excel workbook which will be constantly extanded. Therefore, I wrote the following code:
Sub ConForm()
Dim lastcell As Long
Dim Cellclr As Long
Dim Fontclr As Long
lastcell = Tabelle3.Range("A1048576").End(xlUp).Row
Cellclr = RGB(232, 245, 246)
Fontclr = RGB(26, 155, 167)
Set C = Tabelle3.Range(Tabelle3.Cells(9, 3), Tabelle3.Cells(lastcell, 3))
With C.FormatConditions.Add( _
Type:=xlExpression, _
Formula1:="=AND($C9<>"""";"$C9.Value <= Tabelle4.Range(""B2"").Value)")
.Interior.Color = Cellclr
.Font.Color = Fontclr
End With
End Sub
If I just use the following range and formula:
Range("C9")
Formula1:="=C9<>""""")
the code works out for Cell C9. However, as already mentioned, it should be this Formula
=AND($C9<>"""";"$C9.Value <= Tabelle4.Range(""B2"").Value
be applied for the range
Tabelle3.Range(Tabelle3.Cells(9, 3), Tabelle3.Cells(lastcell, 3))
Does someone know where I made a mistake/mistakes and how to solve this issue?

First, check the colours on your formatting to see what's a string and what's not - you have a mysterious extra " in the middle of your formula, which will prevent the code from compiling in the first place. You have also tried to put VBA code (Tabelle4.Range("B2").Value) into an Excel formula, which won't work.
If you want to fix the value of Tabelle4.Range("B2").Value when the macro is run, you can change
Formula1:="=AND($C9<>"""";"$C9.Value <= Tabelle4.Range(""B2"").Value)")
to
Formula1:="=AND($C9<>"""";$C9<=" & Tabelle4.Range("B2").Value & ")")

You need to concatenate the strings and values correctly.
Example:
MyVariable = "ccc"
result = "aaa" & "bbb" & MyVariable & "AnotherString"
'result is "aaabbbcccAnotherString"
I'm not sure what you tried but probably you meant something like
Formula1:="=AND($C9<>"""";" & Range("$C9").Value <= Tabelle4.Range("B2").Value & ")")
Or more likely something like
Formula1:="=AND($C9<>"""";$C9<=Tabelle4!B2)")
Update:
Formula1:="=AND($C9<>"""";$C9<=" & Tabelle4.Range("B2").Value & ")")

Related

Excel VBA - if/then statement - Identifying cells with a dash

I am trying to write a VBA line where if cell A1 contains a dash anywhere in the cell, then B1 will say "Blue". If there is no dash, then B1 would say "Red".
I have the following code written, but it's not working and I'm not sure if I'm doing the "like" part correctly:
ActiveCell.FormulaR1C1 = _
"=IF(RC[-1]=" - ",""Blue"",""Red"")"
Thank you for any help you can provide! I've done so much searching, but have been unable to find any examples that didn't include specific numbers or text.
You can also use
ActiveCell.FormulaR1C1 = "=IF(ISNUMBER(FIND(""-"",RC[-1])),""Blue"",""Red"")"
Or a one-liner:
ActiveCell.FormulaR1C1 = "=IF(ISERROR(FIND(""-"",RC[-1])),""Red"",""Blue"")"
You could do it with a simple VBA script like this:
Sub Test()
Dim sh1 As Worksheet
Set sh1 = Sheets("Sheet1")
Application.ScreenUpdating = False
For x = 1 To sh1.Cells(rows.Count, "A").End(xlUp).Row
If InStr(1, sh1.Range("A" & x).Value, UCase("-"), 1) > 0 Then sh1.Range("B" & x).Value= "Red"
If InStr(1, sh1.Range("A" & x).Value, UCase("-"), 1) < 0 Then sh1.Range("B" & x).Value = "Blue"
Next x
Application.ScreenUpdating = True
End Sub
I don't believe that put a formula in every "B" column cells it's a good pratice, Excel can take a long time to calculate.
Try this:
Sub Example()
mySheet.Cells(1, "B").Value = IIf(Not InStr(1, mySheet.Cells(1, "A"), Chr(45), vbTextCompare) = 0, "Blue", "Red")
End Sub
You can loop through every cell you want to put that condition using this code.
Functions:
IIf is equals to Excel Worksheet Function "IF".
InStr search a string in another string, you can pass a unique char as criterea. I used chr(45) because it returns a char according to the passed code, 45 references to Dash code.
The error, corrected (but not pointed out) in several of the other answers lies in changing your formula from
" - "
to
"" - ""
i.e. going from single double-quotes around your - to double double-quotes. The single quote is ending your string - you can even see that the - shows up in black text in your question instead of red text, therefore, it's not part of the string being inserted into ActiveCell.FormulaR1C1.

vlookup with dynamic lookup_value using VBA?

I'm new to using the dynamic lookup value, I tried following the piece of advice from How to perform an excel vlookup with dynamic lookup_value using VBA? to fetch a value dynamically from another workbook.
This below code throws #Name? error.
Request your help to resolve the error.
Code Excerpt:
Dim ws As Worksheet
Dim dynamic_lookup_value As Range
Dim LocationRef As Range
Set ws = ActiveWorkbook.Worksheets("XYZ")
Set dynamic_lookup_value = ws.Cells(2, 1)
ActiveWorkbook.Names.Add Name:="dynamic_lookup_value", RefersTo:=Worksheets("XYZ").Cells(2, 1)
Set LocationRef = ws.Cells(2, ActiveColumn)
ActiveCell.FormulaR1C1 = _
"=IFERROR(VLOOKUP(" & dynamic_lookup_value.Address(0, 0) & ",'[ABC.xlsx]XYZ'!C1:C26,MATCH(""Location Description"",'[ABC.xlsx]XYZ'!R1C1:R1C26,0),)," & LocationRef.Address(0, 0) & ")"
After execution, the formula appears as
=IFERROR(VLOOKUP('A2','[HC report.xlsx]HC Report'!$A:$Z,MATCH("Location Description",'[HC report.xlsx]HC Report'!$A$1:$Z$1,0),),'G2')
Please note lookup value appears 'A2'(with single codes). Tried to declare the dynamic_lookup_value using the following piece of code but in vain.
ActiveWorkbook.Names.Add Name:="dynamic_lookup_value", RefersTo:=Worksheets("XYZ").Cells(2, 1)
If I manually remove the Singe code before and after the A2 and G2, then the formula works fine.
Request the experts advise to resolve this issue.
Many thanks,
Prabhu
New Answer:
Having been able to replicate you error, I think I have a solution: Replace your ActiveCell.FormulaR1C1 with ActiveCell.Formula. This solved it in my simple re-creation of the problem (using the immediate-window)
This works (sets a reference to cell A1 in cell A2, based on address of Cell A1:
Cells(2,2).Formula = "="&Cells(1,1).Address(0,0)
While this doesn't work (gives same issue with 'A1' in single quotes as you had): Cells(2,2).FormulaR1C1 = "="&Cells(1,1).Address(0,0)
I think there may be some confusion between named ranges and range variables in VBA. However, one problem in your formula is an inconsistent application or RC notation so you need
ActiveCell.FormulaR1C1 = _
"=IFERROR(VLOOKUP(" & dynamic_lookup_value.Address(0, 0, xlR1C1) & ",XYZ!C1:C26,MATCH(""Location Description"",XYZ!R1C1:R1C26,0),)," & LocationRef.Address(0, 0, xlR1C1) & ")"

Another >> Unable to set the FormulaArray property of the range class

I've researched as many of the "Unable to set the FormulaArray property of the range class" issues here and in other sites to troubleshoot a FormulaArray operation I'm trying to carry out in a table of data.
I've respected the 255 character limit in my formula taking into account R1C1, I've tried to insert the formula as a text string first. I've tried quite a few things.
Now I'm thinking my issue is with the fact that I'm trying to insert my formula only into blank cells because if I simplify my formula to only be =1+1 I still get the error. If I change .FormulaArray to .Formula to simply enter a standard formula I also get the same error. Is this operation not possible with blank cells?
The error occurs at the .FormulaArray = myFormula1 step.
To confirm, the formula by itself works (pasted further below) when entered into cells manually.
Sub ArrayMacro()
Dim myFormula1 As String
Dim myFormula2 As String
Dim myFormula3 As String
Dim myFormula4 As String
myFormula1 = "=IF(COUNTIFS(MLBtransactions!$D:$D,A$1,MLBtransactions!$A:$A,""<=""&$C2)>0,IF(INDEX(MLB," & "X_X_X)"
myFormula2 = "transactions!$A:$E,MATCH(1,(MLBtransactions!$D:$D=A$1)*(MLBtransactions!$A:$A<=$C2),0),," & "Y_Y_Y)"
myFormula3 = "5)=$A2,""DNP/SUS/MIN"",""with "" & INDEX(MLBtransactions!$A:$E,MATCH(A$1,MLBtransactions," & "Z_Z_Z)"
myFormula4 = "!$D:$D,0),5)),IF(COUNTIFS(MLBstats!$B:$B,A$1,MLBstats!$A:$A,$A2)=1,""DNP/SUS/MIN"",""LEAVE BLANK""))"
Sheets("Sheet1").Select
With Range("E2:AZ140").SpecialCells(4)
.FormulaArray = myFormula1
.Replace ",X_X_X)", myFormula2
.Replace ",Y_Y_Y)", myFormula3
.Replace ",Z_Z_Z)", myFormula4
End With
End Sub
Question update. Using With Range("E2:AZ140").SpecialCells(xlCellTypeBlanks) instead of With Range("E2:AZ140").SpecialCells(4) also ends with the same error.
Here is the full formula being used
=IF(COUNTIFS(MLBtransactions!$D:$D,A$1,MLBtransactions!$A:$A,"<="&$C2)>0,IF(INDEX(MLBtransactions!$A:$E,MATCH(1,(MLBtransactions!$D:$D=A$1)*(MLBtransactions!$A:$A<=$C2),0),5)=$A2,"DNP/SUS/MIN","with " & INDEX(MLBtransactions!$A:$E,MATCH(A$1,MLBtransactions!$D:$D,0),5)),IF(COUNTIFS(MLBstats!$B:$B,A$1,MLBstats!$A:$A,$A2)=1,"DNP/SUS/MIN","LEAVE BLANK"))
Testing with a simplified code (example below) led to the realization as YowE3K points out that myFormula1 needs to be valid in order for the procedure to work.
Sub ArrayMacro()
Dim myFormula1 As String
Dim myFormula2 As String
myFormula1 = "=1+1" & "+2+2"
myFormula2 = "+1+1"
Sheets("Sheet1").Select
With Range("h14:h16").SpecialCells(xlCellTypeBlanks)
MsgBox .Address
.FormulaArray = myFormula1
.Replace "+2+2)", myFormula2
End With
End Sub
When you set a formula using FormulaArray = ..., it needs to be a valid formula. (I think after each Replace the formula needs to continue being valid too, but I haven't tested that. Edit: No, if the Replace would create an invalid formula, it just doesn't process it - but it doesn't crash.)
Your problems all seem to stem from the use of invalid formulas in your myFormula1 variable.
I suggest you use the following:
Sub ArrayMacro()
Dim myFormula1 As String
Dim myFormula2 As String
Dim myFormula3 As String
Dim myFormula4 As String
myFormula1 = "=IF(COUNTIFS(MLBtransactions!$D:$D,A$1,MLBtransactions!$A:$A,""<=""&$C2)>0,IF(1232=$A2,""DNP/SUS/MIN"",""with ""&1233),1234)"
myFormula2 = "INDEX(MLBtransactions!$A:$E,MATCH(1,(MLBtransactions!$D:$D=A$1)*(MLBtransactions!$A:$A<=$C2),0),5)"
myFormula3 = "INDEX(MLBtransactions!$A:$E,MATCH(A$1,MLBtransactions!$D:$D,0),5)"
myFormula4 = "IF(COUNTIFS(MLBstats!$B:$B,A$1,MLBstats!$A:$A,$A2)=1,""DNP/SUS/MIN"",""LEAVE BLANK"")"
'Insert the formula
With Sheets("Sheet1").Range("E2:AZ140").SpecialCells(xlCellTypeBlanks)
.FormulaArray = myFormula1
.Replace "1232", myFormula2
.Replace "1233", myFormula3
.Replace "1234", myFormula4
End With
End Sub
Setting .FormulaArray to a range of cells in VBA is the same as pressing CTRL+SHIFT+ENTER while the entire range is selected. This is used when a single formula is returning an array of results and you want to display that array in the range of selected cells. This requires a contiguous range of cells to display the array. Trying to set .FormulaArray on a non-contiguous range of cells will fail, regardless of whether the formula is good or not.
I think you're trying to create an Array Formula that returns a single result after performing analysis on arrays; and you want this formula used in all blank cells.
In Excel, you would need to array-enter the formula into a single cell and then copy the formula into other cells.
Similarly, you need to do it in 2 steps in VBA. You need to first set the .FormulaArray for just one cell. This will also confirm that the formula is being constructed correctly in VBA. You can then copy that cell to all blank cells, using PasteSpecial if you only want to copy the formula.
Alternatively, you could loop through all blank cells setting the .FormulaArray individually, e.g.:
Dim raCell As Range
For Each raCell In Range("E2:AZ140")
If IsEmpty(raCell) Then raCell.FormulaArray = ...
Next
However, as you have dynamic references, you would need to construct the FormulaArray carefully to correctly determine the formula required based on the .Row and .Column of the current raCell.
Copy and paste would be safer if you have an "achor" point. Somewhere you know you can always enter the exact same formula and get the correct result when copied and pasted to all other cells.

Using variable columns in VBA Excel

While working on a macro in VBA I can't figure out the following issue:
This is a part of the code
ActiveCell.FormulaR1C1 = _
"=SUM(CreateResultsDebit!C[34])-DebitAnalysis!RC[-1]"
Range("B3").Select
ActiveCell.FormulaR1C1 = _
"=SUM(CreateResultsDebit!C[35])-DebitAnalysis!RC[-1]"
Range("B4").Select
Now, I have hardcoded the column reference C[34] and C[35]. Is there a way to use, for instance, an iterator as a variable between the brackets? If I try this myself it doesn't yield any result.
Thank you. Peter.
ok... you need to combine a variable and a string... it is like:
ActiveCell.FormulaR1C1 = "=SUM(CreateResultsDebit!C[" & i & "])-DebitAnalysis!RC[-1]"
to be a bit more specific: (in your code, you set the formula first and then select another cell... I assume that you want the C[34] in B2 and C[35] in B3......)
Dim i As Long
For i = 2 to 3
Range("B" & i).FormulaR1C1 = "=SUM(CreateResultsDebit!C[" & 32 + i & "])-DebitAnalysis!RC[-1]"
Next
In the first cycle (i = 2) it will go for cell B2 and use C[34] (32 + i). In the second cycle, those two values are 1 higher (if you go for i from 2 to 30, then it will go for cell B30 in last cycle and use C[62] in your formula)
EDIT
Another easy way is the use of R1C1 to set multiple cells. For this you would need to change your formula a bit and the code would look like this:
Range("B2:B9").FormulaR1C1 = "=SUM(INDEX(CreateResultsDebit!C[33]:C[51],,ROW()))-CreateResultsDebit!RC[-1]"
This would do the same without any loops ;)
Maybe this will be of help to you, if I understand you correctly. It will sum the columns from left to right and place them in one row consecutively.
Dim i as Integer
Dim iLastColumn as Long
Dim startRange as Range
Set startRange = Range("B3")
iLastColumn = Cells(1,Columns.Count).End(xlToLeft).Column
For i = 1 To iLastColumn
startRange.Offset(1,i).FormulaR1C1 = "=SUM(CreateResultsDebit!C[" & i & "])-DebitAnalysis!RC[-1]"
Next i

Named range in conditional formatting formula

I have code like below. And I would like to set named ranges (cells) instead of ranges (cells) H$7 and $G$7. Because if for example I add new column before these cells and recover macro with this code it does not work correctly. Have you got any idea? Thanks in advance
With Range(SomeRange).FormatConditions _
.Add(xlExpression, xlFormula, "=((H$7<=$G$7)*((H$7+7)>$G$7))")
With .Interior
.Color = RGB(197, 217, 241)
End With
End With
Just type the name of a named range in the formula, nothing special as long as the named range exists. If I name H7 "B" and G7 "A" then this works for me...
Sub Test()
'Range
Dim R As Range
Set R = Range("A1")
R.FormatConditions.Delete
'Formula
Dim F As String
F = "=((B<=A)*((B+7)>A))"
'Condition
Dim Cond As FormatCondition
Set Cond = R.FormatConditions.Add(xlExpression, xlFormula, F)
Cond.Interior
Cond.Color = RGB(197, 217, 241)
End Sub
Note though, with the formula argument of 'FormatConditions.Add', everything within the double quotes gets evaluated exactly as if typed within a cell. The argument is passed as a string and interpreted as a literal string value. So you can test your formula string by copying and pasting it to a cell and it should work the same (return 1 or 0), modify it in the cell, and copy and past back.
You don't have to create/set the names problematically, but if you want to, then I'd probably use the workbooks collection unless you repeat the same name on multiple sheets, then use the worksheet collection.
About named ranges...
The Object (Name)
The Collection (Names)
Setting Referencing
Try getting the address of the named ranges and concatenating them in your formula string.
Eg.
Adr1= range("namedrange1"). Address
Adr2= range("namedrange2"). Address
With Range(SomeRange).FormatConditions _
.Add(xlExpression, xlFormula, "=((" & adr1 & "<=" & ad2 & ")*((" & adr1 & "+7)>" & adr2 & "))")