Variable

J

John

Hi

How can I check if the value of a variable has been set? Right now if check
the value of my variable like this;
ActiveDocument.Variables.Item("UniqueID").Value, I get an "Object has been
deleted" error.

Thanks

Regards
 
T

Thomas Winter

John said:
Hi

How can I check if the value of a variable has been set? Right now if check
the value of my variable like this;
ActiveDocument.Variables.Item("UniqueID").Value, I get an "Object has been
deleted" error.

Thanks

Regards

Basically, you need to trap that error or look through all the variables in
the collection. Here is some code that should help you out. You can now do
this:

If GetVariable(ActiveDocument, "UniqueID") = "12345" Then ......


Public Sub SetVariable(oDocument As Word.Document, sName As String, sValue
As String)

On Error GoTo ErrorHandler

Dim oVariable As Word.Variable

Set oVariable = LocateVariable(oDocument, sName)

If Not oVariable Is Nothing Then

oVariable.Value = sValue

Else

oDocument.Variables.Add sName, sValue

End If

Exit Sub

ErrorHandler:

' Maybe raise an error here...

End Sub

Public Function GetVariable(oDocument As Word.Document, sName As String) As
String

On Error GoTo ErrorHandler

Dim oVariable As Word.Variable

Set oVariable = LocateVariable(oDocument, sName)

If Not oVariable Is Nothing Then

GetVariable = oVariable.Value

Else

GetVariable = ""

End If

Exit Function

ErrorHandler:

GetVariable = ""

End Function

Public Function LocateVariable(oDocument As Word.Document, sName As String)
As Word.Variable

On Error GoTo ErrorHandler

Dim oVariable As Word.Variable

For Each oVariable In oDocument.Variables

If StrComp(oVariable.Name, sName, vbTextCompare) = 0 Then

Set LocateVariable = oVariable

Exit Function

End If

Next

Set LocateVariable = Nothing

Exit Function

ErrorHandler:

Set LocateVariable = Nothing

End Function
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top