VBA循环根据相邻单元

时间:2018-06-15 15:07:42

标签: vba excel-vba excel

我对VBA非常陌生,而且我无法理解如何在一个循环中完成2个任务。非常感谢你的帮助。

我已经能够根据第3列中的数据更改第2列中的数值,但我不明白如何将负值的字体更改为红色。

表格的大小每月根据当月的天数变化(如果重要)。谢谢!

Dim AQRng As Range, Cel As Range, p_AQend As Object
Set p_AQend = Range("AQ2").End(xlDown)
Set AQRng = Range("AQ2", p_AQend)

For Each Cel In AQRng
  If Cel.Value <> 0 Then
   If Cel.Offset(0, 1).Text = "Negative" Then
    Cel.Value = Abs(Cel.Value) * -1
  ElseIf Cel.Offset(0, 1) <> "Negative" Then
    Cel.Value = Abs(Cel.Value)
  End If
 End If
Next Cel

enter image description here

5 个答案:

答案 0 :(得分:1)

我希望我能正确理解这一点。您要更改值的Cel(乘以-1)是您要更改颜色的Cel,是否正确?

如果是的话,

For Each Cel In AQRng
    If Cel.Value <> 0 Then
        If Cel.Offset(0, 1).Text = "Negative" Then
            Cel.Value = Abs(Cel.Value) * -1
            Cel.Font.ColorIndex = 3
        ElseIf Cel.Offset(0, 1) <> "Negative" Then
            Cel.Value = Abs(Cel.Value)
        End If
    End If
Next Cel

我在你的负面条件下添加了一行:

Cel.Font.ColorIndex = 3.Font.ColorIndex会将字体颜色更改为您选择的颜色 - ColorIndex = 3会将其更改为红色。

Read Here获取有关您可以使用ColorIndex选择的各种字体颜色的详细信息。

答案 1 :(得分:1)

试试这个:我在你的负面情况下添加了Cel.Font.Color = RGB(255, 0, 0)

Dim AQRng As Range, Cel As Range, p_AQend As Object
Set p_AQend = Range("AQ2").End(xlDown)
Set AQRng = Range("AQ2", p_AQend)

For Each Cel In AQRng
  If Cel.Value <> 0 Then
   If Cel.Offset(0, 1).Text = "Negative" Then
    Cel.Value = Abs(Cel.Value) * -1
    Cel.Font.Color = RGB(255, 0, 0)

  ElseIf Cel.Offset(0, 1) <> "Negative" Then
    Cel.Value = Abs(Cel.Value)
  End If
 End If
Next Cel

答案 2 :(得分:1)

这是一个无循环的解决方案:

   With Range("AR2", cells(Rows.Count, "AR").End(xlUp))
        .Replace what:="Positive", replacement:="", lookat:=xlWhole
        With .SpecialCells(xlCellTypeBlanks)
            .Offset(, 1).Value = .Offset(, -1).Value
            .Offset(, -1).FormulaR1C1 = "=ABS(RC[2])"
            .Value = "Positive"
        End With

        .Replace what:="Negative", replacement:="", lookat:=xlWhole
        With .SpecialCells(xlCellTypeBlanks)
            .Offset(, 1).Value = .Offset(, -1).Value
            .Offset(, -1).FormulaR1C1 = "=-ABS(RC[2])"
            .Value = "Negative"
            .Font.Color = vbRed
        End With
        .Offset(, -1).Value = .Offset(, -1).Value
        .Offset(, 1).ClearContents
    End With

这假设可以编写AS列,但代码很容易更改以使用不同的帮助程序

答案 3 :(得分:0)

试试这个:

Sub Test()
    Dim rng As Range, cl As Range

    Set rng = Range("AQ2:QA" & Range("A2").End(xlDown).Row)

    For Each cl In rng
        If cl.Value <> 0 Then
            If cl.Offset(0, 1) = "Negative" Then
                cl = Abs(cl) * -1
                cl.Font.Color = vbRed
            Else
                cl = Abs(cl)
            End If
        End If
    Next cl
End Sub

答案 4 :(得分:0)

将负值更改为红色的最快方法。

    Columns("AQ:AQ").NumberFormat = "0.00_ ;[Red]-0.00 "