0 Replies - 1959 Views - Last Post: 19 January 2010 - 02:09 PM

#1 Fib   User is offline

  • D.I.C Addict
  • member icon

Reputation: 163
  • View blog
  • Posts: 554
  • Joined: 12-March 09

Easily reading in data from a csv file

Posted 19 January 2010 - 02:09 PM

Description: You will have to change the value of fileName to equal the path to your csv file. Then just add this to any sub or function.This code will read in a csv file into a string variable, then seperate the file lines and put the lines into an array, then will loop through each line and seperate each column and put the columns into an array. Then you can do whatever you want with each block of data.
'Declare variables for opening the file
    Dim fileName As String
    Dim fileNum As Integer
    fileName = "SomeFile.csv"
    fileNum = FreeFile
    
    'Declare variables for reading the file
    Dim fileData As String
    Dim fileLines As String
    Dim fileColumns As String
    
    'Declare counter variables for looping
    Dim i As Integer
    Dim c As Integer
    
    'Open the file
    Open fileName For Input As #fileNum
    
    'Read in the entire file into one string variable
    fileData = Input(LOF(fileNum), #fileNum)
    
    'Close the file
    Close #fileNum
    
    'Split each line into an array
    fileLines = Split(fileData, vbCrLf)
    
    'Loop through each line
    For i = 0 To UBound(fileLines) - 1
    
        'Split each column into an array
        fileColumns = Split(fileLines(i), ",")
        
        'Loop through each column
        For c = 0 To UBound(fileColumns) - 1
            'Do whatever you want with this data
        Next c
    Next i


Is This A Good Question/Topic? 0
  • +

Page 1 of 1