0

I have some data that i pull from a couple of Oracle databases into Excel via a VBA macro. Some of the columns have data (numbers), afaik, stored as text. I need to convert these "wrongly" formatted data to numbers so that i can do calculations on it, however i cant figure out how to do this effectively using VBA. Furthermore only some of the data is stored as text (columns K-Q are formatted incorrectly, see picture below).

Currently im using this loop to convert the data:

Sub convertTextToNumbers(ByVal sColumnHeader As String)
    Dim col As Range, c As Range
    Dim colIndexNumber As Integer, lastUsedRow As Integer

    colIndexNumber = findColumnIndexNumber(sColumnHeader)

    lastUsedRow = ActiveSheet.Cells(Rows.Count, colIndexNumber).End(xlUp).Row

    Set col = Range(Cells(2, colIndexNumber), Cells(lastUsedRow, colIndexNumber))

    For Each c In col
        c.Value = c.Value
    Next c
End Sub

Is this the most effective way to do it? Can i convert using SQL? The SQL-query im using is simply:

SELECT * FROM table_name

Also converting by choosing another formatting does not work.

Thanks!


Data wrongly formatted is in columns K-Q:

https://i.sstatic.net/N93D8.png

5
  • 2
    use the to_number sql function to convert the columns needed. Commented Sep 17, 2015 at 15:47
  • just wondering why don't you make an ODBC connection and use it in Excel? Commented Sep 17, 2015 at 16:11
  • What should the formats be in K - N? Commented Sep 17, 2015 at 16:18
  • OldProgrammer i think this is exactly what i need. I also found the to_date and to_timestamp functions user206168 i am pulling the data from an ODBC connection, giving me the above MatthewD the formats in K - N and P - Q are supposed to be timestamps. If i do eg. =K10+K11 it will work, however =SUM(K10:K11) does not work. Commented Sep 17, 2015 at 16:26
  • You should be able to pull them as a timestamp with to_timestamp. Note if you use todate you may have to include the timestamp IE 2015-01-01 59:59:59. If not you can apply the timestamp to the cells using the number format. Commented Sep 17, 2015 at 16:38

1 Answer 1

1

Use number format on the columns.

Columns("K:Q").Select
Selection.NumberFormat = "0.00"

Or more programmatic

Private Sub formatNumbers()
    Dim ws As Excel.Worksheet

    Set ws = Application.ActiveSheet
    ws.Range("K:Q").NumberFormat = "0.00"

End Sub

Any format you see in the range format menu can be applied this way.

enter image description here

Sign up to request clarification or add additional context in comments.

2 Comments

Are you applying it before you write the value to the cell?
No it is applied afterwards

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.