VBA打开.CSV文件

时间:2016-12-20 13:12:47

标签: excel vba excel-vba csv

我是VBA的新手,我正在尝试按下按钮打开分号CSV文件并存储在“数据”工作表中。但是,即使我设置分隔符,输出仍然如下所示:

Tempo;Deslocamento;Carga(s);(mm);(N)        
0,00000;"-4 99846";"-28 53779"
0,01000;"-4 98967";"-28 41018"
0,02000;"-4 97449";"-28 29775"
0,03000;"-4 95374";"-28 23815"
0,04000;"-4 92851";"-28 20709"
0,05000;"-4 89975";"-28 12254"
0,06000;"-4 86842";"-27 99132"
0,07000;"-4 83488";"-26 16241"
0,08000;"-4 79954";"-20 51597"
0,09000;"-4 76271";"-10 26401"
0,10000;"-4 72469";"5   76869"
0,11000;"-4 68570";"30  21154"
0,12000;"-4 64606";"51  30509"
0,13000;"-4 60600";"62  65891"
0,14000;"-4 56565";"66  18559"
0,15000;"-4 52529";"65  00101"
0,16000;"-4 48475";"61  91677"

以下是我的代码:

'turn off screen updating
Application.ScreenUpdating = False

'initialize variables    
Dim NewWorkbook As Variant
Dim AnalysisWorkbook As Variant
Dim OpenWorkbook As Variant

'current filename    
AnalysisWorkbook = ActiveWorkbook.Name

'ask the user for the file name to open    
NewWorkbook = Application.GetOpenFilename("CSV (*.csv), *.csv")

'check for cancel button    
If NewWorkbook = False Then Exit Sub

'open the text file with the OpenText method   
Workbooks.OpenText Filename:=NewWorkbook, Origin:=xlWindows, StartRow:=1, _
    DataType:=xlDelimited, TextQualifier:=xlTextQualifierDoubleQuote, ConsecutiveDelimiter:=False, _
    Tab:=True, Semicolon:=True, Comma:=False, Space:=False, Other:=False, OtherChar:=False, _
    FieldInfo:=Array(1, 1), DecimalSeparator:=",", ThousandsSeparator:="."
OpenWorkbook = ActiveWorkbook.Name

'copy data
Windows(OpenWorkbook).Activate
Columns("A:H").Select
Selection.Copy

'paste data    
Workbooks(AnalysisWorkbook).Worksheets("Data").Activate
Columns("A:H").Select
Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False

'close data file    
Workbooks(OpenWorkbook).Activate
Range("A1").Select
Selection.Copy
Workbooks(OpenWorkbook).Close SaveChanges:=False

'turn on screen updating
Application.ScreenUpdating = True

我从我在这里使用的另一个程序中复制了这个代码,打开了.txt文件并尝试修改。但似乎我错过了一些东西。

1 个答案:

答案 0 :(得分:1)

假设我们打开文件并尝试解析它"手工":

Sub parser()
    Close #1
    s = "C:\TestFolder\matheus.csv"
    Open s For Input As #1

   j = 1
   Do While Not EOF(1)
      Line Input #1, TextLine
      ary = Split(TextLine, ";")
      i = 1
      For Each a In ary
        Cells(j, i).Value = a
      i = i + 1
      Next a
    j = j + 1
   Loop

   Close #1
End Sub

上面的代码逐行获取数据并使用" ; "作为分隔符。结果如下:

enter image description here

请注意,这只是部分成功。 mm 字段和 N 字段似乎已合并。