Apply Conditional Formatting Expression with VBA - vba

I am trying to make a conditional format for cell rC. If the sum of absolute values in a range is different from zero, it should trigger the condition.
The Conditional Formatting Expression works in worksheet.
The actual content of sB is more complicated, but I get the same error when trying the simple code below.
( ; as I am on a Danish configuration):
sA = "ADDRESS(" & rC.Row & "+1;" & rC.Column & ";4)"
sB = "ADDRESS(" & rC.Row & "+2;" & rC.Column & ";4)"
rC.FormatConditions.Add Type:=xlExpression, _
Formula1:="=sum(abs(indirect(" & sA & ")" & ":" & "indirect(" & sB & ")))<>0"
It returns
Run-time error '5': Invalid procedure call or argument
Stepping into the code the formula returns
"=sum(abs(indirect(ADDRESS(4+1;8;4)):indirect(ADDRESS(4+2;8;4))))<>0", which works [returns false] when pasted into the spreadsheet.

Maybe it's possible to avoid both sA and sB completely, i.e.
rC.FormatConditions.Add Type:=xlExpression, Formula1:="=SUM(ABS(" & rc.Offset(1, 0).Address(False, False, xlA1) & ":" & rc.Offset(2, 0).Address(False, False, xlA1) & "))<>0"

Related

Excel VBA - insert formula in a set of rows with variable reference directly or replacing a string for example "\=" with "="

I have the goal to write a formula in a set of rows. Some references in the formula have to change each row.
I implemented the following script:
Dim i As Integer
Dim formcolM As String
Dim temprng As String
For i = 0 To 100
formcolM = "NUMBERVALUE(IF(Q" & i & "=""Bedarf kum."";A" & i & ";IF(Q" & i & "=""Ist"";OFFSET(A" & i & ";-1;0);IF(Q" & i & "=""Lz."";OFFSET(A" & i & ";-2;0);IF(Q" & i & "=""Ist+Lz.-Bedarf"";OFFSET(A" & i & ";-3;0);)))))"
Let temprng = "M" & i
Range(temprng).Select
ActiveCell.Value = "\=" & formcolM
next i
With this script I am writing a string each row in my excel table at column M.
I noticed that if the formula hasn't the symbol "\" , you can find an error .
In order to avoid the error I thought to leave the symbol "\" and to use a trick deleting it after (because I don't know how to solve with R1C1 formula. I read some answers on Stackoverflow, but unfortunately I did not understand )
The replacing script after the for cycle:
Columns("M:M").Replace What:="\=", Replacement:="=", LookAt:=xlPart
The strange thing is that the macro doesn't delete it.
Infact when the script finishes , it seems that nothing happened, without errors. But if I want substitute "\=" with another symbol, for example "*", the replacing script works.
I did not understand if the problem is :
the replace method did not recognized the symbol "=" to search
I cannot use the replace method because the symbol "=" disturbs in some way , I don't know in what.
OR, is there another simplest way to get this task done?
Someone could help me in order to fix? I should have the formula working in the column M , automatically with vba (not with another formula in the excel sheet) .
Thanks in advance for your time.
We can apply the formula directly. The issue is that vba is very US-EN Centric and all formula when using the .Formula needs to be in that format.
Also since your formula refers to values in a row 3 above the one in which it is put we need to start the loop at 4 not 0. There is no row 0
There are two ways, in US-En format with English functions and , as the deliminator using .Formula:
Dim i As Integer
For i = 4 To 100
Range("M" & i).Formula = "=NUMBERVALUE(IF(Q" & i & "=""Bedarf kum."",A" & i & ",IF(Q" & i & "=""Ist"",OFFSET(A" & i & ",-1,0),IF(Q" & i & "=""Lz."",OFFSET(A" & i & ",-2,0),IF(Q" & i & "=""Ist+Lz.-Bedarf"",OFFSET(A" & i & ",-3,0),)))))"
Next i
Or using .FormulaLocal and the formula as you would write it in your native tongue.
Dim i As Integer
For i = 4 To 100
Range("M" & i).FormulaLocal = "=NUMERO.VALORE(SE(Q" & i & "=""Bedarf kum."";A" & i & ";SE(Q" & i & "=""Ist"";SCARTO(A" & i & ";-1;0);SE(Q" & i & "=""Lz."";SCARTO(A" & i & ";-2;0);SE(Q" & i & "=""Ist+Lz.-Bedarf"";SCARTO(A" & i & ";-3;0);)))))"
Next i
By the time I got this worked out, Scott already had an answer. I just wanted to post your original code modified to work. I would suggest his method.
Sub TestScript()
Dim i As Integer
Dim formcolM As String
Dim temprng As String
For i = 4 To 100
formcolM = "NUMBERVALUE(IF(Q" & i & "=" & "Bedarf kum." & ";A" & i & ";IF(Q" & i & "=" & "Ist" & ";OFFSET(A" & i & ";-1;0);IF(Q" & i & "=" & "Lz." & ";OFFSET(A" & i & ";-2;0);IF(Q" & i & "=" & "Ist+Lz.-Bedarf" & ";OFFSET(A" & i & ";-3;0);)))))"
temprng = "M" & i
Sheets("Sheet1").Range(temprng).Select
ActiveCell.Value = " = " & formcolM
Next i
End Sub

