Excel VBA – 分析date,处理string错误

我遇到的问题涉及一个CSV文件,我正在寻求parsing为一个Excel电子表格。

数据的一个例子如下:

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 

目前,这是我用来parsing数据的代码:

 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 

问题如下:

  1. date,如2015年6月2日,分析和调换到Excel单元格将结束为06/02/2015。 这不会一致发生,而是随机发生在数据集内的各种date。
  2. CSV分隔符4将最终被错误地parsing,其中“”在数据中,以及逗号; 因此数据没有被正确地转换到相关单元。

我怎样才能纠正这些错误?

像这样的东西应该为你工作:

 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 

这个问题很可能是数据的date格式与Windows区域设置之间的不匹配。 几种方法来处理这个

  • 更改您的Windows区域设置,使它们匹配
  • 将文件types更改为*.txt文件。 然后使用Workbooks.OpenText方法,它允许您指定date列数据types。
  • 创build一个数据连接,这也将允许你这样做。 只要确保你不继续创buildQueryTables。 它已经在那里,删除和重新创build,或刷新。

以下是演示QueryTable方法的一些代码。 在Excel GUI中,这将是数据►获取外部数据►从文本选项


 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 

  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