A New Conundrum

G

Greg Maxey

Today in separate correspondence I was informed that document variables are
always "string" and I should assign a Long variable value to a string.

I have this situation:

Dim pCcnt As Long

On Error Resume Next
pCcnt = ActiveDocument.Variables("pCcnt").Value
On Error GoTo 0

If pCcnt < 0 Or pCcnt > UBound(pCycleCols) Then
pCcnt = 0
End If

Later on the following code is used
..HighlightColorIndex = CycleCols(pCcnt)
pCcnt = pCcnt + 1
ActiveDocument.Variables("pCcnt").Value = pCcnt

The purpose of the variable is to "remember" the next highlight color to be
used when the document is closed and then reopened.

pCcnt has to be a number to work in the array (at least I think so). If
document variables are "strings" and I should mix the tow, what should I do?

Thank you.
 
J

Jezebel

If your doc variable is always read from and written to a code variable of a
given data type, you don't need to do anything. Let VBA handle the
conversion for you. Although strictly speaking it's correct that DocVariable
is stored as a string (vartype(Doc.Variables(x)) = vbString), the Variables
collection appears designed to handle the value argument as a variant. Or at
least, its own string conversions work correctly to that end. The
documentation makes no mention of data types, and gives an example of
assigning a long without conversion. I haven't tested this in detail, but
I've stored dates, booleans, and longs in doc variables without converting
and without any problem.

If you DO want to convert, then you'd use

Variables.Add Name:="pCcnt", Value := CStr(pCcnt)

and

pCcnt = CLng(Variables("pCcnt"))

but, at least in this case, there's no need.
 
J

Jonathan West

If you want more precise control over the conversion between different types
of variables than is offered by the default conversions provided by VBA,
then you can use the conversion functions such as CLng(), CStr(), CBool()
etc to convert data.
 

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