Can someone help me with the implementation of this?
Range("B3").Formula = "=SUMIF(Active.Select!$A:$A,Results.select!$A3,Active.select!B:B)"
I have defined Active and Results as WorkSheet and my objective was to have a dynamic reference to them so so that the macro cna be run on any sheet of the workbook without having any kind of static referece lik Sheet1!
If i try to run what i have wrote he ask me to provide Active and Results through a open... window
I know it might be a noobish question but i am just getting started
If you remove the sheet names then the formula will refer to the Worksheet that it is on.
Range("D2").Formula = "=SUMIF($A:$A,$E$1,$B:$B)"
Worksheets have an Evaluate method that will return the value of a formula
Note: I didn't use Range("B3").Formula = "=SUMIF($A:$A,$A3,B:B)" because it is a circular reference.
Assuming that Active and Results are both Worksheet objects, then if you wish to create a formula to go into cell B3 of the ActiveSheet, try this:
Range("B3").Formula = "=SUMIF('" & Active.Name & "'!$A:$A,'" & Results.Name & "'!$A3,'" & Active.Name & "'!B:B)"
If you want to just obtain the value and use it for something within VBA, try this:
Dim sumIfResult As Double
sumIfResult = Application.WorksheetFunction.SumIf(Active.Range("$A:$A"),Results.Range("$A3"),Active.Range("B:B"))
Related
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.
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.
EDITED WITH BETTER EXAMPLE
I'm trying to use the Evaluate function to evaluate a formula reference for a named range. However, when using the Evaluate function, if you do not explicitly state the sheet reference along with the cell reference, it will assume the active sheet as the cell reference. This causes the wrong result
In my real project I'm trying to only evaluate a part of the named range's formula, so it makes it even trickier.
Using a basic example of what I'm trying to do, let's say you have the following formula in Sheet 1 cell A1 whose name is MyCell:
="Don't evaluate this part"&"My Result Is " & A2
If the Active Sheet is Sheet 2 and you run the following code it will give you the wrong results (this is a quick and dirty example to illustrate the problem)
Dim s As String
s = Replace(Range("MyCell").Formula, """Don't evaluate this part""&", "")
Debug.Print Evaluate(s)
Instead of giving me the value that is in cell A2 of Sheet 1, it gives me the value that is in cell A2 of Sheet2.
Any ideas around this?
This is closest I found, but it is not my exact problem (despite similar titles) and it doesn't provide a solution:
Excel VBA evaluate formula from another sheet
The problem you are having is that by design Excel will assume all unspecific cell references are referring to the existing worksheet. This is why whenever possible it is recommended to explicitly state the worksheet in all code.
The cleanest way (verified with some MSDN definintion hunting) is to just explicitly state the worksheet without activating it:
Sub test2()
Debug.Print Range("MyCell").Worksheet.Evaluate(Range("MyCell").Formula)
End Sub
Alternatively this code will change the active worksheet to the correct one and then change it back after evaluation. Not recommended to perform sheet activations like the code below without extenuating circumstances. Not even here.
Sub test()
Dim ws As Worksheet
Set ws = ActiveSheet
Dim s As String
s = Replace(Range("MyCell").Formula, """Don't evaluate this part""&", "")
Range("MyCell").Worksheet.Activate ' Don't remember if .Worksheet or .Parent ??
Debug.Print Evaluate(s)
ws.Activate
End Sub
As pointed out in the comments by ThunderFrame, it is important to remember that this code assumes MyCell is a simple cell reference as stated in the question. Otherwise you will need to use other methods to determine the target worksheet name (or hardcode it).
Its nearly always better to use Worksheet.Evaluate rather than the default Application.Evaluate: as Mark Balhoff points out that allows you to control unqualified references.
But Worksheet.Evaluate is also usually twice as fast as Application.Evaluate.
See my blog post here for details
https://fastexcel.wordpress.com/2011/11/02/evaluate-functions-and-formulas-fun-how-to-make-excels-evaluate-method-twice-as-fast/
Your line:
Debug.Print Evaluate(Range("MyCell").Formula)
is equivalent to:
Debug.Print Evaluate("=""My Result Is "" & A2")
which is why you get results according to the value of A2 in the ActiveSheet.
If you want to inspect the contents of the formula, you can use this line:
Debug.Print [MyCell].Formula
If you want the value of MyCell with respect to Sheet1, then you have 2 options:
1 - Use Debug.Print Range("Sheet1!MyCell").Value
2 - Use Debug.Print Sheet1.Range("MyCell").Value
I am trying to import a range of cells from a closed workbook.
I use the external reference link built into Excel:
='F:\UGR\JOB DATA SHEET\[JOB SHEETS 1-500.xlsx]JobNumber'!B4
='F:\UGR\JOB DATA SHEET\[JOB SHEETS 1-500.xlsx]JobNumber'!B5
...
Going down the column from B4:B23 and replicating that for columns B-Z.
This works if the sheet name doesn't change. But that file contains sheets for Jobs 1 - 500, each on their own sheet. I am trying to pull those columns of data for whatever JobNumber gets entered into cell "B7". So ideally it would look like this:
='F:\UGR\JOB DATA SHEET\[JOB SHEETS 1-500.xlsx]&B7&'!B4
='F:\UGR\JOB DATA SHEET\[JOB SHEETS 1-500.xlsx]&B7&'!B5
...
Etc.
I know this won't work without the Indirect function, but I need to have the other file open for that to work. This isn't practical given the number of users who are using this file for reference.
I found a macro in VBA that should do what I need, but I can't get it to work. Here is the base macro before I started messing around with it.
Function GetValue(Path, File, Sheet, Ref)
'Retrieves a value from a closed workbook
Dim Arg As String
'Make sure the file exists
If Right(Path, 1) <> "\" Then Path = Path & "\"
If Dir(Path & File) = "" Then
GetValue = "File not Found"
Exit Function
End If
'Create the argument
Arg = "'" & Path & "[" & File & "]" & Sheet & "'!" & Range(Ref.Range("A1").Address(, , xlR1C1))
'Execute XLM macro
GetValue = ExecuteExcel4Macro(Arg)
End Function
Any ideas on how to get it to work, or an alternative work around? I could also temporarily import the sheet to my other file and overwrite it when a new value is entered, thus importing another sheet from the other workbook, but that seems far more complex.
I am using Excel 2013.
UPDATE: I am closer to figuring it out but I cant get it to display anything but #Value errors. My formula looks like this in excel:
=GetValue(H11,H12,B7,B4)
Cell H11 = F:\UGR\JOB DATA SHEET\
Cell H12 = JOB SHEETS 1-500.xlsx
Cell B7 = The input cell where the user enters a JobNumber (aka sheet name).
Cell B4 = B4 (The cell I want to search on the external workbook)
Cell B4 is where I think the error lies. Will this macro be able to tell that it needs to search the external file at cell B4?
I figured it out. The macro cannot be launched from within the workbook itself, it must be done from VBA.
I would like to be able to reference the next worksheet in a workbook using VBA, but avoid referencing the sheet name as I hope to be able to apply the macro to a number of different workbooks.
I am writing an Excel Macro which is for formatting an excel chart. In the chart's series title I would like to make the series name reference a cell in the next worksheet.
I have tried the following which is not working:
ActiveChart.SeriesCollection(1).Name = "='ActiveChart.Next.Select'!$B$1"
However this is not working.
What is the most effective way of getting the series name field of a chart to reference a cell in the following worksheet within a macro?
I have also tried the following, which does not work either:
ActiveChart.SeriesCollection(1).Name = "=Sheets(1)!$B$1"
Please bear in mind that this is a workbook which is structured with a chart, then a sheet, chart, sheet and so on...
You can use this one-liner
ActiveChart.SeriesCollection(1).Name = "='" & Sheets(ActiveChart.Parent.Parent.Name).Next.Name & "'!B1
Sheets(ActiveChart.Parent.Parent.Name returns the name of the next sheet.
The pair of ' are important to use when referring to sheetnames. i.e. a sheet named My Sheet won't work as My Sheet!B1, it must be 'My Sheet'!B1
Looks like you are trying to put VBA code instead of classical Excel formula reference. I havent ever tried it but I pressume that it wont work. If you want to reference something to a cell you must create the formula in that good old clear syntax with =, sheetname, !, cell address something like:
=Sheet1!A1
You can ofcourse use VBA to create this formula for you and assign it to the field. Try this code:
Dim ws As Worksheet
Dim formula As String
Set ws = ActiveSheet.Next
formula = "=" & ws.name & "!A1"
ActiveChart.SeriesCollection(1).name = formula