#NAME? error in Excel for VBA Function - excel

I am making my first VBA program and trying to run the following function. The function checks a specific named range for the first row which does not have a value greater than it's leading value, but less than 1.
Public Function findPurchase()
Dim CRT As Range
Set CRT = Range("CostRateTable")
Dim existsBetter As Boolean
existsBetter = True
Dim r As Integer
r = 2
Dim c As Integer
c = 4
While existsBetter
Dim Found As Boolean
FoundBetter = False
While Not FoundBetter And c <= CRT.Columns.Count
If CRT(r, c) > CRT(r, 2) And CRT(r, c) < 1 Then
FoundBetter = True
Else
c = c + 1
End If
Wend
existsBetter = FoundBetter
If existsBetter Then
r = r + 1
End If
Wend
findPurchase = CRT(r, 3)
'MsgBox(findPurchase)
End Function
I know the function does what it is supposed to because I have both manually checked the table of values, removed the comment ' from the MsgBox, and used the debug tools to step in and out of each of the functions steps as it went through the table. However, when I reference the function in Excel with =findPurchase() I'm given a #NAME? error. The function even shows up in the function auto-complete box when I begin to type its name. When I write other functions, both with and without parameters, I can reference them just fine, for example:
Function addtwo()
addtwo = 1 + 2
End Function
What am I doing wrong with my function which causes it not to work?

You are getting that error because you have a module with the same name as the function.
Change that name to say find_Purchase and everything will be fine :) See the image below...

I had the same issue myself. It turned out that I "Saved As..." another file and macros were not enabled for that file. No banner on the top appeared, but a #NAME? error was generated.
I reopened the file, enabled macros, and the problem was resolved.

Make sure you have placed the function in a Standard Module. The error message means Excel can't find the function.

When Excel opens an unkown workbook containing VBA-Code, it usually asks for macros to be enabled by the user (depending on the application settings).
If the user then enables the macros, all event-driven procedures will be started, such as auto_open or others.
Custom VBA Functions however require for a full recalculation of the workbook. Otherwise the functions return-value still is #NAME, as the calculation is only done directly after opening the workbook.
In order to work directly at the first time opening, one has to add the following line to the workbook_open event
'
' Workbook open event
Private Sub Workbook_Open()
Application.CalculateFullRebuild
End Sub

Check "Trust access to the VBA project object model" in Macro settings from Macros security

One reason for this problem is security restrictions.. I had this problem and I activate "Enable all macros" from security center, and the problem solved

