VBA将负值移至下一个单元格并添加总计

时间:2017-08-17 05:36:59

标签: excel vba excel-vba

宏应该将负值移到右边的单元格并使其为正。 如果右侧单元格中已有值,则宏应将它们加在一起。

我可以使用下面的代码完成第一步。

Sub tested()    
    Dim rng As Range
    Dim lrow As Integer
    Dim nextcell As Long

    With ActiveSheet
    lrow = .Range("L" & Rows.Count).End(xlUp).Row        
        For Each rng In .Range("L3:L" & lrow)    
           If rng.Value < 0 Then    
             rng.Offset(0, -1).Value = Abs(rng.Value)
             rng.Value = ""
           End If    
        Next rng    
    End With
End Sub

2 个答案:

答案 0 :(得分:2)

&#34;将负值移到右边的单元格&#34;表示rng.Offset(0, 1)而非rng.Offset(0, -1)

所以你可以尝试这样的事情......

Dim rng As Range
Dim lrow As Long

With ActiveSheet
lrow = .Range("L" & Rows.Count).End(xlUp).Row
    For Each rng In .Range("L3:L" & lrow)
        If rng.Value < 0 Then
            rng.Offset(0, 1).Value = rng.Offset(0, 1).Value + Abs(rng.Value)
            rng.Value = ""
        End If
    Next rng
End With

答案 1 :(得分:0)

试试这个

Sub tested()
    Dim rng As Range
    Dim lrow As Integer
    Dim nextcell As Long
    With ActiveSheet
    lrow = .Range("B" & Rows.Count).End(xlUp).Row
        For Each rng In .Range("B1:B" & lrow)
            If rng.Value < 0 Then
                If IsNumeric(rng.Offset(0, -1).Value) Then
                    rng.Offset(0, -1).Value = rng.Offset(0, -1).Value + Abs(rng.Value)
                Else
                    rng.Offset(0, -1).Value = Abs(rng.Value)
                End If
                rng.Value = ""
            End If
        Next rng
    End With
End Sub