Trying to add a Hyperlink Formula using VBA and a Variable - excel

I know how to add a formula to a worksheet that my macro is looping through
ThisWorkbook.Sheets("Sheet1").Range("A" & i).Formula = "=1+1"
and I know how to set up a Hyperlink Formula if I know the sheet name
=HYPERLINK("#Sheet2!A1","Sheet2")
but im having some trouble combining the two,
I have the Sheet name stored in a Variable (Sheet_Name) and im trying to set up the Hyperlink Formula to contain that (So instead of #Sheet2 I want it to use the Sheet_Name variable instead)
I cant seem to get the syntax to work

.Formula = "=HYPERLINK(""#'" & sheet_Name & "'!A1"",""" & sheet_Name & """)"
If you need double qutoes within the result string, you need to double them.
It's sometimes tricky to find out, what's the right number of quotes ...
Furthermore you should put single quotes around the sheetname variable - as you need them if there is e.g.
a space in the name ...

Related

VBA code is adding unwanted ' in my formula and returning wrong values [duplicate]

I am trying to write this formula using VBA:
ActiveCell.Value = "=f(R[-1]C[0],Sheet1!" & ColumnLetter & i & ")"
Where ColumnLetter is some variable letter which my macro computes earlier, and f is some function, and i is some number.
The problem is that when I run this, the cell is given this instead: (if ColumnLetter = F, i = 16):
=f(R[-1]C[0],Sheet1!'F16')
but I want:
=f(R[-1]C[0],Sheet1!F16)
Why is VBA or Excel putting those single quotation marks around F16? It does not insert these extra quotation marks if I do not include R[-1][0] as an argument in my formula, but I need to include this.
Help much appreciated!
Its the combination of R1C1 and A1 addressing. You need to pick one method and use it for both parts.
Note that if you type =f(R[-1]C[0],Sheet1!F16) into a cell you will get an error for the same reason.
You say you need to use R1C1 style for the first address, but (assuming this is because you don't want
absolute address) you can use .Offset instead
ActiveCell.Value = "=f(" & ActiveCell.Offset(-1, 0).Address(False, False) _
& ",Sheet1!" & ColumnLetter & i & ")"
The Apostrophe means to Excel that it should interpret it as text.
Write it to ActiveCell.Formula. That way it is recognized as Formula.

Use numbered column references in Excel Conditional Formatting code in VBA script

I have some VBA script that applies some conditional formatting in Excel.
Is there a way that I can reference the number values of the columns instead of the normal cell reference.
This is what I currently have:
"=AND(NOT(ISBLANK(F3)),F3<>""SomeValue1"",F3<>""SomeValue1"")"
And this is the sort of thing I would like to achieve:
"=AND(NOT(ISBLANK(Cells(3,6))),Cells(3,6)<>""SomeValue1"",Cells(3,6)<>""SomeValue2"")"
Replace("=AND(NOT(ISBLANK({addr})),{addr}<>""SomeValue1"",{addr}<>""SomeValue2"")", _
"{addr}", Cells(3,6).Address)
I was able to resolve my query using the following code to first convert the column number into a column letter:
ColLetter = Split(Cells(1, ColNumber).Address, "$")(1)
Once I had this conversion value I was able to use this variable in my code for conditional formatting:
"=AND(NOT(ISBLANK(" & ColLetter & "3))," & ColLetter & "3<>""SomeValue1""," & ColLetter & "3<>""SomeValue1"")"
Thanks to everyone whop responded.

Switch Worksheet Names without Updating References to those Sheets

My file has two identical Worksheets for users to input two different sets of assumption variables, called "InputA" and "InputB". I want to quickly switch which Input sheet is feeding into the other sheets of the model.
Using Find and Replace took over 5 minutes, and there were over 350,000 references to "InputA".
I tried the following macro, which takes an instant to run, but unfortunately also changes all references in the workbook, effectively keeping everything referenced to the original input sheet.
Sheets("InputA").Name = "temp"
Sheets("InputB").Name = "InputA"
Sheets("temp").Name = "InputB"
Is there a way to execute the macro but prevent any references to worksheets from changing to the new sheet name, basically freezing everything except the sheet name change? Or perhaps any other solution that will work quickly? I don't want to go through 350,000 instances and rewrite using INDIRECT(), as that is the only other solution I've seen, because my references are complex and nested and that will take an age.
Thanks.
Assuming that your 2 Input-Sheets have the same structure, I would suggest the following:
Create a named range on Workbook-level, name it for example InputData. This range should contain all data from InputA.
Create a helper-sheet and name it Input - you can later set it to hidden.
Mark the range in the new sheet that is exactly the size of the Input-Data-Range and enter the formula =InputData as Array-formula. You can do so by entering Ctrl+Shift+Enter. The formula should have curly brackets and the sheet should now display the data of InputA.
Change all you formulas to refer to the helper Sheet Input instead of InputA.
Create a macro:
Sub switchInput()
Const sheetAName = "InputA"
Const sheetBName = "InputB"
With ThisWorkbook.Names("inputData")
If InStr(.RefersTo, sheetAName) > 0 Then
.RefersTo = Replace(.RefersTo, sheetAName, sheetBName)
Else
.RefersTo = Replace(.RefersTo, sheetBName, sheetAName)
End If
End With
End Sub
This routine will just change the definition of the named range to point either to the first or second input sheet. As a consequence, the helper sheet will show the data of the selected Input-Sheet. All your formulas itself stays unchanged.
As stated in the comments, you could take the approach recommended by Damian and use a conditional in all relevant cells. The generic conditional would be
=IF(A1="InputA",FORMULA INPUTA,FORMULA INPUTB)
This formula makes A1 the cell that decides which input to pull. This will make changing the around 350.000 output formulas in your workbook the bottleneck, the following macro takes care of changing all the formulas to conatin the conditional:
Sub changeFormulas()
Dim rng As Range, cll As Range
Set rng = shOutput.Range("A2:C10") 'Your relevant worksheet and range here
Dim aStr As String, bStr As String, formulaStr As String
aStr = "InputA"
bStr = "InputB"
For Each cll In rng
If cll.HasFormula And InStr(1, cll.Formula, aStr, 1) Then
formulaStr = Right(cll.Formula, Len(cll.Formula) - 1)
cll.Formula = "=IF(A1=" & Chr(34) & aStr & Chr(34) & "," & formulaStr & "," & Replace(formulaStr, aStr, bStr) & ")" 'Change A1 to the reference most suited for your case
End If
Next cll
End Sub
This might take a bit of time, since it has to access all the relevant cells one by one, but it will only have to run once.
To explain: This macro will go through all the cells in your range rng specified at the top. If a cell has a formula in it and the formula contains "InputA" it will change that formula to fit the generic conditional (with the cells own formula of course). Chr(34) is the quotation mark ", I find using Chr(34) more readable than multiple quotation marks """, but that is just preference.

Syntax for formula =SUM(range(cells(41,10),cells(49,10)))

The "formula" =SUM(range(cells(41,10), cells(49,10))) returns "#NAME"?
I need to create the formula with quotation and & and place it in certain cells.
Also the values in the Cells() function are variables in the code.
The example is a result of one placement of the formula at a particular cell. I've tried a : also to separate the cells(), also tried not using Range().
with Worksheets("Sheet1")
.Range("A1").Formula = "=SUM(" & .range(.cells(41,10),.cells(49,10)).Address & ")"
End with

Using a set variable in a Vlookup

I'm trying to use the following formula in a cell where Name is a defined cell. When I run 'MsgBox Name.Address' it gives me the correct cell, but when I run the formula I get
run-time error '1004'
Worksheets("E'ee Details").Range("N1").FormulaR1C1 = "=VLOOKUP(" & Name.Address & ",EmployeeBank!C[-13]:C[-10],4,FALSE)"
The code also correctly places in the value of the variable if I remove .address
Worksheets("E'ee Details").Range("N1").FormulaR1C1 = "=VLOOKUP(" & Name & ",EmployeeBank!C[-13]:C[-10],4,FALSE)"
This gives me =VLOOKUP(J Bob,EmployeeBank!A:D,4,FALSE) in the cell. This would work but I can't put quotation marks around the name as these are already in place in the vba code. I tried doing multiple quotation marks and also char(34) but couldn't get it to work.
You need to use an additional double quotation.
Sorted it, I was putting in the wrong number of quotation marks!!!!
Worksheets("EeeDetails").Range("N1").FormulaR1C1 = "=vlookup(""" & NewName & """,EmployeeBank!C[-13]:C[-10],4,FALSE)"

Resources