Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

VBScript for removing columns and rows in csv file

Status
Not open for further replies.

walterja

IS-IT--Management
May 25, 2007
6
US
Hello, my script for removing columns within a .csv file works for only removing 1 column and i'm not sure why. Even if I have 2 CutColumn commands, it only removes the last column specified. In example below, it only removes the 1st column, not the 2nd. I'm also going to need to remove all rows that do not contain a certain string in a certain column. Help would be greatly appreciated. Thanks in advance.



'On Error Resume Next
Dim objFSO, dataArray, clippedArray()
Set objFSO = CreateObject("Scripting.FileSystemObject")


'Create an array out of the CSV
'open the data file
Set oTextStream = objFSO.OpenTextFile("C:\test\test.csv")
Set newFile = objFSO.CreateTextFile("C:\test\test_new.csv")
'make an array from the data file
dataArray = Split(oTextStream.ReadAll, vbNewLine)
'close the data file
oTextStream.Close

x = 0
For Each strLine In dataArray
'Now make an array from each line
ReDim Preserve clippedArray(x)
clippedArray(x) = Split(strLine,",")

' Delete Fields
CutColumn = 2
CutColumn


intCount = 0
newLine = ""
For Each Element In clippedArray(x)
If intCount = UBound(clippedArray(x)) Then
EndChar = vbCrLf
Else
EndChar = ","
End If

If intCount <> CutColumn -1 Then
newLine = newLine & Element & EndChar
End If
intCount = intCount + 1
If intCount = UBound(clippedArray(x))+1 Then
newFile.Write newLine
End If
Next

Next
 
Sorry, the second CutColumn line of code should read:

CutColumn = 1
 
This bit of code is assigning a value to a variable:
Code:
' Delete Fields
   CutColumn = 2
   CutColumn = 1
You assign it a value of 2 then immediately afterward you change the value to 1. The 'CutColumn' variable now have the value of 1 for the rest of your script resulting in only column 1 getting deleted.

If you want to cut multiple columns, I would suggest creating a function or subroutine that you could pass in which column(s) you want cut.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top