Excel VBA:导入CSV日期为dd / mm / yyyy [英] Excel VBA: importing CSV with dates as dd/mm/yyyy

查看:144
本文介绍了Excel VBA:导入CSV日期为dd / mm / yyyy的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我明白这是一个相当常见的问题,但我还没有找到可靠的解决方案。



我有一个csv文件中的数据,第一列格式化日/月/年。当我使用Workbooks.OpenText打开它默认为mm / dd / yyyy,直到它确定它认为是月份超过12,然后恢复为dd / mm / yyyy。



这是我的测试代码,它试图强制它为xlDMYFormat,我也尝试了文本格式。我知道这个问题只适用于* .csv文件,而不是* .txt,但这不是一个可以接受的解决方案。

 选项基础1 
Sub TestImport()

Filename =test.csv

Dim ColumnArray(1到1,1到2)

ColumnsDesired = Array(1)
DataTypeArray = Array(xlDMYFormat)

'填充fieldinfo的数组
对于x = LBound(ColumnsDesired)到UBound(ColumnsDesired)
ColumnArray(x,1)= ColumnsDesired(x)
ColumnArray(x,2)= DataTypeArray(x)
下一个x

Workbooks.OpenText文件名:=文件名,DataType:= xlDelimited,逗号:= True,FieldInfo:= ColumnArray

End Sub

test.csv包含:

 日期
11/03/2010
12/03 / 2010
13/03/2010
14/03/2010
15/03/2010
16/03/2010
17/03/2010


解决方案

我有与.OpenText方法相同的问题。我的区域设置是英语 - 澳大利亚而不是新西兰。
我发现另一个线程建议使用.open,
http://www.pcreview.co.uk/forums/date-format-error-csv-file-t3960006.html
所以我试过
Application.Workbooks.Open文件名:= strInPath,格式:= xlDelimited,本地:= True
,它的工作。


I understand this is a fairly common problem, but I'm yet to find a reliable solution.

I have data in a csv file with the first column formatted dd/mm/yyyy. When I open it with Workbooks.OpenText it defaults to mm/dd/yyyy until it figures out that what it thinks is the month exceeds 12, then reverts to dd/mm/yyyy.

This is my test code, which tries to force it as xlDMYFormat, and I've also tried the text format. I understand this problem only applies to *.csv files, not *.txt, but that isn't an acceptable solution.

Option Base 1
Sub TestImport()

Filename = "test.csv"

Dim ColumnArray(1 To 1, 1 To 2)

ColumnsDesired = Array(1)
DataTypeArray = Array(xlDMYFormat)

' populate the array for fieldinfo
For x = LBound(ColumnsDesired) To UBound(ColumnsDesired)
    ColumnArray(x, 1) = ColumnsDesired(x)
    ColumnArray(x, 2) = DataTypeArray(x)
Next x

Workbooks.OpenText Filename:=Filename, DataType:=xlDelimited, Comma:=True, FieldInfo:=ColumnArray

End Sub

test.csv contains:

Date
11/03/2010
12/03/2010
13/03/2010
14/03/2010
15/03/2010
16/03/2010
17/03/2010

解决方案

I had the same problem with the .OpenText method. My Regional Settings are English - AU rather than NZ. I found another thread that suggested using .open, ( http://www.pcreview.co.uk/forums/date-format-error-csv-file-t3960006.html ) so I tried that Application.Workbooks.Open Filename:=strInPath, Format:=xlDelimited, Local:=True and it worked.

这篇关于Excel VBA:导入CSV日期为dd / mm / yyyy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