首页 > 解决方案 > 使范围内的所有单元格值为负

问题描述

我目前正在尝试做两件事。

1)交换两列中的值。这些值最初被列为经度,然后是纬度。我希望首先列出 Latitude,并在代码的第一部分完成此操作。

2) 问题领域。经度作为正值发布,但需要为负值,因为负值将提供正确的位置。我找到了答案

将列正值转换为负值 VBA

使范围内的所有值都为负值,并包括该范围内的空白单元格值。我尝试更改代码以满足我的需求,但出现运行时错误“1004”-对象“_Global”的方法“范围”失败。

如果有人可以帮助我,将不胜感激!

Public Sub CorrectLongitude()

    Dim tempRange As Variant
    Dim Longitude As Range
    Dim Latitude As Range

    '1) Swap Longitude and Latitude

    Worksheets("Raw_Data").Activate

    Set Longitude = Worksheets("Raw_Data").UsedRange.Columns("AR")
    Set Latitude = Worksheets("Raw_Data").UsedRange.Columns("AS")

    tempRange = Longitude.Cells
    Longitude.Cells.Value = Latitude.Cells.Value
    Latitude.Cells.Value = tempRange

    '2) Make Longitude values negative
    'Variable "Latitude is used as Latitude now contains the longitude values from above

    For Each Latitude In Range(Range("AS"), Range("AS" & Rows.Count).End(xlUp))

        If Not IsEmpty(Latitude.Value) Then If IsNumeric(Latitude.Value) Then Latitude.Value = -Abs(Latitude.Value)

        Next

End Sub

标签: excelvba

解决方案


您实际上是在调用 range Range(Range("AS"),Range("AS1000"))。您缺少第一行参考。

For Each Latitude In Range(Range("AS1"), Range("AS" & Rows.Count).End(xlUp))

编辑:个人建议,不要使用For each Latitude,因为您在Latitude其他地方定义了范围,这可能会使 VBA/您自己感到困惑。我通常会这样做Dim cel as Range // For each cel in ...。如果您尝试Latitude.Cells.ValueFor循环之后使用,结果将与您之前调用它时大不相同。

For each cel in Latitude假设使用UsedRangeinSet Latitude = ...包括您需要的所有使用的行,您也许可以这样做。


推荐阅读