Different color but same color index in Excel VBA

后端 未结 2 817
囚心锁ツ
囚心锁ツ 2021-01-06 11:24

I used the code below to get color index of cell in Excel.

Original Link

Function ConditionalColor(rg As Range, FormatType As String) As Long
  \'Ret         


        
2条回答
  •  滥情空心
    2021-01-06 12:12

    Edit: My previous answer does not solve your problem, but I think it may still be relevant to someone asking the same question.

    The problem you are seeing stems from the use of the Colorindex property instead of something more specific like Color.

    For a thorough explanation between the two, you can refer to this address: http://msdn.microsoft.com/en-us/library/cc296089(v=office.12).aspx

    Essentially, there are only 57 possible color index values, but far more available colors. The color index refers to the index in a given palette. You happened to stumble upon two colors that have the same index. To have your program function as expected, you should update colorindex references to color. Without making the change you will continue to have confusing results.


    Previous answer: If you are using conditional formatting that infers the cell whose value should be applied, then when the UDF checks to determine if the conditional formatting is true it will usually defer to the current cell.

    For instance, if your conditional formatting formula is something like:

    =MOD(ROW(),2)=1

    Every time the code hits:

    frmlaR1C1 = Application.ConvertFormula(frmla, xlA1, xlR1C1, , ActiveCell)
    frmlaA1 = Application.ConvertFormula(frmlaR1C1, xlR1C1, xlA1, xlAbsolute, cel)                      
    boo = Application.Evaluate(frmlaA1) 
    

    It will evaulate based upon the current active cell instead of the cell for which the conditional formatting is applied.

    I did a little experimentation, but depending on how frequently you need to utilize the code I think the best result may be to enhance the formula. This would not solve all the issues, but you could try inserting the following just before the first ConvertFormula call:

    frmla = Replace(frmla, "()", "(" & cel.Address & ")")
    

    Which solves it for using Row() or Column().

    If this doesn't completely solve your issue, we'll need to see your conditional formatting formulas.

提交回复
热议问题