VBA setting the formula for a cell - excel

I'm trying to set the formula for a cell using a (dynamically created) sheet name and a fixed cell address. I'm using the following line but can't seem to get it working:
"=" & strProjectName & "!" & Cells(2, 7).Address
Any advice on why this isn't working or a prod in the right direction would be greatly appreciated.

Not sure what isn't working in your case, but the following code will put a formula into cell A1 that will retrieve the value in the cell G2.
strProjectName = "Sheet1"
Cells(1, 1).Formula = "=" & strProjectName & "!" & Cells(2, 7).Address
The workbook and worksheet that strProjectName references must exist at the time that this formula is placed. Excel will immediately try to evaluate the formula. You might be able to stop that from happening by turning off automatic recalculation until the workbook does exist.

Try:
.Formula = "='" & strProjectName & "'!" & Cells(2, 7).Address
If your worksheet name (strProjectName) has spaces, you need to include the single quotes in the formula string.
If this does not resolve it, please provide more information about the specific error or failure.
Update
In comments you indicate you're replacing spaces with underscores. Perhaps you are doing something like:
strProjectName = Replace(strProjectName," ", "_")
But if you're not also pushing that change to the Worksheet.Name property, you can expect these to happen:
The file browse dialog appears
The formula returns #REF error
The reason for both is that you are passing a reference to a worksheet that doesn't exist, which is why you get the #REF error. The file dialog is an attempt to let you correct that reference, by pointing to a file wherein that sheet name does exist. When you cancel out, the #REF error is expected.
So you need to do:
Worksheets(strProjectName).Name = Replace(strProjectName," ", "_")
strProjectName = Replace(strProjectName," ", "_")
Then, your formula should work.

If Cells(1, 1).Formula gives a 1004 error, like in my case, changes it to:
Cells(1, 1).FormulaLocal

