سؤال

I have a userform in Excel 2003 which contains some MSForms.Label controls. I want to set the .BackColor property of each of these controls such that they match the color of some individual cells on a worksheet.

To do this I am reading the .Interior.Color property of those cells, converting it to hex and using that value to set the .BackColor property of the Label objects.

My problem is that the value coming out of .Interior.Color is almost always incorrect the first time it is read. I have tested this by running the following command in the VBA editor immediate window:

Print Hex([sourceCell].Interior.Color)

This command almost always gives the wrong value the first time round, but gives the correct value from the second time onwards. If I change the fill color of [sourceCell] and run the command again it will do the same thing, i.e. wrong value first time, right value second time onwards.

The cells in question are all filled with colors from the chart lines/fills color selection (i.e. the two bottom rows you can see in Excel's "Format Cells" dialog under the "Patterns" tab). These colors have been modified by me to give a custom set of colors and, tellingly, the "wrong" values seem to match Excel's defaults for the customized range of color picks (i.e. the default chart line/fill colors you get when you start a new workbook).

Has anyone else experienced this behaviour/have a workaround? When I try to read the values twice at runtime it doesn't work, i.e. it doesn't switch to the correct value. The code must be stopped and the userform reloaded to force the "correct" values to come out.

هل كانت مفيدة؟

المحلول

Kludge/workaround via Application.OnTime.

If I run the userform prep code to set the label objects' backcolors with the userform hidden, then set the main code to run from an immediate OnTime event (making sure to re-run the prep code as part of the OnTime) then I can force Excel to give me the correct "second time round" values when showing the form.

نصائح أخرى

This works for me:

MyForm.MyControl.BackColor = Range(myrange).Interior.Color

.Interior.Color returns a Variant containing the RGB of the sampled range.

.Interior.ColorIndex always returns -4140 or something weird, probably because .ColorIndex is peculiar to Excel2003's color limitations.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top