Sub CreateTXTFile()
Dim oFSO As New FileSystemObject
Dim oTS As TextStream
Dim oWS As Worksheet
Dim lMaxRow As Long
Dim lRow As Long
Dim lMaxCol As Long
Dim lCol As Long
Dim lColWidths(1 To 3) As Long
Dim sLine As String
Dim sData As String
Dim lStart As Long
lColWidths(1) = 30
lColWidths(2) = 20
lColWidths(3) = 5
Set oWS = Worksheets(1)
lMaxRow = oWS.Cells.SpecialCells(xlCellTypeLastCell).Row
lMaxCol = oWS.Cells.SpecialCells(xlCellTypeLastCell).Column
Set oTS = oFSO.CreateTextFile("C:\Test\Map.csv")
oTS.WriteLine "Variable,Start,Width"
lStart = 1
For lCol = 1 To lMaxCol Step 1
oTS.WriteLine oWS.Cells(1, lCol) & "," & lStart & "," & lColWidths(lCol)
lStart = lStart + lColWidths(lCol)
Next lCol
oTS.Close
Set oTS = oFSO.CreateTextFile("C:\Test\Test3.txt")
For lRow = 2 To lMaxRow Step 1
sLine = vbNullString
For lCol = 1 To lMaxCol Step 1
If (lCol < 3) Then
sData = Left$(oWS.Cells(lRow, lCol) & Space(lColWidths(lCol)), lColWidths(lCol))
Else
sData = Right$(Space(lColWidths(lCol)) & oWS.Cells(lRow, lCol), lColWidths(lCol))
End If
sLine = sLine & sData
Next lCol
oTS.WriteLine sLine
Next lRow
oTS.Close
Set oTS = Nothing
Set oFSO = Nothing
MsgBox "Over"
End Sub
Friday, July 10, 2009
Subscribe to:
Post Comments (Atom)
I have and Excel file with the current scenario:
ReplyDeleteCell A12 contains a formula that CONCATENATE's an existing directory and adds a new file name I want to create, resulting in c:\projects\vendor\xxxxx_info.txt (where xxxxx is a variable from another cell). Note that the directory path will change based on user input.
Cells A13:A17 contain information I want to save in this new text file.
How could I create this text file using VB?