用vbs查询csv

时间:2012-08-08 11:20:34

标签: csv vbscript adodb

有一个像这样的csv文件,我可以使用下面的代码轻松地阅读它。但正如您所看到的,csv中有多个name1,group1,status1,name2,group2等列。每个用户将具有不同数量的列。我想知道是否有办法使用通配符我可以调用objRecordset.Fields.Item("Group1") ("Group%")之类的内容,或者如果我可以自动递增数字直到找不到记录

  

用户名,域,站点,MCO,NAME1组别1,状态1,NAME2组2,状态2,NAME3,组3,STATUS3   Paolina,AA,雅典,希腊,Adobe Acrobat Pro,ACROBAT009,Live ,,,,,,   George,AA,雅典,希腊,SpotFire 2.20,SPOTFIRE220,Live ,,,,,,

option explicit

Const adOpenStatic = 3
Const adLockOptimistic = 3
Const adCmdText = &H0001

Dim strPathtoTextFile, objConnection, objRecordSet, objNetwork
Dim wshshell, Username

Set objConnection = CreateObject("ADODB.Connection")
Set objRecordSet = CreateObject("ADODB.Recordset")

Set objNetwork = CreateObject("WScript.Network")
userName = objNetwork.UserName

strPathtoTextFile = "C:\Hunter\vbs\" 'must have a trailing \

objConnection.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
          "Data Source=" & strPathtoTextFile & ";" & _
          "Extended Properties=""text;HDR=YES;FMT=Delimited"""

objRecordset.Open "SELECT * FROM Users.txt where [user name] like '" & UserName & "'", _
          objConnection, adOpenStatic, adLockOptimistic, adCmdText
Do Until objRecordset.EOF
    Wscript.Echo "Name: " & objRecordset.Fields.Item("User Name")
    Wscript.Echo "Group: " & objRecordset.Fields.Item("Group1")
    Wscript.echo "Status:" & objRecordset.Fields.Item("Status1")
    objRecordSet.MoveNext
Loop

1 个答案:

答案 0 :(得分:1)

您的示例表明最大组号是最后一个字段,因此可能:

objRecordset.Open "SELECT * FROM Users.txt where [user name] like '" _
      & UserName & "'", _
      objConnection, adOpenStatic, adLockOptimistic, adCmdText
MaxNum = _
      Replace(objRecordset.Fields(objRecordset.Fields.Count-1).Name,"Status","")
Do Until objRecordset.EOF
    Wscript.Echo "Name: " & objRecordset.Fields.Item("User Name")
    For i=1 to MaxNum
       Wscript.Echo "Group: " & objRecordset.Fields.Item("Group" & i)
       Wscript.echo "Status:" & objRecordset.Fields.Item("Status" & i)
    Next
    objRecordSet.MoveNext
Loop

我还没有测试过,但总体思路应该坚持下去。