Excel VBA: how can I restrict code execution to the sheet - vba

I have a sheet with a function called in a cell in the sheet1.
When I change to the sheet2, edit something and go back to sheet1, I see the value change (because I use ActiveWorkbook and ActiveSheet). If I do something in sheet1 the value come back.
I can have multiple workbook with the same data too ...
Edit: I forgot to specify the name of workbooks and sheets are not static, all is dynamic.
Edit 2: I think Excel do a refresh of all sheet when editing a sheet and VBA code is execute, but the activesheet is not the Sheet1 where the data is ... So, VBA code run in the wrong sheet.
Edit 3: The sheet have "Calculation Options" to "Automatic" and I have a button in the bottom of my Excel page "Calculate" to force refresh of all formulas and VBA code.
Excel cell content:
=IF(BD66;MainFunction(BJ66);"")
Main Function:
Function MainFunction(var)
MainFunction = (var * Test()) / (...)
End Function
Sub Function is use in several functions:
Private Function Test()
Test = ActiveWorkbook.ActiveSheet.Range("BE50")
End Function
How can I do for execute code only on the active sheet and not on all sheet ?
Or what is the best way for do that ?
Thanks for your help.

From what I can see - your Test function causes the problem by always looking at the activesheet rather than the sheet that contains the =IF(BD66;MainFunction(BJ66);"") formula.
To look at this sheet you need to look at the cell that called the function using Application.Caller:
Public Function MainFunction(Target As Range) As Double
MainFunction = Target * Test(Application.Caller)
End Function
Private Function Test(Target As Range) As Double
Test = Target.Parent.Range("BE50")
End Function
I've updated var to Target as that's what I'm used to seeing in worksheet events.

I've find a workaround for my problem ...
I add parameters in my main function for replace all sub function which use "Active..."
My formulas are less simple to build, but it works in the sheet which contains formula ...
Thanks for your helps

Related

VBA Function #VALUE and debugging disabled

Every time I try to put some arguments in a Function Excel would return #VALUE. Below is one of the examples. Also, I cannot debug when I put arguments in. What is the possible cause? Thank you.
Function lastrowC(SelectedCell As Range)
sc = SelcetedCell.Column
lastrowC = ActiveSheet.Cells(Rows.Count, sc).End(xlUp).Row
End Function
Your code does not work due to a typo. If you add Option Explicit to the top of your code, then try to calculate, VBA will
show you the problem (you misspelled Selected)
Either way, please consider the below code which will target the correct worksheet rather the active worksheet. Your code, as is, will likely look to the wrong sheet to determine the last row under certain circumstances. You need to look at the sheet where the range was selected, which is not always going to be the same as the active sheet
Paste the below code in a Module to call function from excel
Function lastrowC(Target As Range) As Long
With Target.Worksheet
lastrowC = .Cells(.Rows.Count, Target.Column).End(xlUp).Row
End With
End Function

How to trigger VBA Workbook_SheetCalculate Event?

I tried Workbook_SheetCalculate Event and tried to trigger it, but it did not work, although I recalculated the worksheet!
How to trigger this Event?
here is an example, in the worksheet for the event have the following code:
Private Sub Worksheet_Calculate()
MsgBox "Calculating"
End Sub
Then in the sheet, in any cell, enter =RAND()
The formula causes a recalculation and triggers the event.
Or from a standard module use the following:
Public Sub Test()
'Application.Calculate ''could use this event for the workbook
With Worksheets("Sheet5") 'sheet containing the event code
.Calculate
End With
End Sub
The key seems to be that there is something in the sheet to calculate e.g. =RAND().
I remembered from another post, at some point, a link to the following Excel’s Smart Recalculation Engine
A quick extract says:
Excel normally only calculates the minimum number of cells possible.
Excel’s smart recalculation engine normally minimises calculation
time by tracking changes and only recalculating
Cells, formulae, values or names that have changed or are flagged as needing recalculation.
Cells dependent on other cells, formulae, names or values that need recalculation.
So, if you just had constants in the sheet, even if you issue a Worksheet.Calculate the msgbox wouldn't appear. You could test this by removing the =RAND() from the sheet and just putting 1 in the cell.
If I have two sheets each with a single non-volatile formula, and this in the workbook module:
Private Sub Workbook_SheetCalculate(ByVal Sh As Object)
Debug.Print Sh.Name
End Sub
I see both sheets names on calling:
Application.CalculateFull
or:
Application.CalculateFullRebuild
but no output with:
Application.Calculate
If I add a volatile formula to one of the sheets then I get that sheet when calling Application.Calculate.
If you're still having problems then you'd need to post a few more details including your event code and what types of formulas you have on your sheets.

Worksheets.Add in UDF Not Working

