问题
I wrote a function that calculates the sales for 2014 for the specific worksheets inside the workbook, then prints the total sales for 2014 in a specific cell. I can call the function inside of VBA, no issue. But if try to use the function in the workbook, I get a reference error. I know #REF! means the formula refers to a cell that isn't valid, do I need to be returning some kind of value into the cell that I am trying to call the function into? For example, if I type sum2014("A1151") into cell F25, do I need to be returning some kind of boolean value for the function to work properly?
Function sum2014(someaccount As String) As Currency
Dim i As Integer
Dim total As Currency
Dim ws As Worksheet
total = 0
Set ws = ActiveWorkbook.Worksheets(someaccount)
For i = 1 To 50
If ws.Range("A3").Offset(i, 0) >= DateValue("January 1, 2014") And ws.Range("A3").Offset(i, 0) <= DateValue("December 1, 2014") Then
total = total + ws.Range("A3").Offset(i, 1)
sum2014 = total
End If
Next
If Worksheets("New Charges").Range("C3").Offset(i, 0) = someaccount Then
Worksheets("New Charges").Range("E3").Offset(i, 0) = total
End If
For i = 1 To 5
If Worksheets("New Charges").Range("C3").Offset(i, 0).Value = someaccount Then
Worksheets("New Charges").Range("E3").Offset(i, 0).Value = total
End If
Next
End Function
Example of calling the function inside VBA:
Sub testfunction()
sum2014 ("A1151")
sum2014 ("B1808")
sum2014 ("C3711")
sum2014 ("D3265")
End Sub
I can call the function inside VBA, and it works fine. The sales are calculated and placed in the proper location. But I cannot call the UDF inside of the workbook. I am calling the function with
sum2014=("A1151")
Any hints or suggestions would be greatly appreciated. I could probably clean up the function with do while or do until loops instead of for loops but for right now I would just like to get the function working inside of the workbook then revisit rewriting later.
回答1:
While it is correct that a function called from a sheet may not change sheets (and you may run into problems if you try to use a trick to work around it), your immediate problem is that sum2014 is a valid Excel range address (column 13403 (SUM), row 2014), hence the #REF! error when you try to do =SUM2014("A1151"). It's the same as if your function was called A1.
A name usable in a formula may not look like a valid Excel range. Pick another name (and make sure you don't change other cells from that function, otherwise it will be a #VAL! error).
If you need to change various cells from a routine, make it a sub and call it from an external event, such as a button press or a Worksheet_Change handler, but not from a formula in a cell.
来源:https://stackoverflow.com/questions/53134535/udf-works-in-vba-returns-ref-in-workbook