I was trying to figure out a good way to determine if a file being read has a line terminator of CR/LF (Windows/DOS) or LF (Unix/Linux). Since VBA Line Input assumes that the file is in the Windows format (CR/LF line terminator), it reads in the entire file if the file is in the Unix format. Here's a function that determines how many columns are in a CSV file regardless the format format (except for the Mac format, which terminates each line with CR):
- ' ----------------------------------------------------------------------------
- ' get the number of columns by reading the 1st line which should be the header
- '
- Private Function GetNumCols(pFile) As Integer
- Dim data As String
- Dim temp As Variant
- Open pFile For Input As #1
- Line Input #1, data
- Close #1
- ' play the following trick in case CSV is in the Unix format
- ' algorithm:
- ' 1. read one line. If Unix file, it will read the entire file
- ' 2. split the line with linefeed char
- ' 3. if there are more than 1 linefeed chars, it's unix
- ' 4. if Unix, split the first element of the array that were split by
- ' linefeed by ","
- ' 5. if Windows, split the input line by ","
- temp = Split(data, vbLf)
- If UBound(temp) > 2 Then
- temp = Split(temp(1), ",")
- Else
- temp = Split(data, ",")
- End If
- GetNumCols = UBound(temp) + 1
- End Function
Thanks for sharing this information. I really like your blog post very much. You have really shared a informative and interesting blog post with people..
ReplyDeletemicrosoft excel vba training
Thank you! I am glad you like it.
ReplyDelete