VBA - Convert Column Values Into Negative

时间:2018-08-20 20:40:24

标签: excel vba excel-vba

Trying to convert an entire Column H in sheet Data_TC from positive values to negative values. The range consists of H1:LastRow

I have LastRow as a module as follows,

Option Explicit

Function LastRow(sh As Worksheet)
    On Error Resume Next
    LastRow = sh.Cells.Find(What:="*", _
                            After:=sh.Range("A1"), _
                            LookAt:=xlPart, _
                            LookIn:=xlValues, _
                            SearchOrder:=xlByRows, _
                            SearchDirection:=xlPrevious, _
                            MatchCase:=False).Row
    On Error GoTo 0
End Function

And here is the code I am working with to convert the values:

Worksheets("Data_TC").Activate
Application.ScreenUpdating = False
Application.CutCopyMode = False

For Each cell In Sheets("Data_TC").Range("H" & LastRow(Sheets("Data_TC")))
  If cell.Value > 0 Then
    cell.Value = cell.Value * -1
  End If
Next cell

When I run it will convert random values into negative values but that is about it. Any idea why?

3 个答案:

答案 0 :(得分:2)

尝试:

For Each myCell In Sheets("Data_TC").Range("H1:H" & Sheets("Data_TC").Range("H" & Rows.Count).End(xlUp).Row)
    If myCell.Value > 0 Then
        myCell.Value = myCell.Value * -1
    End If
Next myCell

这将遍历H列中的所有单元,并将正数转换为负数

答案 1 :(得分:2)

您需要具有一个 range 个单元格。您要做的是仅检查具有值的最后一个单元格。
尝试更改:

For Each cell In Sheets("Data_TC").Range("H" & LastRow(Sheets("Data_TC")))

收件人:

For Each cell In Sheets("Data_TC").Range("H1:H" & LastRow(Sheets("Data_TC")))

答案 2 :(得分:0)

根据我的测试,您可以尝试以下VBA代码:

Option Explicit
Sub convertValue()
Dim cell As Range
Worksheets("Data_TC").Activate
Application.ScreenUpdating = False
Application.CutCopyMode = False
For Each cell In Sheets("Data_TC").Range("H1:H" & LastRow(Sheets("Data_TC")))
  If cell.Value > 0 Then
    cell.Value = cell.Value * -1
  End If
Next cell
End Sub
Function LastRow(sh As Worksheet)
    On Error Resume Next
    LastRow = sh.Cells.Find(What:="*", _
                        After:=sh.Range("A1"), _
                        LookAt:=xlPart, _
                        LookIn:=xlValues, _
                        SearchOrder:=xlByRows, _
                        SearchDirection:=xlPrevious, _
                        MatchCase:=False).Row
    On Error GoTo 0
End Function

希望它对您有所帮助。