While Excel functions are localized, the corresponding methods in the object model library are not - having different members per localization would mean a different build version for every possible localization, and then support and debugging would be unfathomably chaotic. Not to mention, some locales use non-ANSI characters, which the VBE could have a hard time displaying correctly.
Application.WorksheetFunction
is early-bound - that means the compiler knows what it's looking at, so when you type the dot in WorksheetFunction.
, you get a list of all members of that object; Compactar
(or any other localized worksheet function name) isn't in that list - hence the "object does not support this property or method" compile error.
Rule of thumb, when you're coding against an early-bound object, the list of members you get when you type the .
derefencing operator is the list of everything you can legally do with that object. There are cases where sometimes members are hidden (you can make them visible in the Object Browser; F2 and right-click anywhere, select "show hidden members"), and cases where late-bound members are tacked-on at run-time on an extensible COM interface, but generally speaking, if it's not in the list of members, it's not a legal member to call.
If you used the late-bound equivalent, your code would compile - and blow up at run-time with error 438 instead (the late-bound / run-time equivalent of the compile-time error you're getting):
cell = Application.Compactar(cell) '<~ error 438 at run-time
You're looking for the Trim
worksheet function... but note that VBA has its own Trim
function, so you don't even need to get WorksheetFunction
involved for this.
Note that you are implicitly assigning to the default member of the Range
class here. More explicit code would be like this:
cell.Value = Trim(cell.Value) ' fully-qualified: VBA.Strings.Trim
But, this assumes there is no worksheet error - if any cell
contains e.g. #VALUE!
or #REF!
, then this would raise a type mismatch error. Always validate the type of cell values before treating them as a String
, as a Date
, or any Double
or otherwise numeric value - the IsError
function can be used to avoid working with a Variant/Error
value and accidentally coercing it into a String
:
If Not IsError(cell.Value) Then cell.Value = Trim(cell.Value)