I had a similar persistent problem with one of my functions when everything else seemed fine.
Open the worksheet & go to the Developer Tab. Open VBA, and back on the Developer ribbon select "View Code". See if it opens any similar Code (apart from your Module) specific to that worksheet (eg. Sheet2 (Code). I found that I had duplicated the code on the worksheet in addition to the Module. Delete the "worksheet" code. (You may need to save the workbook & re-open at this stage). When I deleted the worksheet code, the module function then worked.

In addition to checking some of the above mentioned items, you might need to specify the filename where the custom function is actually defined, e.g. cell content
=XLstart.xlsm!myCustomFunc(Arg1,Arg2)
where myCustomFunc is defined in the startup file XLstart.xlsm.
Following the Excel help for "Correct a #NAME? error":
In the formula bar, select the [suspect] function name.
In the Name Box (to the left of the formula bar), click the arrow and then select a [user-defined] function from the list that Excel suggests.
This will add the filename per the above format.
MS 2010, Windows 10.

Here's why I got that error. This answer is not provided so far.
If you have two or more workbooks (spreadsheets) open, then you may have your module under the other workbook - not the only you want to do the calculation on. This may seem impossible but ... as soon as you open the Developer/VBA code editor Excel wants to show you the structure (objects, modules, etc) of every open workbook. It's not what I expect as a developer, but there it is. So like me, you may have pressed 'Add module' and dropped the code in another workbook and worksheet.
If this is your issue, nothing mention above will work. Move your VBA module and code to the correct spreadsheet visible through this VBA code editor.

True,
I had the same (in Excel 2010) and when I migrated to Excel 2016 , the function prototype was shown, but when I completed the function, the #NAME error was shown with a pop-up... so the code was never triggered.
It turned out I had a Macro of the same name as a Sub or UDF function !
I renamed the Macro, and then it worked
Cheers

Another cause I found for the #NAME? error is that the macro workbook with the custom function has a range name the same as the function name. I changed the function name and solved the problem.

This solution applies to users with an Excel installed in another language than "United States English":
I had a similar problem when making a copy of the active workbook to duplicate it and immediately opened the copy afterwards:
Non-working code:
ThisWorkbook.SaveCopyAs NewFileName
Set wb = Workbooks.Open(FileName:=NewFileName)
This always showed me several cells with Error 2029 / "#NAME?". If I opened the Workbook "the official way" via the File-Menu it worked as expected.
I solved the issue by adding the parameter "local:=true" to the open statement:
Working code:
ThisWorkbook.SaveCopyAs NewFileName
Set wb = Workbooks.Open(FileName:=NewFileName, Local:=True)
as VBA expected english function names in my German workbook. With this parameter VBA is told directly to use the local names.
I hope that helps someone not to loose several hours, as I did...

Short answer - if the function was working before, RESTART YOUR COMPUTER.
Long answer - I had this same thing happen to me. The problem is that the function I had created had been working for months. Then one day it just started showing a #NAME error instead of working like it was before. I had tried closing all other excel workbooks and even closing excel all-together and re-opening the sheet. Nothing seemed to work. Then for kicks, I edited the code to where I knew VBA would complain that there is a compile error. Surprisingly, it didn't complain. OK... I saved and closed excel anyways and then restarted my computer.
Once rebooted, I re-opened the excel workbook. Then VBA finally gave me a compile error. So I changed my function back to the original code I had before and now the sheet is running the function like it is supposed to. No more #NAME error.
Not sure all of those steps are necessary, but simply restarting the computer seems to have fixed my issue.

Related

Invalid forward reference, or reference to uncompiled type

I'm currently using a code to update a file with a loop running through multiple sheets. Up until now, the code ran smoothly. On today's run, I encountered "run-time error '-2147319767 (80028029)' Automation error, Invalid forward reference, or reference to uncompiled type."
The error occurs on the line Workbooks("Upload.xlsm").Worksheets(branchName).Range("C7").PasteSpecial Paste:=xlPasteValues and presents itself on the 6th iteration of the loop.
I used On Error Resume Next as a temporary measure to complete the run as it was imperative to have it done at that time.
Upon completion, 3 of the iterations had failed (sixth, seventh and tenth). The three had no correlation to one another (i.e. different copy sources, values, etc) but had other iterations with the exact same copy source/values which completed successfully.
Running another copy command at a later time onto these sheets resulted in the same error. I eventually had to delete and recreate the sheet to resolve the error.
' Uploads file update
fpath = Workbooks("TEG Rates.xlsm").Worksheets("Link List").Range("E3").Value
Workbooks.Open fpath & "Upload.xlsm"
For branchNo = 21 To 37
branchName = Workbooks("TEG Rates.xlsm").Worksheets("Link List").Range("A" & branchNo).Value
branchGroup = Workbooks("TEG Rates.xlsm").Worksheets("Link List").Range("B" & branchNo).Value
' Copy/Paste Buy & Sell
Workbooks("TEG Rates.xlsm").Worksheets(branchGroup).Range("D7:G111").Copy
Workbooks("Upload.xlsm").Worksheets(branchName).Range("C7").PasteSpecial Paste:=xlPasteValues
For no = 7 To 10
Workbooks("Upload.xlsm").Worksheets(branchName).Range("D" & no).Value = "=ROUND(100/C" & no & ",6)"
Next no
Workbooks("Upload.xlsm").Worksheets(branchName).Range("D14").Value = "=ROUND(100/C14,6)"
Workbooks("Upload.xlsm").Worksheets(branchName).Range("D15").Value = "=ROUND(10000/C15,4)"
Workbooks("Upload.xlsm").Worksheets(branchName).Range("D16").Value = "=ROUND(100/C16,6)"
Workbooks("Upload.xlsm").Worksheets(branchName).Range("D19").Value = "=ROUND(100/C19,6)"
Next branchNo
Workbooks("Upload.xlsm").Close SaveChanges:=True
Application.CutCopyMode = False
While currently I am able to operate this code, my concern is that my team will encounter this whilst I'm away. What could have caused this/what can I do to prevent this from occurring? I'd be willing to provide the files if required.
My friend and I had the same issue. I enabled the "AccessibilitycplAdmin 1.0 type admin" under Tools > References (within the VBA editor), that fixed the issue in both computers
I had the same issue with a macro today.
Noticed that the error popped up when selecting a sheet using Sheets(sheet_name_var).Select.
A workaround that I've found is:
- Make a copy of the sheet the macro was having problems with,
- Delete the original sheet,
- Rename the copy to the original name.
Hope this helps.
I was having the same error caused by an issue that was potentially related, and it was helpful to create a worksheet object rather than referencing a sheet within a workbook all in one step. So, instead of:
Workbooks("Upload.xlsm").Worksheets(branchName).Range("C7").PasteSpecial
You could instead try:
Dim xlWB as Excel.Workbook
Dim xlWS as Excel.Worksheet
Dim xlRange as Excel.Range
Set xlWB = Workbooks("Upload.xlsm")
Set xlWS = xlWB.Worksheets(branchname)
Set xlRange = xlWS.Range("C7")
xlRange.PasteSpecial Paste:=xlPasteValues
Sometimes it's beneficial to break up the steps, even though it is doing the same thing.
The only way I found to solve it was:
Change the property "Load To" for all query results in the damaged Sheet to "Only Create Connection".
Make a copy of the Sheet
Delete the damaged Sheet
Rename the just created Sheet to the name of the damaged one
Change all the query results to the new Sheet in the same original location
I hope this helps.
I had a very similar issue, I have several similar excel files, all with the same code. The code ran in all excels but one, with the same error:
"run-time error '-2147319767 (80028029)' Automation error, Invalid forward reference, or reference to uncompiled type."
I was able to solve the problem by saving the corrupt excel as .xlsx instead of .xlsm, closing all excel applications, reopen the .xlsx, add the code and save as .xlsm. Now it is working...
Exactly same thing happened to me. But with a little bit more serious consequences as my dashboard was already in production.
It was really shocking as code as running smoothly just 5 mins earlier.
Here's the changes that I made -
Conditional formatting
Pivot table updates - major formatting updates
I believe some weird combination of conditional formatting over pivot table might have caused this issue.
One peculiar symptom associated with this corrupted workbook/sheet as that I was unable to see any macro in the dialogue while I was trying to assign a macro to the button.
The dialogue box was empty ! not listing any macros from any module/form/worksheet.
Tried -
Removing pivot table
Resetting formatting
Removing conditional formatting
Restarting excel
Restarting system
None of the above worked !
Next solution, as suggested by Horacio, is to duplicate and delete the corrupted sheet.
This immediately solved the issue.
Similar problem - same error. The sheet is the results of a query "Load To" table. Followed the idea from https://stackoverflow.com/users/13737858/horacio-cano. Changed "Load to" from table to Connection only; deleted the sheet; changed "Load to" to new table; refreshed query. Macro runs without error.
I solved this by removing the reference to Microsoft Scripting Runtime in Tools>References selecting "Ok" and then re-adding it again.
(Not the exactly the same situation as posted by the OP, but the same error message:)
I got the same error message while trying to delete an ActiveX element in a UserForm.
Turns out that I still had (another) user form open as a modal window in the Excel app (which was in the background because I was trying to edit it the Visual Basic Editor).
Simply closing the user form solved the issue.
Not really an answer, but my 2 cents on the matter (a comment could not fit it :))
I found that the underlaying error comes from .NET:
Exception Source: mscorlib
Exception Type: System.Runtime.InteropServices.COMException
Exception Message: Invalid forward reference, or reference to uncompiled type. (Exception from HRESULT: 0x80028029 (TYPE_E_INVALIDSTATE))
Exception Target Site: InvokeDispMethod
With that, I found that this page:
https://developercommunity.visualstudio.com/t/live-code-analysis-causes-compiler-errors-in-code/599442
System.Runtime.InteropServices.COMException : A reference to the component 'MyProjectReference' already exists in the project.
at VSLangProj.References.AddProject(Project pProject)
So it appears the error is linked to some cached file(s) used internally and language stuff.
Now if you look here : What does 'Cor' stand for?
MSCorLib.dll officially became the acronym for Multilanguage Standard
Common Object Runtime Library.
If you finally add in the mix that I was manupulating files in Excel while changing the UI Language in settings just before I got a corrupted file with the same error that the OP mentions, I would guess the error definitely has some thing to do it!...

