VBA将负面范围改为正面

时间:2017-03-15 15:24:46

标签: excel vba excel-vba

我正在尝试根据动态范围将负值更改为正值。动态我的意思是行号可能会改变。

例如

rowStart = 10
rowEnd   = 20

从这些我需要将此范围内的值更改为正数。我正在尝试以下但是我收到了一个错误:

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

我得到的错误是:运行时错误'13':类型不匹配

关于如何使这项工作的任何想法?

5 个答案:

答案 0 :(得分:6)

你不可能以这种方式做到这一点。

循环:

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

或者您可以使用Evaluate:

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

答案 1 :(得分:4)

您必须循环播放

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

答案 2 :(得分:3)

试试这个:

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

答案 3 :(得分:3)

您的数字格式是否允许简单地删除负号(即连字符)?

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

答案 4 :(得分:1)

放置一个数组并循环遍历项目(如果范围较大,可能比更新范围更快):

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