Checking for variable

L

Lee

I have tried a docvariable but can't seem to get it to
work...
I tried:
If ActiveDocument.Variables("new").Value = 0 Then
FrmOutwardLetter.Show
End If
and I had a variable in the document named "new".

This is probably wrong... Don't know how to do this as I'm
new at VBA. Can anyone help with some code please?

Thanks
 
J

Jezebel

Your code is correct. You'll get an error if the variable doesn't exist. The
form will display if the variable exists and is equal to zero. But you
should deal with the possibility of error:

Const pVarName as string = "New"
Dim pNewDoc as boolean

'Show the form unless the variable is defined and equals FALSE
pNewDoc = TRUE 'Default
on error resume next
pNewDoc = ActiveDocument.Variables(pVarName)
on error goto 0

If pNewDoc then
FrmOutwardLetter.Show
ActiveDocument.Variables(pVarName) = FALSE
end if
 
G

Guest

Hi there.

Here you have a function returning nothing if the Variable
does not esist:
Public Function GetDocumentVariable( _
ByVal strVariableName As String) As String
Dim aVar As Variable
Dim strValue As String

strValue = ""
' Loop through all the document variables (if
needed)
For Each aVar In ActiveDocument.Variables

' Check name of variable
If LCase(aVar.Name) = LCase(strVariableName) Then
' Copy value
strValue = aVar.Value

' Break out of loop
Exit For
End If

' Destroy reference to variable
Set aVar = Nothing
Next

' Return value
GetDocumentVariable = strValue
 
P

Peter Hewett

Hi <[email protected]>

Rather than iterating the Document Variables collection I'd use something like this:

Public Function GetDocVarValue(ByVal DocVarName As String)

' Return the Document Variables value or vbNullString if it does not exist
On Error Resume Next
GetDocVarValue = ActiveDocument.Variables(DocVarName).Value
On Error Resume Next
End Function

You don't need to worry about the case of the Document Variable name.

HTH + Cheers - Peter
 
P

Peter Hewett

Hi Peter Hewett

Ooops sorry, of course the declaration should have been:

Public Function GetDocVarValue(ByVal DocVarName As String) As String

Cheers - Peter


Hi <[email protected]>

Rather than iterating the Document Variables collection I'd use something like this:

Public Function GetDocVarValue(ByVal DocVarName As String)

' Return the Document Variables value or vbNullString if it does not exist
On Error Resume Next
GetDocVarValue = ActiveDocument.Variables(DocVarName).Value
On Error Resume Next
End Function

You don't need to worry about the case of the Document Variable name.

HTH + Cheers - Peter

HTH + Cheers - Peter
 

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