Option Explicit
Sub SaveValueInDefinedName()
' ============================================
' Save a value in a Defined Name
' ============================================
' Constant string for the defined name we are adding
Const szVersion As String = "WorkbookVersion"
' Constant string for the equal sign
Const szEqual As String = "="
Dim nmVersionName As Name
Dim szReferVal As String
' ========================================================================
' If the name doesn't exist, we create it and set the initial value to 1
On Error Resume Next
Set nmVersionName = ThisWorkbook.Names(szVersion)
If Err.Number > 0 Then
Names.Add szVersion, 1
' ========================================================================
Else
' ========================================================================
' if our name exists, we need to increment the value in it by 1
' to do this, we parse the name's RefersTo value:
szReferVal = Replace(Names(szVersion).RefersTo, szEqual, Empty)
' Reset the name to refer to our new value
Names(szVersion).RefersTo = szEqual & CLng(szReferVal) + 1
' ========================================================================
End If
' Explicitly clear memory
Set nmVersionName = Nothing
End Sub
|