Error when setting workbook variable - 2147352565

I have a simple code that runs upon initialization of a userform that sets a few workbook and worksheet variables so they can be used easily throughout the rest of my modules, and the references can be easily changed in one place if the file moves. I recently migrated my workbooks from my desktop to a separate server/drive, and accordingly updated the file pathways; however, when I try to run the code now I immediately get the message:
"Run-time error '-2147352565 (8002000b)': Can't move focus to the control because it is invisible, not enabled, or of a type that does not accept the focus."
This error occurs on the line
Set ReportWkbk = Workbooks("N:\ rest of file pathway here\QuaRT_Template.xlsm")
Is there anything that can be happening on the server/drive that is causing this issue? If so, is there anything I can do to fix it? I do work with other excel workbooks saved in the same location that seem to have no issue being referenced, though their references are in the workbook itself, not through Visual Basic.
The Subscript Out of Range error occurs because the Excel workbook being referenced is not open (or opening) in the same instance of Excel. You can easily reproduce the error by creating two workbooks (name one WorkBook2.xlsx) and ensuring they open in separate instances of Excel. Then run this code:
Sub OpenWkbkNames()
Dim wbk As Workbook
For Each wbk In Workbooks
Debug.Print wbk.Name
Next
'Hmm. Workbook 2 is not listed, but lets activate it and see what happens.
Workbooks("workbook2.xlsx").Activate
End Sub
You could avoid the issue by looping through the names of the workbooks open in THIS instance of Excel to ensure its available.
I've been researching Run-time error '-2147352565 (8002000b)' and found this: https://msdn.microsoft.com/en-us/library/microsoft.visualstudio.vsconstants.disp_e_badindex.aspx
Apparently, that is VS's way of saying Subscript Out of Range too. I suspect (but have no solid proof) that since the code worked locally but the issue appeared after the file was migrated to a shared drive that Windows is taking a long time to open the file so opens it in a new instance of Excel. Essentially, Excel gets impatient and decides to move on while Windows completes its task. I base this assumption on the detection logic that was added to Excel 2013 (https://blogs.office.com/2013/06/03/opening-workbooks-by-running-separate-instances-of-excel/).

