基于位置和字体颜色的乘法单元格

时间:2015-09-24 21:39:21

标签: excel-vba vba excel

这对你们来说应该是一个相当容易的问题,但我似乎无法在网上找到解决方案。我的数据集中有三列,其中负值显示为红色而不是前面的“ - ”符号。如果它们在E,I和M列中并且它们的字体颜色是-16776961,我需要将这些值乘以-1。我已经看到一些代码接近但我不知道如何修改它们来做所需的事情:

If Range("E5:E100").Value = 1 Then Range("").Value = Range("B2").Value * 10 

我还以为我可以这样做:

For Each c In r
    With c
        If Not IsError(.Value) Then
            Select Case .Color
                 Case -16776961
                     .Value = .Value * -1
            End Select
        End If
    End With
Next c

但我不确定具体的语法是什么。

提前感谢任何给予此镜头的人。

另一次尝试:

Range("U1").Select
ActiveCell.FormulaR1C1 = "-1"

Rows("4:4").Select
Selection.AutoFilter

Range("U1").Select
Selection.Copy

ActiveSheet.Range("$A$4:$X$43").AutoFilter Field:=5, _
                                           Criteria1:=RGB(232, 88, 88), _
                                           Operator:=xlFilterFontColor
Range("E11:E52").Select
Selection.SpecialCells(xlCellTypeVisible).Select
Selection.PasteSpecial Paste:=xlPasteValues, _
                       Operation:=xlMultiply, _
                       SkipBlanks:=False, _
                       Transpose:=False

1 个答案:

答案 0 :(得分:0)

如果NumberFormat不是[Blue]#,##0.00_);[Red](#,##0.00);0.00,则此代码切换红色数字

Option Explicit

Public Sub convertNegatives()
    Const FIRST_ROW     As Long = 4
    Const CONVRT_COL    As String = "E I M" 'Columns to process

    Dim ws As Worksheet, ur As Range, cc As Variant, c As Variant, clr As Long

    clr = RGB(232, 88, 88)
    Set ws = ActiveSheet
    cc = Split(CONVRT_COL)

    With ws.UsedRange
       Set ur = .Range(ws.Cells(FIRST_ROW - 1, 1), .Cells(.Rows.Count - 1, .Columns.Count))
    End With

    Application.ScreenUpdating = False
    For Each c In cc
       convertColorFilter ur.Columns(c), clr    'Option 1
       'convertColorLoop ur.Columns(c), clr     'Option 2
    Next
    Application.ScreenUpdating = True
End Sub

选项1 (自动筛选)

Private Sub convertColorFilter(ByRef col As Range, ByVal clr As Long)
    Dim cel As Range, vr As Range

    col.Parent.AutoFilterMode = False
    col.AutoFilter Field:=1, Criteria1:=clr, Operator:=xlFilterFontColor

    Set vr = col.Cells.SpecialCells(xlCellTypeVisible)

    If vr.Count > 0 Then
        For Each cel In vr
            If cel.Font.Color = clr Then cel.Value2 = cel.Value2 * -1
        Next
    End If: col.Parent.AutoFilterMode = False
End Sub

选项2 (For循环)

Private Sub convertColorLoop(ByRef col As Range, ByVal clr As Long)
    Dim cel As Range
    If col.Columns.Count = 1 Then
        For Each cel In col.Cells
            If cel.Font.Color = clr Then cel.Value2 = cel.Value2 * -1
        Next
    End If
End Sub