Excel VBA - 错误解析日期,处理字符串
问题描述:
我遇到的问题涉及到一个CSV文件,我正试图解析为一个Excel电子表格。Excel VBA - 错误解析日期,处理字符串
数据的例子如下: -
01/02/2015,MXP,0.4,150.00,Producing design document, 64111258
02/06/2015,IHM,0.8,210.00,"Maximilian dolce, lorem ipsum", 64111258
02/06/2015,AXSP,0.6,250.00,"Magnificent, thanks very much", 64111258
目前,这是我使用的解析数据的代码: -
Sub OpenCSV()
Dim filePath As String
Dim intChoice As Integer
Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = False
intChoice = Application.FileDialog(msoFileDialogOpen).Show
rowIndex = 0
If intChoice <> 0 Then
filePath = Application.FileDialog(_ msoFileDialogOpen).SelectedItems(1)
Open filePath For Input As #1
Do Until EOF(1)
Line Input #1, LineFromFile
LineItem = Split(LineFromFile, ",")
Sheets("Sheet2").Cells(11, 2).Offset(rowIndex, 0).Value = LineItem(0) ' Date
Sheets("Sheet2").Cells(11, 2).Offset(rowIndex, 1).Value = LineItem(1) ' Code
Sheets("Sheet2").Cells(11, 2).Offset(rowIndex, 2).Value = LineItem(2) ' Hours
Sheets("Sheet2").Cells(11, 2).Offset(rowIndex, 3).Value = LineItem(3) ' Cost
Sheets("Sheet2").Cells(11, 2).Offset(rowIndex, 4).Value = LineItem(4) ' Description
rowIndex = rowIndex + 1
Loop
Close #1
End If
End Sub
的问题如下: -
- 日期(如2015年6月2日)被解析并转换到excel单元格的日期将最终为2015年6月2日。这不会一致发生,而是随机发生在数据集内的各种日期。
- CSV分隔符4将最终被错误地解析,其中“”在数据中,以及逗号;因此数据没有正确地转换到相关单元。
如何纠正这些错误?
答
Dim arr() As String
Dim newDate As Date
arr = Split(LineItem(0), "/")
newDate = DateSerial(Year:=arr(2), Month:=arr(1), Day:=arr(0))
然后使用
Sheets("Sheet2").Cells(11, 2).Offset(rowIndex, 0).Value = newDate
答
像这样的东西应该为你工作:
Sub tgr()
Dim wb As Workbook
Dim wsDest As Worksheet
Dim sFilePath As String
Dim aData As Variant
sFilePath = Application.GetOpenFilename("CSV Files, *.csv", MultiSelect:=False)
If sFilePath = "False" Then Exit Sub 'Pressed cancel
Set wb = ActiveWorkbook
Set wsDest = wb.Sheets("Sheet2")
Application.ScreenUpdating = False
With Workbooks.Open(sFilePath)
aData = .Sheets(1).Range("A1", .Sheets(1).Cells(.Sheets(1).Rows.Count, "E").End(xlUp)).Value
.Close False
End With
Application.ScreenUpdating = True
With wsDest.Range("B11").Resize(UBound(aData, 1), UBound(aData, 2))
.Value = aData
.Resize(, 1).NumberFormat = "mm/dd/yyyy" 'Can set date format here, change to dd/mm/yyyy if needed
End With
End Sub
+0
如何将逻辑运算符应用于正在复制的数据?如果它是非线性的,那么我只想复制某些单元格,而不是所有行中的a1和E之间的所有单元格。我宁愿一行一行地遍历行。那可能吗? – Resurgent
答
最有可能的,问题是您的数据和Windows区域设置的日期格式不匹配。有几个方式来处理这个
- 更改您的Windows区域设置,以便它们匹配
- 更改文件类型到
*.txt
文件。然后使用Workbooks.OpenText
方法,该方法允许您指定日期列数据类型。 - 创建一个数据连接,这也将允许你这样做。只要确保你不继续创建QueryTables。它已经在那里,删除并重新创建或刷新。
以下是演示QueryTable方法的一些代码。在Excel的界面,这将是该数据►获取外部数据►从文本选项
Option Explicit
Sub OpenCSV()
Dim filePath As String
Dim intChoice As Integer
Dim WS As Worksheet
Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = False
intChoice = Application.FileDialog(msoFileDialogOpen).Show
If intChoice <> 0 Then
filePath = Application.FileDialog(_
msoFileDialogOpen).SelectedItems(1)
Set WS = Worksheets("sheet2")
With WS.QueryTables
'If it exists, either delete and re-import or refresh
If .Count > 0 Then
Range(.Item(1).Destination.Address).CurrentRegion.Delete
.Item(1).Delete
End If
End With
'
With WS.QueryTables.Add(Connection:="TEXT;" & filePath, Destination:=WS.Range("$B$11"))
.Name = "New Text Document"
.FieldNames = True
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.TextFilePromptOnRefresh = False
.TextFilePlatform = 437
.TextFileStartRow = 1
.TextFileParseType = xlDelimited
.TextFileTextQualifier = xlTextQualifierDoubleQuote
.TextFileConsecutiveDelimiter = False
.TextFileTabDelimiter = True
.TextFileSemicolonDelimiter = False
.TextFileCommaDelimiter = True
.TextFileSpaceDelimiter = False
'make sure format argument matches format in the csv file
.TextFileColumnDataTypes = Array(xlDMYFormat)
.TextFileTrailingMinusNumbers = True
.Refresh BackgroundQuery:=False
End With
End If
End Sub
如果导入CSV直接到Excel(没有VBA)你有同样的问题吗?如果你没有问题,你可以试着记录宏并修改它以满足你的需求。如果这不起作用,我可能会帮助解决第二个问题。但是你真的需要弄清楚什么时候#1碰巧确定它发生的原因。 – Benjamin