Is there a Cells().Formula function? - vba

my script compiled fine so I assumed it was ok but couldn't find it and of course it error's out on this line, this is encapsolated in a while loop, I'm just trying to have a simple way to add a formula to a row of data, then do something similar to add it to a row of data. Is there no .Formula or do I have another error?
Cells(arow, acol).Formula = "=COUNTIF(" & wsData.Name & "!" & Cells(fdRow, acol).Address & ":" & Cells(ldRow, acol) & ")"
acol = acol + 1

Just a few little changes needed:
You're missing a .Address on Cells(ldRow, acol)
I also included apostrophes ' around the worksheet name (only necessary if the name has spaces in it).
As #Wayne G. Dunn also pointed out you need the second parameter of the COUNTIF function, which I have put at the end as 1. You'll need to update that.
Here is the updated code:
Cells(arow, acol).Formula = "=COUNTIF('" & wsData.Name & "'!" & Cells(fdRow, acol).Address & ":" & Cells(ldRow, acol).Address & ",1)"

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

VBA -- variable in .formula

is there a more elegant (simpler) way to put a variable in .formula? I don't want to use .formulaR1C1
I have this code:
Range("C8").Select
Selection.End(xlDown).Select
PosR = ActiveCell.Row
KonR = PosR - 2
Range("N" & PosR).Select
aAddress = Range("$N$9").Address & ":" & Range("$N$" & KonR).Address
ActiveCell.Formula = "=SUM(" & aAddress & ")"
Obviously I want to put =SUM($N$9:$N$101) (101 is the last cell minus 2) into that cell and this code does the job. But I just want to be sure that this is the easiest way to do this.
The easiest way is to skip all that selecting and those variables
PosR = Range("C8").End(xlDown).Row
Range("N" & PosR).Formula = "=SUM($N$9:$N$" & PosR - 2 & ")"
Edit: to be more explicit, the easiest way is to use FormulaR1C1 but you said you didn't want to, so...
You can use the code below (without using Select and ActiveCell:
PosR = Range("C8").End(xlDown).Row
KonR = PosR - 2
Range("N" & PosR).Formula = "=SUM(" & Range("$N$9").Address & ":" & Range("$N$" & KonR).Address & ")"
Or, the much simplier version:
Range("N" & PosR).Formula = "=SUM($N$9:$N$" & KonR & ")"
Well you should be trying to avoid using Select in VBA. You've made the actual inclusion of a variable in the .Formula about a simple as it gets, but your whole code could be simplified:
PosR = Range("C8").End(xlDown).Row
Range("N" & PosR).Formula = "=SUM($N$9:$N$" & PosR - 2 & ")"
Really you should be fully qualifying your ranges too, like so
With ThisWorkbook.Sheets("Sheet1")
PosR = .Range("C8").End(xlDown).Row
.Range("N" & PosR).Formula = "=SUM($N$9:$N$" & PosR - 2 & ")"
End With
And if you have blank cells in column C then your use of xlDown will fail to find the last cell. You may want to look at ways of finding the last cell in VBA or simply use
' Again, preferably fully qualified
Range("C" & Rows.Count).End(xlUp).Row
Range("$N$9").Address gives exactly "$N$9".
Range("N9").Address gives the same. Thus, it is a bit overwork. Check out the first two debug.print in the sample below.
Thus, once you calculate the last row and assign value to it lngLast, it is possible to get the formula like this:
"=SUM(N9:N" & lngLast & ")"
Option Explicit
Public Sub TestMe()
Dim strA As String
Dim lngLast As Long
strA = Range("$N$9").Address
Debug.Print strA = "$N$9"
strA = Range("N9").Address
Debug.Print strA = "$N$9"
lngLast = Range("N" & Rows.Count).End(xlUp).Row - 2
ActiveCell.Formula = "=SUM(N9:N" & lngLast & ")"
End Sub
Good morning, everyone :)

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 Offset within Vlookup?

