Need help, in this line....If IsError(Application.Match(iLine, arr, 0)) Then ...
Its runtime error is that an object is required. I've tried a number of different things to solve, but am stuck. Been researching but not finding anything as a resolution.
When I try to declare..."Dim arr as variant" it retorts that "Expected end of statement". I am simply clicking on "ProcessCollection.vbs" to run the script. I'm using EditPlus3, and it does highlight "Application" in red text in this line.
I've tried VbsEdit and when it debugs to this line, iLine, arr, are defined, but the value of "Application" is "Empty".
GetFiles()
'WriteCSV()
'*****
Function GetFiles
Dim arr
'Dim arr as Variant
Dim iFileLines
Dim iLine
Set objFSO = CreateObject("Scripting.FileSystemObject")
objStartFolder = "C:\hgis\a"
Set objFolder = objFSO.GetFolder(objStartFolder)
Set colFiles = objFolder.Files
For Each objFile in colFiles
'Wscript.Echo objFile.Name
mfn = objStartFolder +"\"+ objFile.Name
Wscript.Echo mfn
'open file & process each file
set fso = CreateObject("Scripting.FileSystemObject")
Set theFile = fso.OpenTextFile(mfn, 8, True)
iFileLines = theFile.Line
iLine = 0
arr = Array(2, 3, iFileLines - 1) ' second, third, and 2nd from last
msgbox iFileLines
Set objFileToRead = CreateObject("Scripting.FileSystemObject").OpenTextFile(mfn,1)
Dim strLine, TotStr
TotStr = "CellA"
do while not objFileToRead.AtEndOfStream
strLine = objFileToRead.ReadLine()
msgbox strline
'Parse lines for specific data - i.e. "-2014-" to get date/time stamp
iLine = iLine + 1
'And then check if the line number is in the array:
'Capture data and store to csv file for Excel analysis
If IsError(Application.Match(iLine, arr, 0)) Then
' It isn't in the array, do this....
msgbox "no"
Else
' It is in the array, grab it
TotStr = TotStr +","+ strline
msgbox TotStr
End If
loop
objFileToRead.Close
Set objFileToRead = Nothing
Next
'csvFile.Close
End Function
'*****
I found a function from Justin Doles at DigitalDeviation.com that I used to replace the Application.Match function.
Function IsInArray(strIn, arrCheck)
'IsInArray: Checks for a value inside an array
'Author: Justin Doles - www.DigitalDeviation.com
Dim bFlag
bFlag = False
If IsArray(arrCheck) AND Not IsNull(strIn) Then
Dim i
For i = 0 to UBound(arrCheck)
If LCase(arrcheck(i)) = LCase(strIn) Then
bFlag = True
Exit For
End If
Next
End If
IsInArray = bFlag
End Function
'*****
Related
I am trying to design a macro to search for multiple strings in an excel.
I have the following code which searches for the word "techno" in an excel but, I need to include a variable into the code so that I can search for multiple words such "Techno", "electromagnetic", "waves", etc. at once. I am unable to create a loop for this condition.
Can anyone suggest a solution to this problem? The below code works fine but, only a tweak is required to include multiple strings in the search.
Sub SearchFolders()
Dim xFso As Object
Dim xFld As Object
Dim xStrSearch As String
Dim xStrPath As String
Dim xStrFile As String
Dim xOut As Worksheet
Dim xWb As Workbook
Dim xWk As Worksheet
Dim xRow As Long
Dim xFound As Range
Dim xStrAddress As String
Dim xFileDialog As FileDialog
Dim xUpdate As Boolean
Dim xCount As Long
myArray = Array("techno", "magnetic", "laser", "trent")
On Error GoTo ErrHandler
Set xFileDialog = Application.FileDialog(msoFileDialogFolderPicker)
xFileDialog.AllowMultiSelect = False
xFileDialog.Title = "Select a forlder"
If xFileDialog.Show = -1 Then
xStrPath = xFileDialog.SelectedItems(1)
End If
If xStrPath = "" Then Exit Sub
xUpdate = Application.ScreenUpdating
Application.ScreenUpdating = False
Set xOut = Worksheets.Add
For myCounter = 0 To UBound(myArray)
MsgBox myCounter & " is the Count No."
xStrSearch = myArray(myCounter)
MsgBox xStrSearch & " is the Value fr String search"
xRow = 1
With xOut
.Cells(xRow, 1) = "Workbook"
.Cells(xRow, 2) = "Worksheet"
.Cells(xRow, 3) = "Cell"
.Cells(xRow, 4) = "Text in Cell"
Set xFso = CreateObject("Scripting.FileSystemObject")
Set xFld = xFso.GetFolder(xStrPath)
xStrFile = Dir(xStrPath & "*.xls*")
Do While xStrFile <> ""
Set xWb = Workbooks.Open(Filename:=xStrPath & "\" & xStrFile, UpdateLinks:=0, ReadOnly:=True, AddToMRU:=False)
For Each xWk In xWb.Worksheets
Set xFound = xWk.UsedRange.Find(xStrSearch)
MsgBox xFound & " is the strings found"
If Not xFound Is Nothing Then
xStrAddress = xFound.Address
End If
Do
If xFound Is Nothing Then
Exit Do
Else
xCount = xCount + 1
MsgBox xCount & " is the count of strings"
xRow = xRow + 1
.Cells(xRow, 1) = xWb.Name
.Cells(xRow, 2) = xWk.Name
.Cells(xRow, 3) = xFound.Address
.Cells(xRow, 4) = xFound.Value
End If
Set xFound = xWk.Cells.FindNext(After:=xFound)
MsgBox xFound & " next string"
MsgBox xStrAddress & " is the address "
MsgBox xFound.Address & " is the address found"
Loop While xStrAddress <> xFound.Address 'To check how xStrAddress is populated or do we need to declare it as a help from excel pointed out
myCounter = myCounter + 1
Next
xWb.Close (False)
xStrFile = Dir
Loop
.Columns("A:D").EntireColumn.AutoFit
End With
Next myCounter
MsgBox xCount & "cells have been found", ,
ExitHandler:
Set xOut = Nothing
Set xWk = Nothing
Set xWb = Nothing
Set xFld = Nothing
Set xFso = Nothing
Application.ScreenUpdating = xUpdate
Exit Sub
ErrHandler:
MsgBox Err.Description, vbExclamation
Resume ExitHandler
End Sub
If the strings you are searching will always be the same, hard code them into an array and Loop through the array elements to search each string, like so:
Dim myArray as Variant
Dim myCounter as Long
myArray = Array("techno", "electromagnetic", ...etc.)
For myCounter = 0 To UBound(myArray)
... 'your code here
xStrSearch = myArray(myCounter)
... 'the rest if your code here
Next myCounter
I take a bunch of .CSV files from a server, open them and save them to another server as .XLSX. My issue is with:
'Get the folder object associated with the directory
Set objPickup = objFSO.GetFolder(pickUp)
Set objDropoff = objFSO.GetFolder(Dropoff)
I keep getting an error and i'm guessing it's because I am pulling in an array pickUp.
Sub ListfilesAndMove()
'List all files in selected folder
Dim objFSO As Object, objPickup As Object, objDropoff As Object, objFile As Object
Dim wb As Workbook, Dropoff As String, pickUp As Variant
Dim LastRowMonthly46 As Long, b As Long, c As Long
Dim ADay As Integer, AMonth As Integer, AYear As Integer, myDate As Date
Set objFSO = CreateObject("Scripting.FileSystemObject")
Dim ws As Worksheet: Set ws = ActiveSheet
Dim B3 As Range: Set B3 = ws.Range("B3")
Dim B26 As Range: Set B26 = ws.Range("B26")
Worksheets("Menu").Activate 'Go to worksheet Menu
'Make variable Pickup equal to value of B3
With Application
pickUp = .Transpose(ws.Range(B3, B26))
End With
Dim i As Long
For i = LBound(pickUp) To UBound(pickUp)
Debug.Print pickUp(i)
Next i
Dropoff = ActiveSheet.Range("B28").Value
Worksheets("Report").Activate 'Go to worksheet Report
Worksheets("Report").Visible = True
Worksheets("Menu").Visible = False
'Get the folder object associated with the directory
Set objPickup = objFSO.GetFolder(pickUp)
Set objDropoff = objFSO.GetFolder(Dropoff)
'Set values for cells A1,B1 and C1 and align text
Worksheets("Report").Range("A1").Value = "The files found in " & objPickup.Name & " are:"
Worksheets("Report").Range("A1").VerticalAlignment = xlCenter
Worksheets("Report").Range("A1").HorizontalAlignment = xlLeft
Worksheets("Report").Range("B1").Value = "Processed Yes/No"
Worksheets("Report").Range("B1").HorizontalAlignment = xlCenter
Worksheets("Report").Range("C1").Value = "New File Location"
Worksheets("Report").Range("C1").VerticalAlignment = xlCenter
Worksheets("Report").Range("C1").HorizontalAlignment = xlLeft
'Loop through the Files collection
Application.DisplayAlerts = False
For Each objFile In objPickup.Files
Worksheets("Report").Cells(Worksheets("Report").UsedRange.Rows.Count + 1, 1).Value = objFile.Name
'Open and Save File
Dim Filename As String
Filename = objFile
If Right(Filename, 4) = ".csv" Then
Application.ScreenUpdating = False
Set wb = Application.Workbooks.Open(Filename)
File_name = ActiveWorkbook.Name
File_name2 = ActiveWorkbook.Name
FileLength = Len(File_name2)
File_name2 = Left(File_name2, FileLength - 4)
ActiveWorkbook.ActiveSheet.Name = "Sheet1" 'Rename sheet
With wb 'Save File
'save file to dropoff location
.SaveAs (objDropoff & "\" & File_name2 & ".xlsx"), FileFormat:=xlOpenXMLWorkbook, ConflictResolution:=xlLocalSessionChanges
.Close SaveChanges:=False 'close file
End With
Dim FSO As Object
Set FSO = CreateObject("scripting.filesystemobject")
'Add Processed Comment
Worksheets("Report").Cells(Worksheets("Report").UsedRange.Rows.Count, 2).Value = "Yes"
'Add location of new File
Worksheets("Report").Cells(Worksheets("Report").UsedRange.Rows.Count, 3).Value = objDropoff
Else
Worksheets("Report").Cells(Worksheets("Report").UsedRange.Rows.Count, 2).Value = "No"
End If
Next
Application.DisplayAlerts = True
'Apply wrap text to B1
Worksheets("Report").Range("B1").WrapText = True
Worksheets("Report").Columns("A:C").AutoFit
'Clean up!
Set objPickup = Nothing
Set objDropoff = Nothing
Set objFile = Nothing
Set objFSO = Nothing
End Sub
I'm not sure why all that code is necessary; based on the explanation of what you need to do, you should only need to run two lines of code for each file:
one to open the .CSV:
Workbooks.OpenText "C:\yourPath\yourFile.csv", 65001, 1, , , , True
and one to save as .XLSX:
ActiveWorkbook.SaveAs "C:\yourPath\yourFile.xlsx", xlOpenXMLWorkbook
I don't memorize syntax for rarely used commands like this; instead I let Excel write the code for me using the Macro Recorder. I do the task once and then clean up the code that Excel generates (which resulted in the examples above).
More Information:
MSDN : Workbooks.OpenText Method
MSDN : Workbook.SaveAs Method
MSDN : Recording a Macro to Generate Code
MSDN : Revising Recorded VBA Macros
I have a database of about 140,000 test files. I am looking to loop through each folder and pull information from the file name of text and excel files so as to organize the data a little better.
I have found ways to pick a folder path and import information about each file using the code below. This works great except I would like to only pull information from excel and text files and I would also like to pull additional text information from the filename as well. For example I might have a file named:
"444555_CAT1010EL_650-700-800C-2hr laging NOT CH4.txt"
And I would want to print:
the 6 numbers at the beginning of the name (they could be anything) in this example "444555" in one column
print the 3 letters (they could be anything) before "1010EL" in another column. In this example "CAT"
"CH4" in the final column OR even have a column for "CH4" and if the filename contains "CH4" put an X in that column
have a column for "laging" and if the filename contains "laging" anywhere put an X in that column
Thank you in advance for your help.
Sub Compile3()
Dim oShell As Object
Dim oFile As Object
Dim oFldr As Object
Dim lRow As Long
Dim iCol As Integer
Dim vArray As Variant
vArray = Array(10, 0, 1, 156, 2, 4, 144, 146, 183, 185)
'0=Name, 31=Dimensions, 1=Size, 163=Vertical Resolution
Set oShell = CreateObject("Shell.Application")
'-------------------ROW INFO INPUT OPTIONS-----------------
'' 1)
' lRow = 1
' 2) find first empty row in database for bottletracker
'
Dim iRow As Long
iRow = Cells.find(What:="*", SearchOrder:=xlRows, SearchDirection:=xlPrevious, LookIn:=xlValues).Row
lRow = iRow
'------------------------------------------------------------
With Application.FileDialog(msoFileDialogFolderPicker)
.title = "Select the Folder..."
If .Show Then
Set oFldr = oShell.Namespace(.SelectedItems(1))
With oFldr
'Column header information
For iCol = LBound(vArray) To UBound(vArray)
Cells(lRow, iCol + 4) = .getdetailsof(.items, vArray(iCol))
Next iCol
For Each oFile In .items
lRow = lRow + 1
For iCol = LBound(vArray) To UBound(vArray)
Cells(lRow, iCol + 4) = .getdetailsof(oFile, vArray(iCol))
Next iCol
Next oFile
End With
End If
End With
End Sub
I'd use this code. There's three separate procedures at the end that find the last cell on the sheet, return the folder and return all files within the folder.
The main code then looks at each file name and pulls the required information from it.
Note, this code: InStr(sFileName, "CAT") <> 0 will return TRUE/FALSE depending if the text "CAT" is within the file name. InStr(sFileName, "CAT") returns the position of "CAT" within the text, and <>0 turns that into a boolean depending on if it's different from 0.
Option Explicit
Public Sub Test()
Dim sFolder As String
Dim cFiles As Collection
Dim vFile As Variant
Dim sFileName As String
Dim rLastCell As Range
sFolder = GetFolder("S:\DB_Development_DBC\") & Application.PathSeparator
Set cFiles = New Collection
EnumerateFiles sFolder, "*.xls*", cFiles
EnumerateFiles sFolder, "*.txt", cFiles
With ThisWorkbook.Worksheets("Sheet1")
For Each vFile In cFiles
Set rLastCell = LastCell(ThisWorkbook.Worksheets("Sheet1")).Offset(1) 'Find last row
sFileName = Mid(vFile, InStrRev(vFile, Application.PathSeparator) + 1) 'Get just file name from path.
.Cells(rLastCell.Row, 1) = Left(sFileName, 6) 'First 6 characters.
.Cells(rLastCell.Row, 2) = Mid(sFileName, InStr(sFileName, "1010EL") - 3, 3) '3 characters before 1010EL.
.Cells(rLastCell.Row, 3) = InStr(sFileName, "CH4") <> 0 'Contains CH4.
.Cells(rLastCell.Row, 4) = InStr(sFileName, "laging") <> 0 'Contains laging.
Next vFile
End With
End Sub
Sub EnumerateFiles(ByVal sDirectory As String, _
ByVal sFileSpec As String, _
ByRef cCollection As Collection)
Dim sTemp As String
sTemp = Dir$(sDirectory & sFileSpec)
Do While Len(sTemp) > 0
cCollection.Add sDirectory & sTemp
sTemp = Dir$
Loop
End Sub
Function GetFolder(Optional startFolder As Variant = -1) As Variant
Dim fldr As FileDialog
Dim vItem As Variant
Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
With fldr
.Title = "Select a Folder"
.AllowMultiSelect = False
If startFolder = -1 Then
.InitialFileName = Application.DefaultFilePath
Else
If Right(startFolder, 1) <> "\" Then
.InitialFileName = startFolder & "\"
Else
.InitialFileName = startFolder
End If
End If
If .Show <> -1 Then GoTo NextCode
vItem = .SelectedItems(1)
End With
NextCode:
GetFolder = vItem
Set fldr = Nothing
End Function
Public Function LastCell(wrkSht As Worksheet, Optional Col As Long = 0) As Range
Dim lLastCol As Long, lLastRow As Long
On Error Resume Next
With wrkSht
If Col = 0 Then
lLastCol = .Cells.Find("*", , , , xlByColumns, xlPrevious).Column
lLastRow = .Cells.Find("*", , , , xlByRows, xlPrevious).Row
Else
lLastCol = .Cells.Find("*", , , , xlByColumns, xlPrevious).Column
lLastRow = .Columns(Col).Find("*", , , , xlByColumns, xlPrevious).Row
End If
If lLastCol = 0 Then lLastCol = 1
If lLastRow = 0 Then lLastRow = 1
Set LastCell = wrkSht.Cells(lLastRow, lLastCol)
End With
On Error GoTo 0
End Function
Edit:
I've updated the code to include the other requirements and moved finding the last cell to within the loop so it actually works.
Note:
Mid(sFileName, InStr(sFileName, "1010EL") - 3, 3) - this code will throw an error if the text doesn't contain 1010EL. Add a check that InStr(sFileName, "1010EL") <> 0 before letting that line execute.
I have more than 50 files needed to create the pivot table and each file has the same exact formort with different contents. So far, I have finished creating the code for the pivot and it works very well when running alone, however, it failed when I tried to run the code for all workbooks in the same folder. I don't know what happened and why it kept showing that no files could be found despite nothing wrong about the pathname.
Sub DoAllFiles()
Dim Filename, Pathname As String
Dim WB As Workbook
Pathname = "D:\Reports"
Filename = Dir(Pathname & "\*.xls*")
Do While Filename <> ""
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Set WB = Workbooks.Open(Pathname & Filename) 'open all files
PivotX WB
WB.Close SaveChanges:=True
Application.DisplayAlerts = True
Application.ScreenUpdating = True
Filename = Dir()
Loop
End Sub
Here is the code for pivot and it works very well when running it alone:
Sub PivotX(WB As Workbook)
Dim Lrow, Lcol As Long
Dim wsData As Worksheet
Dim rngRaw As Range
Dim PvtTabCache As PivotCache
Dim PvtTab As PivotTable
Dim wsPvtTab As Worksheet
Dim PvtFld As PivotField
Set wsData = ActiveSheet
Lrow = wsData.Cells(Rows.Count, "B").End(xlUp).Row
Lcol = wsData.Cells(1, Columns.Count).End(xlToLeft).Column
Set rngRaw = wsData.Range(Cells(1, 1), Cells(Lrow, Lcol))
Set wsPvtTab = Worksheets.Add
wsData.Select
ActiveWorkbook.PivotCaches.Create(SourceType:=xlDatabase, SourceData:=rngRaw, Version:=xlPivotTableVersion12).CreatePivotTable TableDestination:=wsPvtTab.Range("A3"), TableName:="PivotTable1", DefaultVersion:=xlPivotTableVersion12
Set PvtTab = wsPvtTab.PivotTables("PivotTable1")
PvtTab.ManualUpdate = True
Set PvtFld = PvtTab.PivotFields("Month")
PvtFld.Orientation = xlPageField
PvtTab.PivotFields("Month").ClearAllFilters
Set PvtFld = PvtTab.PivotFields("Year")
PvtFld.Orientation = xlPageField
PvtTab.PivotFields("Year").ClearAllFilters
Set PvtFld = PvtTab.PivotFields("Fund_Code")
PvtFld.Orientation = xlRowField
PvtFld.Position = 1
Set PvtFld = PvtTab.PivotFields("Curr")
PvtFld.Orientation = xlColumnField
PvtFld.Position = 1
wsPvtTab.PivotTables("PivotTable1").PivotFields("Curr").PivotItems("USD").Position = 1
With PvtTab.PivotFields("Trx_Amount")
.Orientation = xlDataField
.Function = xlSum
.NumberFormat = "#,##0;[red](#,##0)"
End With
wsPvtTab.PivotTables("Pivottable1").RowAxisLayout xlTabularRow
'Remove grand total
wsPvtTab.PivotTables("Pivottable1").RowGrand = False
For Each PvtTbCache In ActiveWorkbook.PivotCaches
On Error Resume Next
PvtTbCache.Refresh
Next PvtTbCache
'Determine filter value
Set PvtFld = PvtTab.PivotFields("Year")
PvtFld.ClearAllFilters
PvtFld.EnableMultiplePageItems = True
With PvtFld
.AutoSort xlmnual, .SourceName
For Each Pi In PvtFld.PivotItems
Select Case Pi.Name
Case "2014"
Case Else
Pi.Visible = False
End Select
Next Pi
.AutoSort xlAscending, .SourceName
End With
'determine filter value
Set PvtFld = PvtTab.PivotFields("Month")
PvtFld.ClearAllFilters
PvtFld.EnableMultiplePageItems = True
With PvtFld
.AutoSort xlmnual, .SourceName
For Each Pi In PvtFld.PivotItems
Select Case Pi.Name
Case "11"
Case Else
Pi.Visible = False
End Select
Next Pi
.AutoSort xlAscending, .SourceName
End With
PvtTab.ManualUpdate = False
End Sub
Any help would be very much appreciated. Thank you very much in advance.
This should solve your problem:
Set WB = Workbooks.Open(Pathname & "\" & Filename)
When I tried using your code, for some reason, it did not retain the backslash you put at the beginning of the "Filename" variable. That would explain why VBA couldn't find the files. Adding it back should between the path name and file name should make it work correctly
I believe you have the answer to your base problem above but I would offer the following 'tweaks' to avoid screen flashing and unrecovered variable assignment.
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Do While Filename <> ""
Set WB = Workbooks.Open(Pathname & "\" & Filename) 'open all files
Call PivotX(WB)
WB.Close SaveChanges:=True
Set WB = Nothing
Filename = Dir()
Loop
Application.DisplayAlerts = True
Application.ScreenUpdating = True
The Set WB = Nothing is really only purposeful on the last pass when WB is not reassigned but your PivotX sub could use several Set nnn = Nothing before exiting. While the reference count is supposed to be decremented (and memory consequently released), that is not always the case. (see Is there a need to set Objects to Nothing inside VBA Functions) In short, it is just good coding practise.
Finally, using Dim Filename, Pathname As String declares Filename as a variant, not a string type. It isn't making any difference here but you should be aware of what your variables are being declared as.
I am new to scripting and I cannot figure out how to replace a string in a file with values read from a different file. I have tried storing the values in an array and then plugging them into the replace method but I can't get the loops to work. Here are two of my attempts:
Const ForReading = 1
Const Inc = 0 Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = objFSO.OpenTextFile _
("ReadInFile.txt", ForReading)
Do Until objTextFile.AtEndOfStream
strNextLine = objTextFile.Readline
arrServiceList = Split(strNextLine , ",")
Loop
Set objFS = CreateObject("Scripting.FileSystemObject")
strFile = "OrigFile.txt"
Set objFile = objFS.OpenTextFile(strFile)
Do Until objFile.AtEndOfStream
strLine = objFile.ReadLine
If InStr(strLine,"777")> 0 Then
strLine = Replace(strLine,"777",arrServiceList(Inc)) Inc = Inc + 1;
End If
Loop
Const ForReading = 1
Set fso = CreateObject("Scripting.FileSystemObject")
Set answers = fso.OpenTextFile("OrigFile.txt", ForReading)
Set fdf = fso.OpenTextFile("ReadInFile.txt", ForReading)
Set computers = CreateObject("Scripting.Dictionary")
Do Until answers.AtEndOfStream Or fdf.AtEndOfStream
computers.Add names.ReadLine, locations.ReadLine
Loop
names.Close
locations.Close
I also tried a for each loop to read the array but I cannot incorporate it with the other loop.
I did some rebuilding with comment to help you on your way. Please try to understand each step.
Option Explicit ' this makes sure you don't forget to declare variables
Const ForReading = 1
Dim objFSO, objTextFile
Dim serviceCollection, service, strNextLine
Dim i ' i is a variable, it get incremented. So don't make it a const
Dim strLine, objReadFile, objWriteFile
Set objFSO = CreateObject("Scripting.FileSystemObject")
' An ArrayList let you .Add items to the collection without redimming it like a
' native array
Set serviceCollection = CreateObject("System.Collections.ArrayList")
Set objTextFile = objFSO.OpenTextFile("ReadInFile.txt", ForReading)
Do Until objTextFile.AtEndOfStream ' Reads an textfile from start to end
strNextLine = objTextFile.Readline
for each service in Split(strNextLine , ",") ' This splits a single line into parts on the comma character
serviceCollection.Add service
Next
Loop
' Make an array from all services
arrServiceList = serviceCollection.ToArray()
Set objReadFile = objFSO.OpenTextFile("OrigFile.txt")
Set objWriteFile = objFSO.CreateTextFile("NewFile.txt", true)
i = 0
Do Until objReadFile.AtEndOfStream
strLine = objReadFile.ReadLine
If InStr(strLine,"777")> 0 Then
' This next line is not totally safe, because arrServiceList can go over its upperbound
strLine = Replace(strLine, "777", arrServiceList(i))
i = i + 1;
End If
' Important! Write the line to the new textfile
objWriteFile.WriteLine strLine
Loop
' It is good practice to close opened files
objReadFile.Close
objWriteFile.Close
Still you can get some issues: When there are multiple 777s on one line, they get replaced with the same variable because i is not incremented in the mean time. You could solve this by replacing it with something like
Do Until objReadFile.AtEndOfStream
strLine = objReadFile.ReadLine
do
If InStr(strLine,"777")> 0 Then
strLine = Replace(strLine, "777", arrServiceList(i), 1, 1)
i = i + 1;
thereWasAReplace = True ' do not forget to declare
else
thereWasAReplace = False
End If
Loop While thereWasAReplace
' Write the line to the new textfile
objWriteFile.WriteLine strLine
Loop
Disclaimer: I did this from the top of my head, so you can encounter a little bug or two.