简体   繁体   中英

VBA change negative range to positive

I'm trying to change the negative values to positive based on a dynamic range. By dynamic I mean that the row number might change.

For example

rowStart = 10
rowEnd   = 20

From these I need to change the values in this range to positive. I'm trying the following but I'm getting an error:

Range("K" & rowStart & ":K" & rowEnd).Value = _
    Abs(Range("K" & rowStart & ":K" & rowEnd).Value)

The error I get is: Run-time error '13': Type mismatch

Any ideas on how to make this work?

You can't do it in whole that way.

Either Loop:

For i = rowStart to rowEnd
    ActiveSheet.Range("K" & i).Value = Abs(ActiveSheet.Range("K" & i).Value)
Next i

Or you can set it using Evaluate:

ActiveSheet.Range("K" & rowStart & ":K" & rowEnd).Value = Evaluate("INDEX(ABS(" & Range("K" & rowStart & ":K" & rowEnd).Address & "),)")

You must loop over the items :

Sub ksdjfh()
    Dim r As Range

    rowStart = 10
    rowEnd = 20

    For Each r In Range("K" & rowStart & ":K" & rowEnd)
        r.Value = Abs(r.Value)
    Next r
End Sub

Try this:

rowStart = 10
rowEnd = 20
For Each myCell In Range("K" & rowStart & ":K" & rowEnd)
    myCell.Value = Abs(myCell.Value)
Next

Does your number format allow for simply removing the negative signs (ie hyphens )?

Dim rowStart As Long, rowEnd As Long
rowStart = 10
rowEnd = 20
With ActiveSheet
    .Range("K" & rowStart & ":K" & rowEnd).Replace What:="-", Replacement:="", LookAt:=xlPart
End With

Place in an array and loop over the items (might be faster than updating the range if it's a big range):

Sub Test()

    Dim rowStart As Long, rowEnd As Long
    Dim rRange As Range
    Dim vRange() As Variant
    Dim vItem As Variant
    Dim R As Long

    rowStart = 10
    rowEnd = 20

    With Sheet1
        'Define the range.
        Set rRange = .Range(.Cells(rowStart, 1), .Cells(rowEnd, 1))
    End With
    vRange = rRange

    'Loop through the values - consider R to mean Row.
    For R = 1 To UBound(vRange, 1)
        vRange(R, 1) = Abs(vRange(R, 1))
    Next R

    rRange.Value = vRange

End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM