我需要帮助在excel中进行某种动态色彩缩放。 我需要缩放一列,但要基于另一列的值。实际上,每当第一列的值更改时,我都需要将颜色缩放比例重置为第二列。
答案 0 :(得分:1)
除非我有误解,否则似乎您想要特定于值的条件格式。
Value1
的所有行在列B中都应具有自己的色标。Value2
的所有行在B列中都应具有自己的色标。一种实现此目的的方法可能涉及VBA,并且包含以下内容。
Value1
和Range.AutoFilter
一起获得A列包含某个值(例如Range.SpecialCells
)的所有行。Range.FormatConditions.Add
添加条件格式。Worksheet_Change
事件和某些条件IF
逻辑,可以使A列发生更改时运行代码。假设您对A列中的值进行了排序(它们似乎出现在您共享的文档中),则代码可能类似于:
Option Explicit
Private Sub ApplyValueSpecificConditionalFormatting(ByVal columnToFormat As Variant)
Dim filterRangeIncludingHeaders As Range
Set filterRangeIncludingHeaders = Me.Range("A1", Me.Cells(Me.Rows.Count, columnToFormat).End(xlUp))
Dim filterRangeExcludingHeaders As Range
Set filterRangeExcludingHeaders = filterRangeIncludingHeaders.Offset(1).Resize(filterRangeIncludingHeaders.Rows.Count - 1)
filterRangeExcludingHeaders.Columns(columnToFormat).FormatConditions.Delete ' Prevent redundant/obsolete rules.
' In your case, values in column A appear to be sorted. So we can assume that whenever
' the current row's value (in column A) is not the same as the previous row's value (in column A),
' that we have a new, unique value -- for which we should add a new colour scale in column B.
' A better, more explicit way would be to build a unique "set" of values (possibly accomodating
' type differences e.g. "2" and 2), and loop through the set.
Dim inputArray() As Variant
inputArray = filterRangeIncludingHeaders.Value
Dim rowIndex As Long
For rowIndex = (LBound(inputArray, 1) + 1) To UBound(inputArray, 1)
If inputArray(rowIndex, 1) <> inputArray(rowIndex - 1, 1) Then
filterRangeIncludingHeaders.AutoFilter Field:=1, Criteria1:=inputArray(rowIndex, 1)
Dim cellsToFormat As Range
On Error Resume Next
Set cellsToFormat = filterRangeExcludingHeaders.Columns(columnToFormat).SpecialCells(xlCellTypeVisible)
On Error GoTo 0
If Not (cellsToFormat Is Nothing) Then
' Probably best to put the below in its own function.
With cellsToFormat.FormatConditions.AddColorScale(colorscaleType:=2)
.SetFirstPriority
.ColorScaleCriteria(1).Type = xlConditionValueLowestValue
.ColorScaleCriteria(1).FormatColor.Color = vbWhite
.ColorScaleCriteria(2).Type = xlConditionValueHighestValue
.ColorScaleCriteria(2).FormatColor.Color = 8109667
End With
End If
Set cellsToFormat = Nothing
End If
Next rowIndex
Me.AutoFilterMode = False
End Sub
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Column = 1 Then
ApplyValueSpecificConditionalFormatting columnToFormat:=2 ' or B
ApplyValueSpecificConditionalFormatting columnToFormat:="C" ' or 2
End If
End Sub
代码应放置在工作表的代码模块中(在A列中包含值,在B列中包含色标)。