简体   繁体   English

使用宏将csv中的datetime值复制到excel中

[英]copy datetime value from csv into excel using macro

I'm trying to open a list of csv file and copy the data into different spreadsheets of a excel file. 我正在尝试打开csv文件列表并将数据复制到excel文件的不同电子表格中。 My script is as follows 我的脚本如下

Sub importcsv()
    Dim strFile As String
    Dim strCSV As String
    strFile = "D:\15049"
    strCSV = "A4260512_ECRec.csv"
    Workbooks.Open Filename:=strFile & "\" & strCSV
    Range("A1").CurrentRegion.Copy Destination:=Workbooks("test 150302.xlsm").Sheets("test2").Range("A1")
    Workbooks(strCSV).Close
End Sub

The problem I have is in my csv file there is one colume of date time data (dd/mm/yyyy hh:mm), when copying those to excel, some are copied in the right order, some are not. 我遇到的问题是在我的csv文件中有一个日期时间数据(dd / mm / yyyy hh:mm),当将它们复制到excel时,有些是按照正确的顺序复制,有些则不是。 For example, 31/3/1990 is copied exactly but 1/4/1990 is copied as 4/1/1990. 例如,完全复制31/3/1990但复制1/4/1990为4/1/1990。 In my region setting, date format is set as d/mm/yyyy. 在我的区域设置中,日期格式设置为d / mm / yyyy。

Anyone has any idea? 任何人有任何想法? Please help. 请帮忙。

Thanks, 谢谢,

Have you tried setting the number format for the area to be copies and to be pasted? 您是否尝试过设置要复制和粘贴的区域的数字格式?

Worksheets("Sheet1").Columns("A").NumberFormat = "YYYY/MM/DD"

range and rows 范围和行

Worksheets("Sheet1").Range("A17").NumberFormat = ""
Worksheets("Sheet1").Rows(1).NumberFormat = "hh:mm:ss"

You will need to specify the column as being in DMY format, at the time you open the file. 在打开文件时,您需要将列指定为DMY格式。 You can do this in one of two ways 您可以通过以下两种方式之一完成此操作

  1. Add a connection to a QueryTable -- this done manually would be using the Data Ribbon / Get External Data tab /From Text 添加到QueryTable的连接 - 这是手动完成的将使用数据功能区/获取外部数据选项卡/从文本
  2. Change the file suffix to .txt and then use the Workbooks.OpenText method. 将文件后缀更改为.txt ,然后使用Workbooks.OpenText方法。

Both of the above provide options to specify that the date column format is DMY. 以上两者都提供了指定日期列格式为DMY的选项。

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

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