Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Apr 26th, 2012  |  syntax: None  |  size: 1.91 KB  |  hits: 26  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. reading and writing a csv file using FileSystemObject
  2. Set objFSO = CreateObject("scripting.filesystemobject")
  3.     'create a csv file
  4.     Set objTF = objFSO.createtextfile("C:testmyfile.csv", True, False)
  5.     'open an existing csv file with writing ability
  6.     Set objTF = objFSO.OpenTextFile("C:testmyfile.csv", 8)
  7.        
  8. Const sFilePath = "C:testmyfile.csv"
  9. Const strDelim = ","
  10. Sub CreateCSV_FSO()
  11.     Dim objFSO
  12.     Dim objTF
  13.     Dim ws As Worksheet
  14.     Dim lRow As Long
  15.     Dim lCol As Long
  16.     Dim strTmp As String
  17.     Dim lFnum As Long
  18.  
  19.     Set objFSO = CreateObject("scripting.filesystemobject")
  20.     Set objTF = objFSO.createtextfile(sFilePath, True, False)
  21.  
  22.     For Each ws In ActiveWorkbook.Worksheets
  23.         'test that sheet has been used
  24.         Set rng1 = ws.UsedRange
  25.         If Not rng1 Is Nothing Then
  26.             'only multi-cell ranges can be written to a 2D array
  27.             If rng1.Cells.Count > 1 Then
  28.                 X = ws.UsedRange.Value2
  29.                 'The code TRANSPOSES COLUMNS AND ROWS by writing strings column by column
  30.                 For lCol = 1 To UBound(X, 2)
  31.                     'write initial value outside the loop
  32.                     strTmp = IIf(InStr(X(1, lCol), strDelim) > 0, """" & X(1, lCol) & """", X(1, lCol))
  33.                     For lRow = 2 To UBound(X, 1)
  34.                         'concatenate long string & (short string with short string)
  35.                         strTmp = strTmp & (strDelim & IIf(InStr(X(lRow, lCol), strDelim) > 0, """" & X(lRow, lCol) & """", X(lRow, lCol)))
  36.                     Next lRow
  37.                     'write each line to CSV
  38.                     objTF.writeline strTmp
  39.                 Next lCol
  40.             Else
  41.                 objTF.writeline IIf(InStr(ws.UsedRange.Value, strDelim) > 0, """" & ws.UsedRange.Value & """", ws.UsedRange.Value)
  42.             End If
  43.         End If
  44.     Next ws
  45.  
  46.     objTF.Close
  47.     Set objFSO = Nothing
  48.     MsgBox "Done!", vbOKOnly
  49.  
  50. End Sub