This is my first post as a blogger - at the age of 70! So please be generous.
When I started with Excel VBA some decades ago I did it - like many - wit the macro recorder. It took me some time until I realized the shortcomings of statements like
In the Worksheet object write
When I started with Excel VBA some decades ago I did it - like many - wit the macro recorder. It took me some time until I realized the shortcomings of statements like
.... Range("A2").Value = ...
When the design of the sheet is changed, a row above or a column to the left is inserted this code points to the wrong cell. Better - though still not perfect will be .... Range("celTest").Value = ....
Cell A2 hast been given the name "celTest" and this name will point to the right cell no matter of a sheet's design change. However, with many meaningful names (I never address any range without) typos become more likely an names become difficult to remember. Ugly VB errors are the annoying result. By far the best way is to make each named range a property of the sheet as follows.In the Worksheet object write
Public Property Get celTest() As Range: Set celTest = Me.Range("celTest"): End Property
Within this module assigning the cell a value now looks like
Me.celTest.Value = ....And from within another module
wsTest.celTest.Value = ...I should note here that I never ever use ActiveSheet. ... ThisWorkbook.Sheets("Test"). .... or even worse .Sheets(1) ... All these methods are pure poison for design changes. Working with the Worksheet's object name is by far the best way for design independent code. You will love this approach last but not least because of VBE's autocomplete which comes into effect whi ch makes it very easy to find the correct range. And last but not least: In this specific case the ultimate solution will be
Public Property Get Test() As String: Test = Me.Range("celTest").Value: End Property
Public Property Let Test(ByVal s As String): Test = Me.Range("celTest").Value = s: End Property
Once you'started with this you will realize the power of it regarding better, cleaner and bug free code.
Kommentare
Kommentar veröffentlichen