View Single Post
 
Old 11-08-2023, 06:44 AM
gmaxey gmaxey is offline Windows 10 Office 2019
Expert
 
Join Date: May 2010
Location: Brasstown, NC
Posts: 1,601
gmaxey is just really nicegmaxey is just really nicegmaxey is just really nicegmaxey is just really nicegmaxey is just really nice
Default

vivka,


You thought correctly. It is optional. All variables that are implicitly declared are of type Variant. Variables of type Variant require more memory resources than most other variables. While in the case we have at present, it probably doesn't mater but generally your code will be more efficient if you declare variables explicitly and with a specific data type.


Code:
Sub ScratchMacro()
'A basic Word Macro coded by Gregory K. Maxey
'Illustrates an implicit variable (not declared using a declaration statement e.g., Dim)
  Set oRng = ActiveDocument.Range
  oRng.Select
lbl_Exit:
  Exit Sub
End Sub
Sub ScratchMacroII()
'A basic Word Macro coded by Gregory K. Maxey
'Illustrates an two explicit variables 1) The compilier resolves as variant 2) Is declared as variant
Dim oRng
Dim oRng2 As Variant
  Set oRng = ActiveDocument.Range
  'Notice after you type oRng. that the properties and methods of the Word range object do not appear.
  oRng.Select
  Set oRng2 = ActiveDocument.Range
  'Notice after you type oRng2. that the properties and methods of the Word range object do not appear.
  oRng2.InsertAfter "more text"
lbl_Exit:
  Exit Sub
End Sub
Sub ScratchMacroIII()
'A basic Word Macro coded by Gregory K. Maxey
'Illustrates an explicit variable set to a specific data type
Dim oRng As Range
  Set oRng = ActiveDocument.Range
  'Notice after you type oRng. that the properties and methods of the Word range object do not appear.
  oRng.Select
  'Note: I typically use the OptionExplicit statement at the top of my code window to force me to
  'explicity declare all variables.  For example, your code would not compile because you have
  'an implicit variable "Para"
lbl_Exit:
  Exit Sub
End Sub
Sub ScratchMacroIV()
'A basic Word Macro coded by Gregory K. Maxey
'Why to I used the lbl_Exit and Exit Sub lines.
  MsgBox "Mainly as a matter of style and practice." & vbCr + vbCr _
      & "I find myself updating a lot of code written by others weeks, years or decaces ago" _
      & " and I use those two lines as my marker that I have finished revising a procedure."
  MsgBox "Secondarily it is my escape clause from a procedure." & vbCr + vbCr _
      & "One of my earlier mentors told me that while it didn't matter anymore (if it ever did) he just never liked to reach" _
      & " the End Sub line in procedure." _
      & " I also use it to escape err handling labels and as a exit point after error handling."
  On Error GoTo Err_Handler
  Err.Raise 6
lbl_Exit:
  Exit Sub
Err_Handler:
  Resume lbl_Exit
End Sub
__________________
Greg Maxey
Please visit my web site at http://www.gregmaxey.com/
Reply With Quote