Excel – Add property to existing VBA class


I would like to do something like add a nice-to-Excel-functions Name property to the WorkBook class. Is there a good way to do this?

More detailed problem: In VBA you can assign a formula to a range in an Excel worksheet. I want to do so, and I want my formula to refer to a second workbook, which is an object called wb in my code. I then use wb.Name in assigning a formula to a range.

The problem arises when wb.Name has a single-quote in it. Then you wind up with something like this:

=MONTH('[Ryan's WB]Sheet1'A1)

in the spreadsheet, which fails because the single-quote in the workbook name matches to the first single-quote.

What I would like is a FunName property for the WorkBook class that replaces all single-quotes in the Name property with two single-quotes and returns that. Then the above formula would properly wind up looking like

=MONTH('[Ryan''s WB]Sheet1'A1)

Best Solution

You don't need to make a separate class to extend the workbook class. You can add properties to the existing ThisWorkbook class module, like this:

Public Property Get FunName() As String

    FunName = Replace(Me.Name, "'", "''")

End Property

Then you call ThisWorkbook.FunName to get your cleaned up name. However, this code has to exist in the workbook at hand. If you want it to work on any workbook, your function is the way to go.