当前位置:编程学习 > VB >>

按要求提取csv文件内容

我的csv文件内容是:
Date,$Time,PV1,PV2,PV3
03/23/12,17:40:26,102,102,102
03/23/12,17:45:26,110,110,110
03/23/12,17:50:26,118,118,118
03/23/12,17:55:26,125,126,126
03/23/12,18:00:26,133,133,133
我想在vb文本框中按要求显示其中某一列或几列:例如四列
Date        $Time   PV2  PV3
03/23/12  17:40:26  102  102
03/23/12  17:45:26  110  110
03/23/12  17:50:26  118  118
03/23/12  17:55:26  126  126
03/23/12  18:00:26  133  133
应该怎么编呢
dim i as long
dim str as string
dim data() as string, lines() as string
open "xxx.csv" for input as #1
    str = input(lof(1), 1)
close #1
lines = split(str, vbcrlf)
for i = lbound(lines) to ubound(lines)
    data = split(lines(i), ",")
    if i = lbound(lines) then 
        text1.text = data(0) & " " & data(1) & " " & data(3) & " " & data(4)
    else
        text1.text = text1.text & vbcrlf & data(0) & " " & data(1) & " " & data(3) & " " & data(4)
    end if
next
dim i as long
dim str as string, r as string
dim data() as string, lines() as string
open "xxx.csv" for input as #1
    str = input(lof(1), 1)
close #1
lines = split(str, vbcrlf)
for i = lbound(lines) to ubound(lines)
    data = split(lines(i), ",")
    if i = lbound(lines) then 
        r = data(0) & " " & data(1) & " " & data(3) & " " & data(4)
    else
        r = r & vbcrlf & data(0) & " " & data(1) & " " & data(3) & " " & data(4)
    end if
next
text1.text = r

这样可以快一点。

Dim strData As String
Dim reg As Object,match As Object
Open "xxx.csv" For Input As #1
    strData = Input(LOF(1), 1)
Close #1
Set reg = CreateObject("vbscript.regExp")
reg.Global = True
reg.Pattern = "(.*?),(.*?),(.*?),(.*?),([^\r\n]*)"
Set matchs = reg.Execute(strData)
For Each match In matchs
    Debug.Print match.SubMatches(0) & "," & match.SubMatches(1) & "," & match.SubMatches(3) & "," & match.SubMatches(4)
Next
可以将其当作外部数据库来查询。

Dim a() As String, strLine As String
Open "xxx.csv" For Input As #1
Text1 = ""
Do Until EOF(1)
    Line Input #1, strLine
    a = Split(strLine, ",")
    If Ubound(a) = 4 Then
        a(3) = "" 'Remove PV2
        strLine = Replace(Join(a, Space(1)), Space(2), Space(1))
        Text1 = Text1 & strLine & vbcrLf
    End If
Loop
Close #1    
补充:VB ,  资源
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,