VBA function refuses to return a string

52 Views Asked by At
Function getExcelFolderPath2() As String

    Dim fso As FileSystemObject
    Set fso = New FileSystemObject
    
    Dim fullPath As String
    
    fullPath = fso.GetAbsolutePathName(ThisWorkbook.Name)
    
    fullPath = Left(fullPath, Len(fullPath) - InStr(1, StrReverse(fullPath), "\")) & "\"
    
    getExcelFolderPath2 = fullPath

End Function

Even though fullPath gets a string with relevant contents, getExcelFolderPath2 ends up being empty. This is from a break on that last line, just to be clear:

enter image description here

There must be something really simple that I'm missing, but I can't see it.

I expected to have getExcelFolderPath2 be equal to fullPath.

2

There are 2 best solutions below

1
FunThomas On BEST ANSWER

This is more a comment than an answer, but too long:

I guess the function works correctly. It works for me (and at least for user Dominique).

Could it be that you set the breakpoint on the statement getExcelFolderPath2 = fullPath and then look to the Locals Window? When the runtime hits that statement and breaks, the statement itself is not executed.

enter image description here

But if you step to the end of the function, the function value is set

enter image description here

Call the function from the immediate window to check:

enter image description here

2
Dominique On

For me, this is working fine.

How do you call that function? I have simplye put =getExcelFolderPath2() inside a cell (like "B3").

Oh, did you add the Microsoft Scripting Runtime in your list of VBA references? (VBA editor, "Tools" menu, "References" item)