If you want to make address directly, the worksheet must exist.
Turning off automatic recalculation want help you :)
But... you can get value indirectly...
.FormulaR1C1 = "=INDIRECT(ADDRESS(2,7,1,0,""" & strProjectName & """),FALSE)"
At the time formula is inserted it will return #REF error, because strProjectName sheet does not exist.
But after this worksheet appear Excel will calculate formula again and proper value will be shown.
Disadvantage: there will be no tracking, so if you move the cell or change worksheet name, the formula will not adjust to the changes as in the direct addressing.

Related

VBA to put SUMIFS in a cell

I wrote code to put SUMIFs in a cell based on sheet name. newFileName and oldFileName are declared variables used as sheet names.
Sheets(newFileName).Select
Range("C2").Formula = WorksheetFunction.SumIfs(Sheets(oldFileName).Range("$G:$G"), Sheets(oldFileName).Range("F:F"), Range("B2"))
This works!
However, I want to put the SUMIFS formula in cell C2
Sheets(newFileName).Select
Range("C2").Formula = "=SumIfs(Sheets(oldFileName).Range("$G:G"), Sheets(oldFileName).Range("F:F"), Range("B2"))"
This gives a compile error. Any ideas how to make it work?
You need to write the formula in formula syntax, which means ' before and after the sheet name and ! before the ranges. More importantly, a formula is just a String so you should not be using Sheets or Range calls when constructing it:
Sheets(newFileName).Range("C2").Formula = "=SumIfs('" & oldFileName & "'!G:G,'" & oldFileName & "'!F:F,B2)"

How do I create a link in Excel, with a formula in it, to another Workbook?

I'm not sure if this is even possible in Excel but this is what I need to do:
I have a column with a list of hotels and then another column which needs to pull data from each individual hotel's excel file. For example, cell A2 will have the name "Paris" for the hotel and then cell B2 will have the link:
='G:\Hotels\Paris\Paris - Monthly\[Paris_summary_2018.xlsm]Feb'!$CD$89
I have lots of hotels I need to do this for in different sheets. So I need the link to dynamically refer to whatever hotel is in column A and the title of the sheet, for example could I do something like this?
=''G:\Hotels\A2\A2 - Monthly\[A2_summary_2018.xlsm]Feb'!$CD$89
where A2 has the string "Paris". Also is there a way to dynamically refer to "Feb" depending on what sheet I am in the month will be the title
I am also open to using VBA for this.
As long as you don't mind using VBA, you can easily generate the links with something like this:
Sub generate_hotel_links()
Dim r As Range, c As Range
Dim s As String
' This is the range which all the hotel-locations are in
Set r = ThisWorkbook.Worksheets("Sheet1").Range("A1:A10")
On Error Resume Next
For Each c In r
' Generate the formula based on the current cell we are in
s = "=" & Chr(39) & "G:\Hotels\" & CStr(c) & "\" & CStr(c) & " - Monthly\[" & CStr(c) & "_summary_2018.xlsm]Feb" & Chr(39) & "!$CD$89"
' ...and put it in the neighbouring cell
c.Offset(0, 1).Formula = s
Next c
On Error Goto 0
End Sub
On Error Resume Next will make the macro continue no matter what error pops up - the ideal case would be some more robust error handling, or a check for if the workbook / sheet actually exists before attempting to write the formula, but I'll leave it to you to attempt to write this if you feel the need improve the macro.
If you want to just use generic Excel formulas, I'd advice having a look at the question and answers I posted in the comments to your question.
I am not sure if you can use HYPERLINK.
Like this:
=HYPERLINK("G:\Hotels\"&A2&"\"&A2&" - Monthly\["&A2&"_summary_2018.xlsm]Feb!"&$CD$89)

VBA fills whole table instead of defined cell

I ran into a crazy problem that I don't understand and for which I did not yet find a workaround.
First I have an excel macro filling various sheets on a workbook depending on information from other workbooks. I want to include a hyperlink to a website, containing the value in a specified cell in one workbook, while only displaying the value. I try to insert the formula as following
=HYPERLINK("https://example.com/value","value")
This hyperlink is only available for a certain cell, so it should only appear where a condition is true.
Now for the crazy part: If I fill the cell where I want to insert the hyperlink with a normal string or int, it works just fine and VBA only fills the cell I specified. When I insert a Hyperlink, it fills up the whole column on my worksheet, although everything else is kept in the same way.
Please find a snippet of the code below:
RequestID = Workbook1.ActiveSheet.Cells(i, 1).Text 'Request number
Workbook2.Sheets("Sheet1").Cells(y, 4) = RequestID
This only fills cell(y,4) with the correct request number as expected
Workbook2.Sheets("Sheet1").Cells(y, 4) = "RequestID"
This only fills cell(y,4) with the String "RequestID" as expected
Workbook2.Sheets("Sheet1").Cells(y, 4) = "=HYPERLINK(" & Chr(34) &"https://example.com/" & RequestID & Chr(34) & "," & Chr(34) & RequestID & Chr(34) & ")"
This fills up my whole table except for the header with the correctly working hyperlink.
I dont really understand why and I can't think of any possible problem. Maybe someone here has a hint for me, or knows a workaround.
It worked as expected for me when using a normal cell. But when I tried it in a Formatted Table (aka ListObject) then it fill the entire column, because it is a formula and not a value. If this is the case then try setting
Application.AutoCorrect.AutoFillFormulasInLists = False
before you put the Hyperlink in the cell (and then set it back to True)

Use cell value/contents to determine an external reference file or sheet name?

I'm working on a cell formula that returns (via VLOOKUP?) a cell in a closed workbook (thus I believe INDIRECT will not work). The issue is that I want to use a value in the active sheet to determine the name of the sheet in the reference workbook and can't figure it out. Here's the best I've got.
=VLOOKUP($A3,'[Other Workbook.xlsm]ObsDFW'!$1:$800,COLUMNS($D4:D4)+3)
ObsDAL is the name of one of the sheets in the "Other Workbook". What I can't figure out is how to keep the "Obs" part of that name constant, but take the "DFW" from a cell value.
Using bad code, I want it to be:
=...[Master Statistics.xlsm]("Obs" & A1)'!$1:$800...
If context is helpful, the "Other Workbook" is full of hourly weather observations, separated into one sheet for each of a series of airports. I'm trying to pull this info into another file/workbook so I don't have to specify each airport specifically in the code many times over.
Thanks in advance!
You could try this VBA approach. This way you are adjusting Vlookup formula based on your dynamic_part (sheetname)
Sub VlookupClosedWorkbook()
Dim dynamic_part As Variant
dynamic_part = Range("B1").Value 'You should enter in cell B1 dynamic part of sheet name
For x = 3 To Range("A" & Rows.Count).End(xlUp).Row
Range("B" & x).Value = "=VLOOKUP(A" & x & ",'[Other Workbook.xlsm]Obs" & dynamic_part & "'!$1:$800,COLUMNS($D4:D4)+3,FALSE)"
Next x
End Sub
Assign this macro to shape and fire it after you change your dynamic part. When you trigger it for the first time, make sure that you have both Workbooks open.

Runtime Error 1004 On formula R1C1 vba

I have some trouble applying a FORMULAR1C1 to a range.
This is the code i been using:
Range("AE6:AE" & conter).FormulaR1C1 = "=VLOOKUP(RC[-28],'[" & namebook & "]" & namesheet & "'!C1:C4,4,FALSE)"
where Conter is the number of rows that will applying the formula, namebook is the name of the woorkbook (without path) and namesheet is the name of the sheet that are looking the info for the vlookup.
the reason that i used a variable is that the file update daily and change the name because the date.
When i run this i get the runtime error 1004 what can i solve this? thanks
It's better of you stick with one style of Range.
You want to use FormulaR1C1, and your first VLOOKUP parameter is RC[-28], but the second one you are using C1:C4.
Also, you have a few "extra" ' that needs to be removed.
Modify your code to the line below:
Range("AE6:AE" & conter).FormulaR1C1 = "=VLOOKUP(RC[-28],[" & namebook & "]" & namesheet & "!R1C3:R4C3,4,FALSE)"

Resources