mohamed maghrabi
mohamed maghrabi

Reputation: 33

Lining up values to the right

if i have some values scattered that i want to line up to the right enter image description here

Can this be achieved using formulas ,or VBA ?

Thanks

Upvotes: 1

Views: 54

Answers (1)

VBasic2008
VBasic2008

Reputation: 54807

Align Data

Before

enter image description here

After

enter image description here

Option Explicit

Sub AlignData()
        
    Dim ws As Worksheet: Set ws = ActiveSheet ' improve!
    
    With ws.UsedRange
        
        Dim rCount As Long: rCount = .Rows.Count
        Dim cCount As Long: cCount = .Columns.Count
        If rCount + cCount = 2 Then Exit Sub ' one cell only
        
        Dim Data As Variant: Data = .Value
        
        Dim cValue As Variant
        Dim r As Long
        Dim sc As Long
        Dim dc As Long
        
        For r = 1 To rCount
            dc = cCount
            For sc = cCount To 1 Step -1
                cValue = Data(r, sc)
                If Len(CStr(cValue)) > 0 Then
                    Data(r, sc) = Empty
                    Data(r, dc) = cValue
                    dc = dc - 1
                End If
            Next sc
        Next r
        
        .Value = Data
        
    End With
    
    MsgBox "Data aligned.", vbInformation
        
End Sub

Upvotes: 2

Related Questions