Best way to get color back after using s = str(thecolor) to store as hex?

title says it all.
I use s = str(thecolor) to get the hex value.

There doesn’t seem to be a one-stop method to turn that hex value back into an actual color.
How have other people done this efficiently?

You can cast an integer to a color.

dim c as color
dim s as string = "&hFF0000"
dim n as integer

n = val(s)
c = color(n)

Or all on one line, using CType to convert the double that val() returns to an integer value.

c = color(ctype(val(s), integer))

[quote=155991:@Jeff Tullin]title says it all.
I use s = str(thecolor) to get the hex value.

There doesn’t seem to be a one-stop method to turn that hex value back into an actual color.
How have other people done this efficiently?[/quote]

s = str(mycolor) dim c as color = RGB(val("&h"+mid(s,5,2)),val("&h"+mid(s,7,2)),val("&h"+mid(s,9,2)),val("&h"+mid(s,3,2)))

[quote=155993:@Tim Hare]You can cast an integer to a color.

[code]
dim c as color
dim s as string = “&hFF0000”
dim n as integer

n = val(s)
c = color(n)

[code]
Or all on one line, using CType to convert the double that val() returns to an integer value.

c = color(ctype(val(s), integer)) [/quote]

Nice. I had tried casting but somehow did not succeed, so I turned to RGB.

Thank you :slight_smile:

Works nicely ,Tim. Thanks

Confused the pants off me because str() adds a leading 00 to my &cFF0099 colour
Then the casting turns it back into a color where an extra 00 is on the end.
Must be alpha value (which Im not using)

[quote=155996:@Jeff Tullin]Works nicely ,Tim. Thanks

Confused the pants off me because str() adds a leading 00 to my &cFF0099 colour
Then the casting turns it back into a color where an extra 00 is on the end.
Must be alpha value (which Im not using)[/quote]

It is the alpha value. Notice the 01 in the example I posted.

Note: this gets a bit messed up if you store and then retrieve the string value from an XML element.
XML adds a problematic “amp;” into the string which needs to be stripped back out before the casting occurs.

like this:

dim k as string = Properties.GetAttribute("Thecolor") k = replace(k,"amp;","") Thecolor = color(ctype(val( k), integer))

Normal. XML & stands for ampersand as HTML entity.

See List of XML and HTML character entity references - Wikipedia

I would tend to prefer this that replaces the whole HTML entity

k = replace(k,"&","&")

But the end result is the same.

Variant!

dim v as variant = colorAsString Return v.colorValue