简体   繁体   English

VBA Querytables在Excel中将文本转换为数字

[英]VBA Querytables converting text to number in Excel

I have a simple VBA code that fetches stock prices from google finance. 我有一个简单的VBA代码,可从Google Finance获取股价。 When I get the results back in the column, excel is converting rows into numbers. 当我将结果返回到列中时,excel会将行转换为数字。 These are comma separated values that look like 189,209.97,210.03,209.97,210,300 and it works fine (stays as text). 这些是逗号分隔的值,看起来像189,209.97,210.03,209.97,210,300,并且可以正常工作(以文本形式保留)。 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. 但是有时值是190,210,210,210,210,000,在这种情况下excel将其转换为数字(不再有逗号),这使我的下游处理混乱,因为我需要将文本转换为列。 Any way to force excel through VBA to accept all values as text only? 有什么方法可以通过VBA强制Excel仅接受所有值作为文本? 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 如果可能,我发现更容易以正确的格式获取数据,即在数字周围添加等号和引号以使Excel直接将其作为文本加载

Ref : https://superuser.com/questions/307496/how-can-i-set-excel-to-always-import-all-columns-of-csv-files-as-text 参考: 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. 其他方法如果您有权访问创建CSV的源,则可以更改CSV语法。 Enclose every value with double quotation marks and prefix an equal sign like ="00001" 每个值都用双引号引起来,并在等号前面加上=“ 00001”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM