2017-07-07 59 views
0

我有40个不同的excel数据文件(data1.csv〜data40.csv)具有相同的格式。我试图根据从这40个文件中读取的所有数据生成一个图表。 我的想法是,创建一个新的临时.csv文件(tempOut.csv),我将其中依次复制并粘贴从每个文件中读取的所有数据,最后使用该临时文件中的数据生成图形。VBA复制并粘贴数据跳过第一行

问题是,每个文件都有标题行(ID,名称,val1,val2 ,,,,)。当我从每个文件复制数据时,我需要删除此行,或者跳过此行并复制,然后将其粘贴到临时.csv文件中,除第一个文件外。

如何使用我写的代码实现这一点? 这里是我的代码:

Dim thisFile As String 'input file name 
Dim outFile As String 'output file name 
Dim dataRead As String 'containing data copied and pasted 
outFile = "tempOut.csv" 
Open outFile For Output As #1 
For i = 1 To 40 
    thisFile = "C:\datafolder\data" + CStr(i) + ".csv" 
    Open thisFile For Input As #2 
    Do Until EOF(2)   'read until the end of the file 
    Line Input #2, dataRead 
    Print #1, dataRead 
    Loop 
    Close #2 
Next i 
Close #1 

此代码创建一个新的文件,并复制和粘贴,以便从每个文件的所有数据。但是,每次都会复制并粘贴标题行。我添加了if语句,当我= 1时,它读取所有内容。但我不知道如何复制跳过第一行,从第二个文件读取到最后一个文件。

任何人都可以帮助我吗?先谢谢你。

Add: 例如,data1.csv看起来像
| ID |名称| Val1 | Val2 | ...
| 0 | aaaa | 1 | 2 | ...
| 1 | bbbb | 3 | 4 | ...
| 2 | cccc | 5 | 6 | ...

and data2.csv看起来像
| ID |名称| Val1 | Val2 | ...
| 3 | dddd | 7 | 8 | ...
| 4 | eeee | 9 | 9 | ...
| 5 | ffff | 7 | 5 | ...

然后,合并的tempOut.csv应该看起来像
| ID |名称| Val1 | Val2 | ...
| 0 | aaaa | 1 | 2 | ...
| 1 | bbbb | 3 | 4 | ...
| 2 | cccc | 5 | 6 | ...
| 3 | dddd | 7 | 8 | ...
| 4 | eeee | 9 | 9 | ...
| 5 | ffff | 7 | 5 | ...

回答

0

你需要保持跟踪存在,你在哪里,在一个文件中的第一个文件,所以添加变量“j”和“K”像下面的代码:

Dim thisFile As String 'input file name 
    Dim outFile As String 'output file name 
    Dim dataRead As String 'containing data copied and pasted 

    outFile = "tempOut.csv" 
    Open outFile For Output As #1 

    k = 0 

    For i = 1 To 40 
    thisFile = "C:\datafolder\data" + CStr(i) + ".csv" 
    Open thisFile For Input As #2 
    j = 0 

    Do Until EOF(2)   'read until the end of the file 
     If k = 0 Then k = i 
     j = j + 1 
     Line Input #2, dataRead 

     If i = k Or (i > k And j > 1) Then 
      Print #1, dataRead 
     End If 
    Loop 

    Close #2 
    Next i 

    Close #1 
+0

谢谢!但不是你的代码只是将第一个文件粘贴到tempOut.csv中? –

+0

不,它会对所有其他文件执行第一个文件的所有行和第2行以及更大的行。试试看看。 –

+0

我没有在那里看到“或”。 Omg,这很好用!非常感谢你。感谢你,我觉得我已经变得更聪明了。 –