shane1717
shane1717

Reputation: 97

Count Items in file using VB

Kind of new to VBS. I'm trying to count the fields in the file and have this code.

Col()
Function Col()

Const FSpec = "C:\test.txt"
Const del = ","

  dim fs : Set fs = CreateObject("Scripting.FileSystemObject")
  dim f : Set f = fs.OpenTextFile(FSpec, 1)
  Dim L, C

  Do Until f.AtEndOfStream
   L = f.ReadLine()
   C = UBound(Split(L, del))
   C = C +1

   WScript.Echo "Items:", C

  Loop
  f.Close

End Function

It works however, I don't want to count the delim inside " ".

Here's file content:

1,"2,999",3

So basically, I'm getting 4 items for now but I wanted to get 3. Kind of stuck here.

Upvotes: 1

Views: 297

Answers (1)

Rno
Rno

Reputation: 887

For an example of my second suggestion, a very simple example could be something like this. Not saying it is perfect, but it illustrates the idea:

Dim WeAreInsideQuotes  'global flag
Function RemoveQuotedCommas(ByVal line)
    Dim i
    Dim result
    Dim current
    For i = 1 To Len(line)
        current = Mid(line, i, 1) 'examine character
        'check if we encountered a quote
        If current = Chr(34) Then
            WeAreInsideQuotes = Not WeAreInsideQuotes 'toggle flag
        End If
        'process the character
        If Not (current = Chr(44) And WeAreInsideQuotes) Then 'skip if comma and insode quotes
            result = result & current
        End If
    Next
    RemoveQuotedCommas = result
End Function

Upvotes: 1

Related Questions