Excel custom hyperlink for each cell in range using VBA - 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 & """)"

Related

Linking cells to different worksheet by using vba to insert dynamic formulas

I am creating a new worksheet called varRef and am trying to link cells of an existing worksheet to this new worksheet by using VBA. I have been trying to solve it for a couple of hours but cannot get it right and cannot find a similar case on the web either.
The code is:
Dim varRef as Variant 'name of the new sheet
varRef = Inputbox("xyz") 'this is how I define the name
Dim intRow As Integer 'row that corresponds to the appropriate postion in the existing sheet
intRow = ActiveCell.Row 'see above
Cells(intRow, 22).Formula = "=IF(varRef & ""!I148""="""","""",varRef & _
""!I148"")" 'trying to link the contents within the same workbook
The result in the cell I get is
=IF(varRef & "!I148"="","",varRef & "!I148"
which is obviously not working.
Issue 1) is that VBA does not recognize my variable in the formula. It is working for naming the sheet however.
Issue 2) is the quotation marks, that are not working as intended. One is supposed to use double quotation marks to not end the string. However the second marks will not disappear in the final code of the cell.
Any help is very much appreciated and hopefully valuable for other users as well!
You had some count issues with hoe many " you have before and after the varRef variable.
Also, I prefer to use Chr(34) to have " inside the Formula string, this way I don't get confused with how many " I need to use.
Try the code below:
Cells(intRow, 22).Formula = "=IF(" & varRef & "!I148=" & Chr(34) & Chr(34) & "," _
& Chr(34) & Chr(34) & "," & varRef & "!I148)"

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

Is there a Cells().Formula function?

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)"

Using VBA to create a formula that changes based on checkboxes ticked

I am trying to create a function where if a number of checkboxes are ticked in a userform, then the formula in cell A1 shows a different formula with a Choose function.
The formula that I want to appear if all boxes are selected is:
=choose(randbetween(1,4),A3,A4,A5,A6)
If only certain boxes are selected e.g. boxes 1 and 3 are selected then the formula would be:
=choose(randbetween(1,4),A3,B1,A5,B1)
Where B1 is a reference to a blank cell.
The next formula would be dependent on the value of this cell.
Currently the approach I am taking is to do:
Dim a as range, b as range, c as range, d as range,
'set cell reference with data in if checkbox is selected, blank cell reference if checkbox not selected
If checkbox1.value=TRUE then
set a = range("A3")
else
set a = range("B1")
end if
'this is repeated for all checkboxes
Next I want to have it so the formula in A1 is
=choose(randbetween(1,4),a,b,c,d)
where a,b,c,d are the range that I have determined in the IF functions. This is where I am stuck. If I do
[A1]="=choose(randbetween(1,4),a,b,c,d)"
Then the formula doesn't pick up on the values
If I do:
Dim LValue As String
LValue = Choose(Application.RandBetween(1, 4), a, b, c, d)
[A1] = LValue
Then all that is returned is the value rather A1 having a formula within.
Any ideas?
Update:
Thank you for your suggestions. Inspiration struck after responding to your answers and the formula I needed was:
[A1] = "=choose(randbetween(1,4), " & a & "," & b & "," & c & "," & d & ")"
Which displays the formula in the cell with the variables changing. The variables had to be a string rather than a range too.
First, you need to delete the comma after d as range,.
Then you need to add double quotations around the text you paste into the formula.
[a1].Formula = "=choose(randbetween(1,4)," & Chr(34) & a & Chr(34) & "," & Chr(34) & b & Chr(34) & "," & Chr(34) & c & Chr(34) & "," & Chr(34) & d & Chr(34) & ")"
Thank you for your suggestions. Inspiration struck after responding to your answers and the formula I needed was:
[A1] = "=choose(randbetween(1,4), " & a & "," & b & "," & c & "," & d & ")"
Which displays the formula in the cell with the variables changing. The variables had to be a string rather than a range too.

Excel vba error name in formula

I'm trying to pass one formula from vba excel to a cell i have this code
atmFecha = "=IF(L" & tmLastRow & "=0," & Chr(34) & " " & Chr(34) & ",'ws2'!$E$3)"
.Cells(tmLastRow, "H").Value = atmFecha
this instruction insert in the cell the correct formula but display #NAME? I have to press "F2" and then "Enter" to Excel recognize the formula and display the correct value.
I use the instructions formula and formulaR1C1 but the result is the same.
what can i do to recognize automaticly the correct value of the formula ?
After your code, add this line:
Application.Calculate
It sounds like you are set to Manual Calculation, so that line will refresh everything. If you're setting a number of formulas, wait until they're all inserted, then execute that line.
I don't know how it fix but now is working, I was testing with the second file I made this is the code"
Sub btnCalculate()
Dim atmFecha As String
Dim tmLastRow As Integer
With Worksheets("ws1")
tmLastRow = 1
atmFecha = "=IF(C1=0," & Chr(34) & " " & Chr(34) & ",'ws2'!$A$1)"
.Cells(tmLastRow, "A").Value = atmFecha
End With
End Sub