Excel issue "excel 4.0 function stored in defined names"

I am trying to isolate the issue causing
Excel 4.0 function stored in defined names.
Not to bump an old thread, but I had this same issue as well and wanted to post my resolution in case anyone else experiences the same thing as myself.
My problem ended up being caused by a MySQL Excel COM add-on that was a component included in the MySQL Workbench package. Disabling that add-on caused the macro prompt to disappear when saving spreadsheets.
For me this message was caused by the MySQL For Excel COM Add-In. The message stopped appearing when I unloaded the COM Add-In.
The solution already pointed out is correct: disable the MySQL for Excel COM Add-in.
The reason for the message is that this add-in adds hidden names to the workbook. These names are not visible in the Excel Names Manager. But you can see them in the VBA Direct Window if you add this code to a workbook module:
Public Sub DEV_CheckNames()
Dim n As name
For Each n In ActiveWorkbook.Names
If Not n.Visible Then
Debug.Print n.NameLocal, n.RefersToLocal
'If you want to delete the name, uncomment this line:
'n.Delete
End If
Next
End Sub
Result (for a German instance of Excel 2013):
LOCAL_DATE_SEPARATOR =INDEX(ARBEITSBEREICH.ZUORDNEN(37);17)
LOCAL_DAY_FORMAT =INDEX(ARBEITSBEREICH.ZUORDNEN(37);21)
LOCAL_HOUR_FORMAT =INDEX(ARBEITSBEREICH.ZUORDNEN(37);22)
LOCAL_MINUTE_FORMAT =INDEX(ARBEITSBEREICH.ZUORDNEN(37);23)
LOCAL_MONTH_FORMAT =INDEX(ARBEITSBEREICH.ZUORDNEN(37);20)
LOCAL_MYSQL_DATE_FORMAT =WIEDERHOLEN(LOCAL_YEAR_FORMAT;4)&LOCAL_DATE_SEPARATOR&WIEDERHOLEN(LOCAL_MONTH_FORMAT;2)&LOCAL_DATE_SEPARATOR&WIEDERHOLEN(LOCAL_DAY_FORMAT;2)&" "&WIEDERHOLEN(LOCAL_HOUR_FORMAT;2)&LOCAL_TIME_SEPARATOR&WIEDERHOLEN(LOCAL_MINUTE_FORMAT;2)&LOCAL_TIME_SEPARATOR&WIEDERHOLEN(LOCAL_SECOND_FORMAT;2)
LOCAL_SECOND_FORMAT =INDEX(ARBEITSBEREICH.ZUORDNEN(37);24)
LOCAL_TIME_SEPARATOR =INDEX(ARBEITSBEREICH.ZUORDNEN(37);18)
LOCAL_YEAR_FORMAT =INDEX(ARBEITSBEREICH.ZUORDNEN(37);19)
These names are added to the active workbook in the moment you click on the button of the add-in (which opens the taskpane). Unfortunately, I haven't found out yet why the MySQL add-in sometimes adds these names by itself without being activated.
Added: This is a known bug in the MySQL for Excel add-in as of http://bugs.mysql.com/bug.php?id=73467
I have the same problem in Excel 2013 and was solved by unloading the MySQL Add in - I did this by going to FILE - OPTIONS - Add Ins
I ran into this warning after creating the following defined name:
Name: wsNamesArray
Refers To: =RIGHT(GET.WORKBOOK(1),LEN(GET.WORKBOOK(1))-FIND("]",GET.WORKBOOK(1)))
This formula returns an array with names for each sheet in the workbook. I was using it to return the names of various sheets (first, last, previous and next sheet).
The problem is that this formula uses the GET.WORKBOOK Excel 4 function. From what I understand this is something like a VBA macro imbedded in a function. To save that functionality the Excel workbook must be saved in a format that allows macros such as .xlsm or .xlsb (or any of several other file types).
My choices were to delete the defined name containing an Excel 4 function or to replace the defined name with a formula without the Excel 4 function,
As in ChipsLetten's answer, same solution here on my computer: On saving some (actually macro free) workbook, I get an alert "Excel 4.0 function stored in defined names", and an option to save the workbook as "macro-enabled". On de-activating the "MySQL for Excel" COM-Add-in, the alert does not appear any more.
In order to disable the "MySQL for Excel" add-in (if you ever have installed it): Tab "Developper", then button "COM Add-Ins", and you get a list of add-ins that you can enable or disable per tick-mark.
have you installed some connector for excel?, maybe that's causing the issue, just uninstall it and the error will be gone.
If you have worksheets with hidden ranges as described in domke consulting's answer, you can use the following code to remove them:
Public Sub Remove_Hidden_MySQL_Names()
Dim n As Name
For Each n In ActiveWorkbook.Names
If Not n.Visible Then
'Delete Names added by MySQL for Excel add-in
If (InStr(n.NameLocal, "LOCAL_") <> 0 And (InStr(n.NameLocal, "_FORMAT") <> 0 Or _
InStr(n.NameLocal, "_SEPARATOR") <> 0)) Then
Debug.Print "Would delete", n.NameLocal, n.RefersToLocal
'If you want to delete the name, uncomment this line:
'n.Delete
Else
Debug.Print "Keeping", n.NameLocal, n.RefersToLocal
End If
End If
Next
End Sub
For me, in 2020, this issue is caused due to the fact that you want to save it into a .xlsx format. It needs to be saved in a .xls .xlsm or .xlsb file, which are macro enabled files. .xlsm is the preferred option.

