简体   繁体   中英

EXCEL VBA: Format existing numeric cells based on value range

Am trying to run VBA on certain columns (ex: M, N, U, V...) to format the values based on their range.

I currently have:

    Private Sub Worksheet_Change(ByVal Target As Range)
  If Not Intersect(Target, Range("U:W")) Is Nothing Then
    If Target.Value < -1000000 Then
        Target.NumberFormat = "#,###.0,, ""M"""
    ElseIf Target.Value <= -1000 Then
        Target.NumberFormat = "#,###.0, ""K"""
    ElseIf Target.Value < 1000 Then
        Target.NumberFormat = "### """""
    ElseIf Target.Value < 1000000 Then
        Target.NumberFormat = "#,###.0, ""K"""
    ElseIf Target.Value < 1000000000 Then
      Target.NumberFormat = "#,###.0,, ""M"""
    ElseIf Target.Value < 1000000000000# Then
      Target.NumberFormat = "#,###.0,,, ""B"""

    End If
  End If
End Sub

Unfortunately, this isn't working on values already entered. However, if I click in each cell and then hit return, if formats correctly.

QUESTION: How would I go about formatting the values that are already there?

Thank you

Looks like the Target is only the range that changed: 在此处输入图片说明 https://msdn.microsoft.com/en-us/vba/excel-vba/articles/worksheet-change-event-excel

You'll probably have to write a sub that will loop through the other data, or just "edit" the cells once and the macro will work going forward.

EDIT:

How about looping through the columns and calling your function?:

Sub OneTimeLoop()
    Dim rng as Range, cell as Range

    set rng = Range("U:V")

    For Each cell in rng
        Worksheet_Change cell
    Next cell
End Sub

I think, you need Precedents property, which will retrieve all cells a current cell is dependent upon.

Say, you have:

  1. in A1 cell: 1
  2. in A2 cell: =A1+1

Then the following code will show $A$1 :

Sub F()
    MsgBox Range("A2").Precedents(1).Address
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