I have a UDF that can be called from within a cell in my excel workbook. I need it to add a worksheet at the end of the workbook. I have used sheets.add multiple times in my VBA script, but never in a function called from inside a cell and this is apparently causing some issue.
The function accepts an optional parameter for file path of the workbook in which to add the sheet, and if the user leaves this blank I want to default to the active workbook.
Below is the relevant code... What am I doing wrong?
Public Function onesheet(Optional filepath As String)
Dim wb As Workbook
Dim ws As Worksheet
If filepath = "" Then
Set wb = ActiveWorkbook
Set target_ws = wb.Sheets.Add(after:=wb.Sheets(wb.Sheets.Count))
End If
The function is being called from the cell with
=onesheet()
A function (UDF) has one role: compute a value and return that value to the cell (or formula/expression) that called it.
This is a function:
Public Function Foo(ByVal bar As String) As String
Foo = "Hello, " & bar
End Function
You can use it in a worksheet cell like this:
=Foo("dsdavidson")
And every time Excel recalculates that cell's value, it calls the UDF, making the cell's value read Hello, dsdavidson.
Functions don't have side-effects. Functions don't modify other cells. Functions take input, process it, and output a result.
What you're doing wrong, is using a UDF as if it were a macro.
Change your Function for a Sub, and don't call it from within a cell. Make a button to call it instead. Or whatever rocks your boat. But you can't have a cell formula that adds a worksheet to the workbook every time it recalculates.
Macros need to be Public and parameterless. So you'll want to take your optional parameter value from a specific cell, or display a form that lets the user pick from a list of available opened workbooks - and then call your procedure and pass the user's selection as a parameter.
Quite possibly the macro code could end up looking something like this (YMMV):
Public Sub AddWorksheet()
With New PromptForm
.Show
If .Cancelled Then Exit Sub
OneSheet .SelectedBook
End With
End Sub
You cannot add sheets through user defined function.
Here are the limitations of User Defined Functions.
A user-defined function called by a formula in a worksheet cell cannot change the environment of Microsoft Excel. This means that such a function cannot do any of the following:
1) Insert, delete, or format cells on the spreadsheet.
2) Change another cell's value.
3) Move, rename, delete, or add sheets to a workbook.
4) Change any of the environment options, such as calculation mode or screen views.
5) Add names to a workbook.
6) Set properties or execute most methods.
For more details visit this site...
https://support.microsoft.com/en-in/help/170787/description-of-limitations-of-custom-functions-in-excel

UDF for array formulas created from macro

I want to create a udf for a formula I have written on excel. The formula is as follows:
=INDEX('Pivot-LH'!$D$5:$D$1650,SMALL(IF(B93='Pivot-LH'!$A$5:'Pivot-LH'!$A$1650,ROW('Pivot-LH'!$A$5:'Pivot-LH'!$A$1650)-ROW('Pivot-LH'!$A$5)+2),1))
Basically the syntax is to look for cell B93 (variable) through some data on Pivot-LH sheet and return the 1st, 2nd and 3rd values.
I want to define a udf for this and tried to do this by recording a macro. It gave the following result which I modified to enter B93 as a variable called newroute. However this always gives the value zero:
Public Function LH(newroute As Range) As Variant
Selection.FormulaArray = "=INDEX(R5C4:R1650C4,SMALL(IF(newroute=R5C1:R1650C1,ROW(R5C1:R1650C1)-ROW(R5C1)+2),1))"
End Function
Why does it not give the same result as the formula?
If you want to call LH from a worksheet formula, your function can only return a value. It cannot update the sheet directly.
See: https://support.microsoft.com/en-us/kb/170787
A user-defined function called by a formula in a worksheet cell cannot
change the environment of Microsoft Excel. This means that such a
function cannot do any of the following:
Insert, delete, or format cells on the spreadsheet.
Change another cell's value.
Move, rename, delete, or add sheets to a workbook.
Change any of the environment options, such as calculation mode or screen views.
Add names to a workbook.
Set properties or execute most methods.
So you need something like:
Public Function LH(newroute As Range) As Variant
LH = newroute.Parent.Evaluate("=INDEX(R5C4:R1650C4,SMALL(IF(" & _
newroute.Address() & _
"=R5C1:R1650C1,ROW(R5C1:R1650C1)-ROW(R5C1)+2),1))"
End Function
Try this
Public Function LH(newroute As Range) As Variant
Selection.FormulaArray = "=INDEX(R5C4:R1650C4,SMALL(IF(" & newroute.address & "=R5C1:R1650C1,ROW(R5C1:R1650C1)-ROW(R5C1)+2),1))"
End Function

How to refresh calculation instantaneously in excel

I have a problem in refreshing the cell's calculation.
In other words, I have many columns where i have a formula or macro in each one of them.
But the problem is that i should absolutely activate the option " automatic calculation" in the excel options or i should save then the new results appear.
Now, I would insert something in the macro that can refresh me the results instantaneously.
Thanks
To force all formulas to update, including custom vba formulas, execute the following in VBA:
Application.CalculateFullRebuild
This can also be executed from the VBA immediate window.
More documentation here:
https://learn.microsoft.com/en-us/office/vba/api/excel.application.calculatefullrebuild
You could simply press :
F9 to calculate the whole active workbook
Shift + F9 to calculate the active sheet
Anyway, here are the different options with .Calculate :
Sub Souma()
'Use this to calculate all the open workbooks
Application.Calculate
'Use this to calculate the whole sheet, called "Sheet1"
ThisWorkbook.Worksheets("Sheet1").Calculate
'Use this to calculate the cell A1 on the sheet called "Sheet1"
ThisWorkbook.Worksheets("Sheet1").Range("A1").Calculate
'Use this to calculate the range A1 to D10 on the sheet called "Sheet1"
ThisWorkbook.Worksheets("Sheet1").Range("A1:D10").Calculate
'Use this to calculate the column A on the sheet called "Sheet1"
ThisWorkbook.Worksheets("Sheet1").Columns(1).Calculate
'Use this to calculate the row 1 on the sheet called "Sheet1"
ThisWorkbook.Worksheets("Sheet1").Rows(1).Calculate
End Sub
Copy and paste the code below to your VBA project:
Private Sub Workbook_Open()
Application.Calculation = xlCalculationAutomatic
End Sub
This code should automatically run after you open the Excel file, enabling automatic calculation in all opened files.