Excel VBA can't open Workbook

First: I'm using Excel 2007, but the code has to work for Excel 2003 as well.
My problem is the following: I need to access cells in a different workbook, which may be closed. The following code can be found all around the web:
Function Foo()
Dim cell As Range
Dim wbk As Workbook
Set wbk = Workbooks.Open("correct absolute path")
' wbk is Nothing here so the next statement fails.
Set cell = wbk.Worksheets("Sheet1").Range("A1")
Foo = cell.Value
wbk.Close
End Function
sadly, wbk is Nothing after the open statement (I'd love to give a better error message, but no idea how I'd do that; what I'd give for a real IDE and an useful language :/). The absolute path is correct and points to a valid excel xlsx file.
Also I assume the best way to do this, is to "cache" the workbook and not open/close it every time the function is called? Any possible problems with that (apart from having to handle the situation when the workbook is already open obviously)?
Image while stepping through:
I can reproduce this problem. It only happens to me when I attempt to paste this code into a user-defined function.
I believe this is by design (the quote is for XL 2003, but the same thing happens to me on XL 2010)
Using VBA keywords in custom functions
The number of VBA keywords you can use in custom functions is smaller than the number you can use in macros. Custom functions are not allowed to do anything other than return a value to a formula in a worksheet or to an expression used in another VBA macro or function. For example, custom functions cannot resize windows, edit a formula in a cell, or change the font, color, or pattern options for the text in a cell. If you include "action" code of this kind in a function procedure, the function returns the #VALUE! error.
http://office.microsoft.com/en-us/excel-help/creating-custom-functions-HA001111701.aspx
The only workaround I've found is to call this kind of code via a normal macro. Something like selecting the cells to apply it to, then looping over Selection or the like.
You can use this (similar to what Bruno Leite proposed, but much simpler to write):
Dim excelApp As New Excel.Application
excelApp.Visible = False
Set WB = excelApp.Workbooks.Open(FileName, xlUpdateLinksNever, True)
As UDFs are called repeatedly, you should make sure to do an excelApp.Quit before exiting the function (and a WB.close(False) before) to avoid having countless Excel instances running on your box.
I spent some thoughts on it and came to the conclusion that you cannot mess around with the workbooks of the current instance of excel while executing a UDF. On the other hand, opening a second instance of excel will do the job without interference.
To get data from Workbook without is open, you can use this, with ADO connection.
To use in Excel 2007 change this
Microsoft.Jet.OLEDB.4.0
to
Provider=Microsoft.ACE.OLEDB.12.0
and
Extended Properties=\"Excel 8.0;HDR=Yes;\
to
Extended Properties=\"Excel 12.0;HDR=Yes;\
[]'s
The workaround of putting my routine into a separate macro in the workbook module, and calling that macro from the Workbook_BeforeSave code, seems to have done the trick.
I've had a similar issue, but in my case it's a "Workbooks.Open(filename)" command at the start of a small routine embedded in Workbook_BeforeSave. VBA just skips right over the line of code as if it weren't there, it doesn't even report an Err.Code or Err.Description.
The only clue for me was that it's part of the Workbook_BeforeSave routine, and the limits with Functions above seem to indicate that could be a possible cause. So I dug around further to find more details.
It seems that Workbook_BeforeSave disables Excel from opening more files, and I guess there's a good reason for doing that, since the File > Open option is still visible in the File menu, but it can't be clicked. Strangely, the Open toolbar icon/button still works, and so whilst I can manually open the file from there, I wonder if it's because it's impossible to call this action from VBA code and that's why they allowed it?
You don't have to "Set" a cell, It's part of the workbook class (as far as I know). Just use the following...
foo = wbk.Worksheets("Sheet1").Range("A1").Value
I would suggest that you open you the new workbook upon opening the calling workbook, in the worbook_open event.
You then store the new workbook reference in a global variable.
Then the function called by your cell uses the said global variable instead of trying to open a new workbook. This way you go around the limitations.
PS : Of course global variable are to be avoided, some sort of container would be better than a direct global variable.
You can check the error in a proper way by using the following code:
filelocation = c:\whatever\file.xlsx
On Error GoTo Handler 'this is key as if the next row returns an error while opening the file it will jump to the Handler down there.
Set wkb2 = Workbooks.Open(filelocation, ReadOnly)
Handler:
MsgBox "File " & filelocation & " does not exist or cannot be reached, please review and try again"
I know that this does not answer the question (that's why I also landed in this thread, as I cannot open the file and can't understand why is that so)
Cheers,
RV

Possible to tell which workbook called a function in an Excel Add-In (xla)

I want to write a little logging function in an excel add-in that I will be calling from many different workbooks. I'd like to be able to just call it by passing only the log text, and the log function itself could handle the timestamp, workbookname, etc.
However, I cannot use either ThisWorkbook or ActiveWorkbook to determine which workbook was responsible for making the call, as Thisworkbook will return a reference to the add-in itself, whereas VBA code running in a workbook other than the workbook with active focus in Excel could make the call, but the ActiveWorkbook will return the one that has focus in the window.
Application.Caller looked like a possible solution, but this seems to work only when the function is called from a cell, not from VBA.
Is what I'm trying to do impossible?
Update
According to > 1 person, this is in fact impossible. If anyone happens to know some clever workaround please speak up.
Ok, so having read the question properly I'll try again...
So, to state the problem:
you want a routine written in an addin, that when called from vba in another workbook can work out (among other things) which workbook contains the vba that made the call, without having to pass this information explicitly.
As stated this is not possible (this is a similar question to accessing the call stack from code: something that is to my knowledge not possible)
However you can almost get what you want like this
Declare your log function like this:
Sub MyLogger(wb as Workbook, LogText as String)
Dim CallerName as String
CallerName = wb.name
' your code...
End Sub
Then wherever you call the sub use
MyLogger ThisWorkbook, "Log Text"
Not quite as good as passing nothing, but at least its always the same
To get the name of the calling workbook, use
Application.Caller.Worksheet.Parent.Name
Application.Caller returns information about how Visual Basic was called. If called from a custom function entered in a single cell, a Range object specifying that cell is returned
Having got a reference to the cell, .Worksheet.Parent.Name gives you the name of the workbook
Note that Application.Caller will return other things depending on how your function is called (see VBA help for details)
In an Add-In Function called by an Excel Worksheet Array Entered Function Call, I find that "Application.Caller.Parent.name" gives the Sheet Name (Tab Name, not sheet number).
I had the same issue when coding a custom function. Function works well, but anytime another workbook is calculated or activated, all cells using that function revert to #value. It can be very frustrating when working with multiple files using this formula.
To get the Workbook I used:
Dim CallingWb As Workbook
Set CallingWb = Application.Caller.Parent.Parent
This should work if your function is in a cell.
Too late for the original post, but might help others!

Resources