0

Consider the following code:

Sub CombineNumbersToASTring()

' force Excel to show two decimals, even when there are trailing zeros
Range("A1", "B1").NumberFormat = "0.00"

' give some values to the previously mentioned cells
Cells(1, 1).Value = 0.1
Cells(1, 2).Value = 0.2

' combine the previous two values into one cell
Cells(1, 3).Value = "(" & Cells(1, 1).Value & ", " & Cells(1, 2).Value & ")"

End Sub

The result is erroneously

0.10 0.20 (0.1, 0.2)

although it should be

0.10 0.20 (0.10, 0.20)

So, how could I retain the NumberFormat when converting to a string in Excel VBA? The CStr method seemed not to work.

(Edit: I shall also add here that in my larger code the number of decimal places is changing from cell to another, so the decimal places can't be known from beforehand when writing the VBA code.)

0

3 Answers 3

3

At least two ways you can achieve this.

  1. Use the .Text property.
    Cells(1,3).Value = "(" & Cells(1,1).Text & ", " & Cells(1,2).Text & ")"
  2. Use Formula in Cell(1,3)
    =CONCATENATE("(",TEXT(A1,"0.00"),", ",TEXT(B1,"0.00"),")")
Sign up to request clarification or add additional context in comments.

1 Comment

The first solution is suitable for my needs, and I confirm that it works like a charm. Crazy how simple the solution was. A beforehand knowledge of the decimal places is not needed with this solution. Many thanks, indeed.
1

I think you need to use Format with "0.00" around your values like:

Cells(1, 3).Value = "(" & Format(Cells(1, 1).Value, "0.00") & ", " & Format(Cells(1, 2).Value, "0.00") & ")"

1 Comment

Yes, your solution works for the question that I originally wrote. I forgot to mention that the decimal place is not static in my larger code; I have now added that to my question. But, thank you very much anyways, and +1 for a working solution for the original question. (PatricK's solution above works even with changing decimal places.)
0

Try to extend Number format range to C1 Column (Cell(1,3)): Range("A1", "C1").NumberFormat = "0.00"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.