I'm trying to get a Vlookup for a row which is just left of the Lookup_value. I can't do a Table_array of "-1" (or -2) so I'm wondering if I can do an Offset(0, -1) within that line of code.
The line in question:
wCell.FormulaR1C1 = "=VLOOKUP(RC[1],'[" & filename & "]" & ws.Name & "'!R8C4:R" & lastrow & "C5,-1,FALSE)"
The entire code block:
Range("$C$8:$C$" & lastrow).Select
For Each wCell In Range("$C$8:$C$" & lastrow)
wCell.Select
If wCell.FormulaR1C1 = "" Then
wCell.FormulaR1C1 = "=VLOOKUP(RC[1],'[" & filename & "]" & ws.Name & "'!R8C4:R" & lastrow & "C5,-1,FALSE)"
End If
Next
If you were looking to find information to the left of the reference point in excel, using a Match-Index lookup would be they way for you to go. Not only is this method able to look to the left or right of your reference, but it is also a faster process.
VLookup looks like this:
=VLookup([Value to find],[Where to find the value],[Column to return],[range lookup])
Where as using Match-Index looks like this:
=Index([Range to look in for return],Match([Value to find],[Range to look in for value],[Exact match or partial]))
So, while a bit more complicated to write, using the second method really increases the flexibility of what you can look up and where that information is.
Now, if you were to apply this method to your code, it should look something like this:
wCell.FormulaR1C1 = "=Index([Range of Value to Find],Match(RC[1],'[" & filename & "]" & ws.Name & "'!R8C4:R" & lastrow & "C5, [0 for exact match]))"
(Just change out the bits I added in brackets for the information that they need, and that should address that problem your are running into)

Excel VBA hlookup function

I am trying to use the excel VBA HLookup function. I have tried it two ways and both produce error. Could anyone explain me what is that I am doing wrong?
First try:
lookupValue = Worksheets(1).Name & "!A1"
tableArray = Worksheets(3).Name & "!$A$1:$" & Col_letter & "$1"
Worksheets("Comparison").Cells(1, 2).Value = "=HLookup(" & lookupValue _
& ";" & tableArray & ";1;FALSE)"
Second try:
tda = Worksheets(1).Cells(1, 1).Value ' I also tried using tda without .Value
Table = Worksheets(3).Range(Cells(1, 1))
Worksheets("Comparison").Cells(1, 2).Value = WorksheetFunction. _
HLookup(tda, Table, 1, False)
For your first one, you need to use US regional settings, so a comma separator, and you should really enclose the sheet names in single quotes in case they contain spaces or look like special names (e.g. dates):
lookupValue = "'" & Worksheets(1).Name & "'!A1"
tableArray = "'" & Worksheets(3).Name & "'!$A$1:$" & Col_letter & "$1"
Worksheets("Comparison").Cells(1, 2).Formula = "=HLookup(" & lookupValue _
& "," & tableArray & ",1,FALSE)"
and for the second you have to use a range object for the table argument:
tda = Worksheets(1).Cells(1, 1).Value ' I also tried using tda without .Value
Set Table = Worksheets(3).Range(Worksheets(3).Cells(1, 1), Worksheets(3).Cells(1, Col_letter))
Worksheets("Comparison").Cells(1, 2).Value = WorksheetFunction. _
HLookup(tda, Table, 1, False)
I have assumed Table is declared as Variant, Object or Range.
Note you will still get a run-time error if there is no match for your lookup value.
what you're doing there usually works, which is creating a string with the function you want to call and inputting it.
I don't think that's the safest way, since it would not work if you run that macro from an Excel with a different language.
the proper way to call an Excel function from VBA call is for example:
cells(1,2) = Application.WorksheetFunction.VLookup(123,Range("A1:C100"),3,FALSE)
anyway if you'd rather use this string approach the problem in the first try is that
"=HLookup(" & lookupValue _
& ";" & tableArray & ";1;FALSE)"
results in the string:
=HLookup(Sheet1!A1;Sheet3!$A$1:$B$1;1;FALSE)
note that you're using semicolons where you're supposed to use commmas.
the problem in the second try is that the .Range property takes a string as input, so you cant Range(Cells(1,1)) you should do something like .Range("A1:A3")
hope it helps !