Excel custom hyperlink for each cell in range using VBA

I have a module that removes all formulas from an entire sheet and then, it should, create a hyperlink formula on each cell using the cell value.
Sub Test()
Dim ws1 As Worksheet
Set ws1 = ThisWorkbook.Worksheets("Test")
ws1.Range("B33:F533").Value = ws1.Range("B33:F533").Value
For Each i In ws1.Range("B33:B533")
i.Formula = "=HYPERLINK(""https://somelocation/" & i.Value & """,""" & i.Value & """)"
Next
End Sub
EDIT: It's now working perfectly. Thanks For all the help!
i.Formula = "=HYPERLINK('https://somelocation/"&i.Value&","& i.Value"')"
Has an error in the formula. At the i.Value"') you are missing &, i.Value & "'. The correct one, that 'compiles', is added below:
i.Formula = "=HYPERLINK('https://somelocation/" & i.Value & "," & i.Value & "')"
Also it is worth noting that instead of writing "&i.Value&" and let the VBA IDE add the spaces, it is better to do it yourself, eg: " & i.Value & ".
You're code has 2 flaws, you should add the last & to get a syntax correct formula, and add spaces between the " and &, or else VBA won't see it is right.
Edit; a third flaw:
The line to create the formula is wrong too. Let's break it down:
"=HYPERLINK('https://somelocation/" & i.Value & "," & i.Value & "')"
The parameter in the formula would be:
'https://somelocation/" & i.Value & "," & i.Value & "' so an output example of this line could be 'https://somelocation/1,1'. At first, I thought you are writing an URL with a comma, alright..? But then I looked at the HYPERLINK function in Excel and it requires two parameters. You are only giving one parameter. Excel formulas also expect a double quote instead of a single quote. You can escape a double quote in VBA like this "".
The correct line should be:
i.Cells(1, 1).Formula = "=HYPERLINK(""https://somelocation/" & i.Value & """,""" & i.Value & """)"

VBA Set Cell value to text containing ' not working

I'm trying to get a macro to type out a heap of formulae for me. The formula goes something like this:
=COUNTIF('other_sheet'!A:A,"hello*")
The user can specify A and other_sheet, so I select the cell and then go
ActiveCell.Value = "=COUNTIF('" & othercell & "'!" & column & ":" & _
column & """,hello*"")"
But it keeps giving me errors like:
1004: Object Defined Error
I have tried using ActiveCell.Text, ActiveCell.Formula etc. and they all don't work.
It needs to be ActiveCell.Formula and ", is the wrong way around next to Hello. It should be:
ActiveCell.Formula= "=COUNTIF('" & othercell & "'!" & column _
& ":" & column & ",""hello*"")"
Apparently you can only put proper, completed answers into a cell.
i.e. if the output turns out to be "=sum(A:A" and a bracket isn't closed, then the application throws an error just as if you typed it in manually.

VBA SumProduct Runtime Error 13

As a part of a much longer code, I am trying to include a SumProduct
Dim SumPr as Variant
SumPr=Application.WorksheetFunction.SumProduct(((Workbooks(Source2).Sheets("Prices_EUR_Adj").Range("A:A")) = Range("A" & i)) * ((Workbooks(Source2).Sheets("Prices_EUR_Adj").Range("D:D")) = "PH") * (Workbooks(Source2).Sheets("Prices_EUR_Adj").Range(ColLtr & ":" & ColLtr)))
MsgBox SumPr
However, I keep getting Runtime Error 13 for some reason. Any idea what is wrong? Source2 is properly defined, and ColLtr is letter conversion of column number I got from match; it also works ok as checked by message box.
Try using the Evaluate function instead:
Dim SumPr As Variant
SumPr = Application.Evaluate("SUMPRODUCT(--(" & Workbooks(Source2).Sheets("Prices_EUR_Adj").Range("A:A").Address & "=" & Range("A" & i).Address & ")," & _
"--(" & Workbooks(Source2).Sheets("Prices_EUR_Adj").Range("D:D").Address & "=""PH"")," & _
Workbooks(Source2).Sheets("Prices_EUR_Adj").Range(ColLtr & ":" & ColLtr).Address & ")")
MsgBox SumPr
I'm sure the WorksheetFunction.SumProduct will also work, but I was able to get the Evaluate function working easier.

Using string variables within a formula in VBA

I do not understand why this code doesn't work:
Cells(i, formula_col_index).Value = "=IF(" & time_location & "<>" & time_benchmark & ",""ERROR"",""OK"")"
where
time_location=" 17:00:00",
time_benchmark=" 17:30:00"
It keeps throwing application-defined (or object-defined) error.
Thanks in advance.
Since your variables time_location and time_benchmark contains string values, you should include them in double quotes when using formula:
Cells(i, formula_col_index).Value = "=IF(""" & time_location & """<>""" & time_benchmark & """,""ERROR"",""OK"")"