简体   繁体   中英

VBA Querytables converting text to number in Excel

I have a simple VBA code that fetches stock prices from google finance. When I get the results back in the column, excel is converting rows into numbers. These are comma separated values that look like 189,209.97,210.03,209.97,210,300 and it works fine (stays as text). But once in a while the value is 190,210,210,210,210,000 in which case excel turns it into a number (no more commas), which messes up my downstream processing because I need to convert text to columns. Any way to force excel through VBA to accept all values as text only? Here's what the code looks like:

With DataSheet.QueryTables.Add(Connection:="URL;" & qurl, Destination:=DataSheet.Range("a1"))
        .BackgroundQuery = True
        .TablesOnlyFromHTML = False
        .Refresh BackgroundQuery:=False
        .SaveData = True
End With

将范围更改为所需的范围。

DataSheet.Range("A1").NumberFormat = "@"

If possible, I found easier to get the data in the correct format ie add a equal sign and quotation around the number to make Excel load it as text directly

Ref : https://superuser.com/questions/307496/how-can-i-set-excel-to-always-import-all-columns-of-csv-files-as-text

Additional methods If you have access to the source which creates your CSV, you can alter the CSV syntax. Enclose every value with double quotation marks and prefix an equal sign like ="00001"

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