How to create a parameterized add-in for an excel workbook - vba

I need to create an excel add-in that takes parameters of the upper and lower bound of two data sets. I currently have a function written that performs the correct calculation for integration using the trapezoidal rule hardcoded in for a range with a lower bound of 4 and an upper bound of 13.
(=SUMPRODUCT(A5:A13-A4:A12;(B5:B13+B4:B12)/2)
I need to create a stand alone (possibly add-in) file that can be imported into any excel file and accept two parameters (upper and lower bound in place of the 4 and 13) to accomplish this function as simple as possible.
Would an add-in be the best way to go about this or is there some better way to accomplish this task?

my apologies; cannot comment yet as I don't have enough reputation
How would two parameters accomplish your function? I can't even get your formula running correctly?
That said, you simply need to place your computation in a function in VBA, being sure to make it a public function, and then save that module, export it, and hand it over to whoever needs to use it. They will need to import the module into VBA, but after that they just need to call it from the formula bar, typing as you would a normal worksheet function like:
=TrapezoidFunctionByCaseyHux(
and then they will be asked to provide the parameter cells.
Hope this helps somehow

To create UDF (user defined function) you can use also .Net through the
ExcelDna framework .
So you can create your add-in and distribute it in your organization with an installer.

Import a .bas file with this code into your Visual Basic editor for your excel worksheet
Option Explicit
Function Trapezoid(KnownXs As Variant, KnownYs As Variant) As Variant
Dim i As Integer
If Not TypeName(KnownXs) = "Range" Then
Trapezoid = "X range is not valid"
Exit Function
End If
If Not TypeName(KnownYs) = "Range" Then
Trapezoid = "Y range is not valid"
Exit Function
End If
If KnownXs.Rows.Count <> KnownYs.Rows.Count Then
Trapezoid = "Number of Xs <> Number of Ys"
Exit Function
End If
Trapezoid = 0
For i = 1 To KnownXs.Rows.Count - 1
Trapezoid = Trapezoid + Abs(0.5 * (KnownXs.Cells(i + 1, 1) _
- KnownXs.Cells(i, 1)) * (KnownYs.Cells(i, 1) + KnownYs.Cells(i + 1, 1)))
Next i
End Function
You can then use your selection as parameters and add the .bas file to multiple workbooks

Related

How do I assign an Excel VBA variable to a Defined Name

How do I return a value from a VBA Function variable to a Defined Name in Excel 2010?
In the example below, I want i to be returned to Excel as a Defined Name Value_Count that can be reused in other formulas, such that if MsgBox shows 7, then typing =Value_Count in a cell would also return 7.
Everything else below is about what I've tried, and why I'd like to do it. If it's inadvisable, I'd be happy to know why, and if there's a better method.
Function process_control_F(raw_data As Variant)
Dim i As Integer
i = 0
For Each cell In raw_data
i = i + 1
Next cell
MsgBox i
End Function
My goal is to have the value returned by the MsgBox be returned instead to a Defined Name that can be reused in other forumulas. However, I cannot get the value to show. I have tried a variety of forms (too numerous to recall, let alone type here) similar to
Names.Add Name:="Value_Count", RefersTo:=i
I am trying to accomplish this without returning a ton of extra info to cells, just to recall it, hence the desire to return straight to a Defined Name.
I'm using a Function rather than Sub to streamline my use, but if that's the problem, I can definitely change types.
I am creating a version of a Statistical Control Chart. My desired end result is to capture a data range (generally about 336 values) and apply a series of control rules to them (via VBA), then return any values that fall outside of the control parameters to Defined Names that can then be charted or otherwise manipulated.
I've seen (and have versions of) spreadsheets that accomplish this with digital acres of helper columns leading to a chart and summary statistics. I'm trying to accomplish it mostly in the background of VBA, to be called via Defined Names to Charts — I just can't get the values from VBA to the Charts.
The interest in using a Function rather than a Sub was to streamline access to it. I'd rather not design a user interface (or use one), if I can just keystroke the function into a cell and access the results directly. However, as pointed out by Jean-François Corbett, this is quickly turning into a circuitous route to my goal. However, I still think it is worthwhile, because in the long-term I have a lot of iterations of this analysis to perform, so some setup time is worth it for future time savings.
With minor changes to your function, you can use its return value to accomplish what you want:
Function process_control_F(raw_data As Variant) As Integer ' <~~ explicit return type
Dim i As Integer
Dim cell As Variant ' <~~~~ declare variable "cell"
i = 0
For Each cell In raw_data
i = i + 1
Next cell
process_control_F = i ' <~~~~ returns the value i
End Function
You can then use that function in formulas. For example:

Functions give error only in macro-called dialog

I am writing and re-writing Excel VBA code to make some engineering analysis easier for myself and the others at my company. So the goal is to make it easy for others, not to be integrated into other code or purposes outside our own Excel work.
The problem: a few of the macros will add a custom function to a worksheet cell, bring up the function dialog for inputs, but then when completed, come up with a Value error, stating A value used in the formula is of the wrong data type. Based on this, I believe the issue arises when my function uses a Variant or Range type variable. Some of these functions only give this error via certain input types.
HOWEVER, in every single case, using the function dialog Not in the macro works fine, as does typing the formula in manually. Additionally, all you have to do is double-click on the error cell to edit it, change nothing, press enter, and it's fine!
My macros themselves are as simple as:
Sub NewSTC_dialog()
ActiveCell.FormulaR1C1 = "=sheetname.xlsm!NewSTC()"
Application.Dialogs(xlDialogFunctionWizard).Show
End Sub
My functions have more to them, but the situation is different for different functions, and the functions themselves work fine, so it is preferable to have a solution that applies to the macros rather than within the functions. If I must, I can go through each situation individually or come up with a simplified function that has the same issue to give as an example.
My best workaround so far (I cannot re-find the website were I found this particular solution):
Sub Recalculate()
ActiveCell.Replace What:="=", Replacement:="="
End Sub
Set to a convenient shortcut, and it works great. However, as mentioned above, the goal is to make this easy for everyone else, which would mean not requiring anything additional to have the formula work. Unfortunately, calling this from within the initial macro will not work. In fact, nothing located after the dialog call will run. I tried using On Error Resume Next and it still won't run anything after the dialog call.
Some options searched and tried:
How to refresh cells in Excel 2010 using VBA? and links within that - as mentioned, nothing located after the dialog call will run, thus won't reach these adjustments. Putting before the dialog call also doesn't help. Putting the dialog call in between the false and true statements makes the false apply, then never runs the true statement.
http://www.excelforum.com/excel-general/471632-formula-do-not-work-until-edited.html - Excel is not set to manual
http://blog.contextures.com/archives/2012/02/16/excel-formulas-not-calculating/ - SUMIF is not involved
This is all on Excel 2010, Windows 7 Professional.
EDIT:
Here is an example that creates this behavior. This is similar to the behavior of two of my functions, but not to all of them, so again, I would much prefer the solution be in the macro, not the function. This is just for anybody else's testing purposes.
Function LetNum(input1 As Variant, input2 As Variant) As Integer
If input1 = "A" Or input1 = "a" Then
input1 = 100
ElseIf input1 = 10 Then
input1 = -10
End If
If input2 = "B" Or input2 = "b" Then
input2 = 200
ElseIf input2 = 10 Then
input2 = -1000
End If
LetNum = input1 + input2
End Function
Sub LetNum_dialog()
ActiveCell.FormulaR1C1 = "=LetNum()"
Application.Dialogs(xlDialogFunctionWizard).Show
End Sub
In this situation, typing A and 2 into the dialog box in that order works, but 2 into the second then A into the first doesn't. Additionally, typing B in the second box never works. In all situations, clicking to edit, changing nothing, and hitting enter, fixes it. Additionally, any situation in the dialog box if you bring it up without the macro works fine.
Also, I'm aware this case works better if you input it with quotes, but excel automatically changes it correctly, and not all my functions are string issues.
EDIT 2:
Tim's answer is a great step in the right direction! However, if anybody can come up with a solution that doesn't involve ignoring all errors, that would be more ideal due to some desired error-throwing being ignored. I will look into handling errors differently in the meantime.
The issue seems to be that any error triggered in your UDF effectively "disables" the Function Wizard: note that in cases where you get #VALUE! error, the Show() method never returns any value, and any lines following the call to Show() are not executed.
The only thing which resolved this in my testing was to add a line to the function which skips any errors when the Function Wizard is open:
Dim bSettingUp As Boolean
Function LetNum(input1 As Variant, input2 As Variant) As Integer
If bSettingUp Then On Error Resume Next
If input1 = "A" Or input1 = "a" Then
input1 = 100
ElseIf input1 = 10 Then
input1 = -10
End If
If input2 = "B" Or input2 = "b" Then
input2 = 200
ElseIf input2 = 10 Then
input2 = -1000
End If
LetNum = input1 + input2
End Function
Sub LetNum_dialog()
ActiveCell.Formula = "=LetNum()"
bSettingUp = True
Debug.Print Application.Dialogs(xlDialogFunctionWizard).Show()
bSettingUp = False
End Sub
I'm aware that you'd rather not alter your functions ,but this was the only work-around I could find.

VBA UDF fails to call Range.Precedents property

I am trying to write a simple UDF, which is supposed to loop through each of the cells of a given_row, and pick up those cells which do not have any precedent ranges, and add up the values.
Here is the code:
Public Function TotalActualDeductions(given_row As Integer) As Integer
Total_Actual_Deduction = 0
For present_column = 4 To 153
Set precedent_range = Nothing
If Cells(2, present_column) = "TDS (Replace computed figure when actually deducted)" Then
On Error Resume Next
Set precedent_range = Cells(given_row, present_column).Precedents
If precedent_range Is Nothing Then
Total_Actual_Deduction = Total_Actual_Deduction + Cells(given_row, present_column)
End If
End If
Next
TotalActualDeductions = Total_Actual_Deduction
End Function
If I try to run it by modifying the top declaration, from:
Public Function TotalActualDeductions(given_row As Integer) As Integer
to:
Public Function TotalActualDeductions()
given_row = 4
then it runs successfully, and as expected. It picks up exactly those cells which match the criteria, and all is good.
However, when I try to run this as a proper UDF from the worksheet, it does not work. Apparently, excel treats those cells which have no precedents, as though they have precedents, when I call the function from the worksheet.
I don't know why this happens, or if the range.precedents property is supposed to behave like this.
How can this be fixed?
After a lot of searching, I encountered this:
When called from an Excel VBA UDF, Range.Precedents returns the range and not its precedents. Is there a workaround?
Apparently, "any call to .Precedents in a call stack that includes a UDF gets handled differntly".
So, what I did was use Range.Formula Like "=[a-zA-Z]" , because it satisfied my simple purpose. It is in no way an ideal alternative to the range.precedents property.
Foe a more detailed explanation, please visit that link.

Execute a user-defined function into another cell VBA Excel

I need to automatize a process which execute various (a lot) user-defined function with different input parameters.
I am using the solution of timer API found in I don't want my Excel Add-In to return an array (instead I need a UDF to change other cells) .
My question is the following: "Does anybody can explain to me HOW IT IS WORKING?" If I debug this code in order to understand and change what I need, I simply go crazy.
1) Let say that I am passing to the public function AddTwoNumbers 14 and 45. While inside AddTwoNumber, the Application.Caller and the Application.Caller.Address are chached into a collection (ok, easier than vectors in order not to bother with type). Application.Caller is kind of a structured object where I can find the function called as a string (in this case "my_function"), for example in Application.Caller.Formula.
!!! Nowhere in the collection mCalculatedCells I can find the result 59 stored.
2)Ok, fair enough. Now I pass through the two UDF routines, set the timers, kill the timers.
As soon as I am inside the AfterUDFRoutine2 sub, the mCalculatedCell(1) (the first -- and sole -- item of my collection) has MAGICALLY (??!?!?!!!??) obtained in its Text field exactly the result "59" and apparently the command Set Cell = mCalculatedCells(1) (where on the left I have a Range and on the right I have ... I don't know) is able to put this result "59" into the variable Cell that afterward I can write with the .Offset(0,1) Range property on the cell to the right.
I would like to understand this point because I would like to give MORE task to to inside a single collection or able to wait for the current task to be finished before asking for a new one (otherwise I am over-writing the 59 with the other result). Indeed I read somewhere that all the tasks scheduled with the API setTimer will wait for all the callback to be execute before execute itself (or something like this).
As you can see I am at a loss. Any help would be really really welcomed.
In the following I try to be more specific on what (as a whole)
I am planning to achieved.
To be more specific, I have the function
public function my_function(input1 as string, Field2 as string) as double
/*some code */
end function
I have (let's say) 10 different strings to be given as Field2.
My strategy is as follow:
1)I defined (with a xlw wrapper from a C++ code) the grid of all my input values
2)define as string all the functions "my_function" with the various inputs
3)use the nested API timer as in the link to write my functions IN THE RIGHT CELLS as FORMULAS (not string anymore)
3)use a macro to build the entire worksheet and then retrieve the results.
4)use my xlw wrapper xll to process further my data.
You may wonder WHY should I pass through Excel instead of doing everything in C++. (Sometime I ask myself the same thing...) The prototype my_function that I gave above has inside some Excel Add-In that I need to use and they work only inside Excel.
It is working pretty well IN THE CASE I HAVE ONLY 1 "instance" of my_function to write for the give grid of input. I can even put inside the same worksheet more grids, then use the API trick to write various different my_functions for the different grids and then make a full calculation rebuild of the entire worksheet to obtain the result. It works.
However, as soon as I want to give more tasks inside the same API trick (because for the same grid of input I need more calls to my_function) I am not able to proceed any further.
After Axel Richter's comment I would like to ad some other information
#Axel Richter
Thank you very much for your reply.
Sorry for that, almost surely I wasn't clear with my purposes.
Here I try to sketch an example, I use integer for simplicity and let's say that my_function works pretty much as the SUM function of Excel (even if being an Excel native function I could call SUM directly into VBA but it is for the sake of an example).
If I have these inputs:
input1 = "14.5"
a vector of different values for Field2, for instance (11;0.52;45139)
and then I want to write somewhere my_function (which makes the sum of the two values given as input).
I have to write down in a cell =my_function(14.5;11), in the other =my_function(14.5;0.52) and in a third one =my_function(14.5;45139).
These input changes any time I need to refresh my data, then I cannot use directly a sub (I think) and, in any case, as far as I understand, in writing directly without the trick I linked, I will always obtain strings : something like '=my_function(14.5;0.52). Once evaluated (for example by a full rebuild or going over the written cell and make F2 + return) will give me only the string "=my_function(14.5;0.52)" and not its result.
I tried at the beginning to use an Evaluate method which works well as soon as I write something like 14.5+0.52, but it doesn't work as soon as a function (nor a user-defined function) is used instead.
This is "as far as I can understand". In the case you can enlighten me (and maybe show an easier track to follow), it would be simply GREAT.
So far the comments are correct in that they repeat the simple point that a User-Defined Function called a worksheet can only return a value, and all other actions that might inject values elsewhere into the worksheet calculation tree are forbidden.
That's not the end of the story. You'll notice that there are add-ins, like the Reuters Eikon market data service and Bloomberg for Excel, that provide functions which exist in a single cell but which write blocks of data onto the sheet outside the calling cell.
These functions use the RTD (Real Time Data) API, which is documented on MSDN:
How to create a RTD server for Excel
How to set up and use the RTD function in Excel
You may find this link useful, too:
Excel RTD Servers: Minimal C# Implementation
However, RTD is all about COM servers outside Excel.exe, you have to write them in another language (usually C# or C++), and that isn't the question you asked: you want to do this in VBA.
But I have, at least, made a token effort to give the 'right' answer.
Now for the 'wrong' answer, and actually doing something Microsoft would rather you didn't do. You can't just call a function, call a subroutine or method from the function, and write to the secondary target using the subroutine: Excel will follow the chain and detect that you're injecting values into the sheet calculation, and the write will fail.
You have to insert a break into that chain; and this means using events, or a timer call, or (as in RTD) an external process.
I can suggest two methods that will actually work:
1: Monitor the cell in the Worksheet_Change event:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim strFunc As String strFunc = "NukeThePrimaryTargets" If Left(Target.Formula, Len(strFunc) + 1) = strFunc Then Call NukeTheSecondaryTargets End If End Sub
Alternatively...
2: Use the Timer callback API:
However, I'm not posting code for that: it's complex, clunky, and it takes a lot of testing (so I'd end up posting untested code on StackOverflow). But it does actually work.
I can give you an example of a tested Timer Callback in VBA:
Using the VBA InputBox for passwords and hiding the user's keyboard input with asterisks.
But this is for an unrelated task. Feel free to adapt it if you wish.
Edited with following requirements: It is necessary to run a user defined worksheet function, because there are addins called in this function and those work only within a Excel sheet. The function has to run multiple times with different parameters and its results have to be gotten from the sheet.
So this is my solution now:
Public Function my_function(input1 As Double, input2 As Double) As Double
my_function = input1 + input2
End Function
Private Function getMy_Function_Results(input1 As Double, input2() As Double) As Variant
Dim results() As Double
'set the Formulas
With Worksheets(1)
For i = LBound(input2) To UBound(input2)
strFormula = "=my_function(" & Str(input1) & ", " & Str(input2(i)) & ")"
.Cells(1, i + 1).Formula = strFormula
Next
'get the Results
.Calculate
For i = LBound(input2) To UBound(input2)
ReDim Preserve results(i)
results(i) = .Cells(1, i + 1).Value
Next
End With
getMy_Function_Results = results
End Function
Sub test()
Dim dFieldInput2() As Double
Dim dInput1 As Double
dInput1 = Val(InputBox("Value for input1"))
dInput = 0
iIter = 0
Do
dInput = InputBox("Values for fieldInput2; 0=END")
If Val(dInput) <> 0 Then
ReDim Preserve dFieldInput2(iIter)
dFieldInput2(iIter) = Val(dInput)
iIter = iIter + 1
End If
Loop While dInput <> 0
On Error GoTo noFieldInput2
i = UBound(dFieldInput2)
On Error GoTo 0
vResults = getMy_Function_Results(dInput1, dFieldInput2)
For i = LBound(vResults) To UBound(vResults)
MsgBox vResults(i)
Next
noFieldInput2:
End Sub
The user can input first a value input1 and then input multiple fieldInput2 until he inputs the value 0. Then the results will be calculated and presented.
Greetings
Axel

VBA - Convert string into Arithmetic Operator

Using VBA, I am trying to convert a string such as "/10" into an arithmetic operation, so that if I somehow connect it (depending on how it gets converted) after the number 200, the number 20 would be returned.
Thanks for any help.
What you're looking for is called a Math Parser. Look around for a library that you can use in VBA. If you're working in excel specific stuff - I'm sure excel already has a math parser built in - though I have no idea how you can gain access to it as the programmer. Maybe stick the expression in a cell as a string and call Eval().
EDIT
Microsoft intentionally removed this feature from function calls in excel, however it can be reinstated by creating the following function:
Function Eval(Ref As String)
Application.Volatile
Eval = Evaluate(Ref)
End Function
Then just call Eval("200" & "/10")
EDIT2
As noted in the comments below, modern versions of VBA support
Application.Evaluate("200" & "/10")
the below example provides a way of accomplishing what you are looking for.
Dim s As String
s = "/10"
Dim i As Integer
i = 200
Dim v
v = Evaluate(CStr(i) & s)
MsgBox v