New Excel Forum

This forum has been moved to TeachExcel.com

Ask all future questions in the New Excel Forum.

ExcelKey

Decimal Place in Macor

Macros, VBA, Excel Automation, etc.

Decimal Place in Macor

Postby richmond23 » Mon Jan 23, 2012 2:48 pm

I have borrowed this macro which works fine, but I need to specify that each value in the result has two decimal places. I don't know any VBA

Sub Combine()
Dim J As Integer

If Selection.Cells.Count > 1 Then
For J = 2 To Selection.Cells.Count
Selection.Cells(1).Value = _
Selection.Cells(1).Value & Chr(10) & _
Selection.Cells(J).Value
Selection.Cells(J).Clear
Next J
End If
End Sub
  • 0

richmond23
Rookie
 
Posts: 2
Joined: Jan 23, 2012
Reputation: 0

Re: Decimal Place in Macor

Postby Sisyphus » Mon Jan 23, 2012 10:53 pm

Hi,
This code should do the job:
Code: Select all
Option Explicit

Public Sub Combine()

    Dim J As Integer
   
    With Selection
        If .Cells.Count > 1 Then
            With .Cells(1)
                .NumberFormat = "@"
                .HorizontalAlignment = xlRight
                .Value = FormattedValue(.Cells(1))
            End With
            For J = 2 To .Cells.Count
                .Cells(1).Value = .Cells(1).Value & Chr(10) _
                                    & FormattedValue(.Cells(J))
                .Cells(J).Clear
            Next J
        End If
    End With
End Sub

Private Function FormattedValue(ByRef Cell As Range) As String

    Const NumFormat As String = "0.00"
    FormattedValue = Format(Cell.Value, NumFormat)
End Function

You can change the Constant NumFormat to something else (like "#,##0.00" if you want a thousands separator), and you can change the HorizontalAlignment to either xlLeft or xlCenter, if you don't like the alignment I thought you wanted. :D
  • 0

Have a great day! :D

Sisyphus
I do this for "honour and country" - much less of the latter, actually.
If I helped you, award points, plenty of them.
If I bored you, deduct points for being too long-winded. (I know, :lol)
Sisyphus
Former Moderator
 
Posts: 4454
Joined: Dec 7, 2011
Location: Shanghai
Reputation: 203
Excel Version: 2010

Re: Decimal Place in Macro

Postby richmond23 » Tue Jan 24, 2012 8:15 am

Thanks Sisyphus,
Your code worked perfectly.
  • 0

richmond23
Rookie
 
Posts: 2
Joined: Jan 23, 2012
Reputation: 0


Return to Macros and VBA Questions

Who is online

Users browsing this forum: Google [Bot] and 121 guests