How to improve the speed of loop a file - vba

below is my code, which isn't perfect but working, it take more than 30min to loop through a text file. how to improve the speed of looping through file by using other code or method. please help.
Open "C:\Users\steven.EOPESTATE\Desktop\Sharp Sales\TRMSAVE01.txt" For Input As #1
Do Until EOF(1)
Dim ITEMSQL As String
Line Input #1, varLine
testvarline = Split(varLine, ",")
If testvarline(0) = "$ITEM" Then
'Debug.Print testvarline(0), testvarline(1), testvarline(2), testvarline(3), testvarline(4), testvarline(5), testvarline(6), testvarline(7), testvarline(8), testvarline(9)
testvarline(0) = Replace(testvarline(0), "$", " ")
testvarline(7) = Replace(testvarline(7), ",,", " ")
ITEMSQL = "Insert into SalesItem([ITEMID], [2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12]) Values (" & Chr(34) & "" & (testvarline(0)) & "" & Chr(34) & "," & (testvarline(1)) & "," & (testvarline(2)) & "," & (testvarline(3)) & "," & (testvarline(4)) & "," & (testvarline(5)) & "," & Chr(34) & "" & (testvarline(6)) & "" & Chr(34) & "," & (testvarline(9)) & "," & (testvarline(10)) & "," & (testvarline(11)) & "," & (testvarline(12)) & "," & (testvarline(14)) & ")"
Debug.Print ITEMSQL
DoCmd.RunSQL ITEMSQL
DoCmd.SetWarnings False
DoCmd.Echo False
End If
Loop
Close #1

One of the slowest things you can do on a pc is load from the hard drive. The CPU and RAM are incredibly much faster than the hard drive (see this SO question), so they end up waiting for a hard disk read to complete. Because of this, reading the entire file into memory at once will speed up your program significantly.
Rather than use the Split function again to split up the lines for processing, I recommend parsing them yourself by using the Mid function, which actually avoids a lot of the overhead of normal string processing because it doesn't create a temporary copy of the substring in memory. Here is UNTESTED example code:
Dim strFileText As String
Dim lngCurrIndex As Long
Dim lngEndOfLine As Long
Open "C:\Users\steven.EOPESTATE\Desktop\Sharp Sales\TRMSAVE01.txt" For Binary As #1
strFileText = Space(LOF(1)) 'create space for the whole file'
Get 1, , strFileText 'read in the whole file at once'
lngCurrIndex = 1
Do While lngCurrIndex < Len(strFileText)
Dim ITEMSQL As String
lngEndOfLine = InStr(lngCurrIndex, strFileText, vbCrLf, vbBinaryCompare) 'find the end of this line. NOTE: This assumes that this text files uses the MS convention of CrLf line endings'
varLine = Mid(strFileText, lngCurrIndex, lngEndOfLine - lngCurrIndex) 'get the line'
lngCurrIndex = lngEndOfLine + 2 'set lngCurrIndex to the start of the next line'
testvarline = Split(varLine, ",")
If testvarline(0) = "$ITEM" Then
'Debug.Print testvarline(0), testvarline(1), testvarline(2), testvarline(3), testvarline(4), testvarline(5), testvarline(6), testvarline(7), testvarline(8), testvarline(9)'
testvarline(0) = Replace(testvarline(0), "$", " ")
testvarline(7) = Replace(testvarline(7), ",,", " ")
ITEMSQL = "Insert into SalesItem([ITEMID], [2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12]) Values (" & Chr(34) & "" & (testvarline(0)) & "" & Chr(34) & "," & (testvarline(1)) & "," & (testvarline(2)) & "," & (testvarline(3)) & "," & (testvarline(4)) & "," & (testvarline(5)) & "," & Chr(34) & "" & (testvarline(6)) & "" & Chr(34) & "," & (testvarline(9)) & "," & (testvarline(10)) & "," & (testvarline(11)) & "," & (testvarline(12)) & "," & (testvarline(14)) & ")"
Debug.Print ITEMSQL
DoCmd.RunSQL ITEMSQL
DoCmd.SetWarnings False
DoCmd.Echo False
End If
Loop
Close #1
Depending upon the size of your file, it may not be possible to load it all into memory at once. If that is the case, you can split it into large chunks and do them one at a time.

Related

VBA adding multiple criterias for SumIF

EndRowH = ActiveSheet.Range("H65536").End(xlUp).Row
ActiveSheet.Range("H1").Formula = "=SUMIFS(H3:H" & EndRowH & ", C3:C" & EndRowH & ", "">=" & lngStart & """)"
I Have a criteria on the C column where it has to be greater than the lngStart Value.
The code is working till here.. But I have to add an extra criteria where the sumif needs to be done only if there is blank value in the column I
Dim Blank As Long
Blank = ""
ActiveSheet.Range("H1").Formula = "=SUMIFS(H3:H" & EndRowH & ", C3:C" & EndRowH & ", "">=" & lngStart & "",I3:I" & EndRowH & ", ""!=" & Blank & "" ")"
When working with complex strings you want to put as a Formula, you might want to use an "helper" string, in the code below I use FormulaString, so when you run the Debug.Print line, you can see if the formula string is valid.
Also, and it's only my preference, to get the " inside, I prefer to use Chr(34).
Code
Dim FormulaString As String
FormulaString = "=SUMIFS(H3:H" & EndRowH & ", C3:C" & EndRowH & "," & Chr(34) & ">=" & lngStart & Chr(34) & ",I3:I" & EndRowH & "," & Chr(34) & "<>" & Chr(34) & ")"
Debug.Print FormulaString
ActiveSheet.Range("H1").Formula = FormulaString
Running this code, you will get in the immediate window the following formula:
=SUMIFS(H3:H10, C3:C10,">=5",I3:I10,"<>")
I'd go this way
ActiveSheet.Range("H1").Formula = "=SUMIFS(H3:H" & EndRowH & ", C3:C" & EndRowH & ", concatenate("">=""," & lngStart & "),I3:I" & EndRowH & ", ""="")"

Displaying all but the last line in a text file

I've created this 2 player game called Go and I've made it so that the statistics from the game is recorded in a text file. If the same 2 players play each other more than once, their game will be recorded in the same text file on the next line.
I have done all of that, but now I want the previous games to be displayed on screen so that the players can see the scores from previous matches. I don't want the final line to be displayed as that is the score from the game that has just finished. Here's my code so far:
Dim file As System.IO.StreamWriter
'Imports the data from previous forms to form 3
handikomi = Form1.handi_komi
prisonerB = Form2.prisonerB
prisonerW = Form2.prisonerW
bpass = Form2.bpass
wpass = Form2.wpass
bstones = Form2.bstones
wstones = Form2.wstones
btotalscore = prisonerB + handikomi(0, 2)
wtotalscore = prisonerW + handikomi(1, 2)
If btotalscore > wtotalscore Then
winnerlbl.Text = (handikomi(0, 0) & " IS THE WINNER!")
ElseIf wtotalscore > btotalscore Then
winnerlbl.Text = (handikomi(1, 0) & " IS THE WINNER!")
End If
file = My.Computer.FileSystem.OpenTextFileWriter("F:\My Go project flood fill2\Text files\" & handikomi(0, 0) & " VS " & handikomi(1, 0) & ".txt", True)
'Displays statistics from current match
file.WriteLine("BLACK" & "," & "WHITE" & "," & "Total Score" & "," & btotalscore & "," & wtotalscore & "," & "Prisoners" & "," & prisonerB & "," & prisonerW & "," & "Passes" & "," & bpass & "," & wpass & "," & "Stones" & "," & bstones & "," & wstones)
file.Close()
breakdwnlbl.Text = " BLACK WHITE"
breakdwnlbl.Text = (breakdwnlbl.Text & vbNewLine & "Total Score" & " " & btotalscore & " " & wtotalscore)
breakdwnlbl.Text = (breakdwnlbl.Text & vbNewLine & "Prisoners" & " " & prisonerB & " " & prisonerW)
breakdwnlbl.Text = (breakdwnlbl.Text & vbNewLine & "Passes" & " " & bpass & " " & wpass)
breakdwnlbl.Text = (breakdwnlbl.Text & vbNewLine & "Stones" & " " & bstones & " " & wstones)
Dim data As String 'to hold value of file line
Dim filename As String 'declare file
filename = "F:\My Go project flood fill2\Text files\" & handikomi(0, 0) & " VS " & handikomi(1, 0) & ".txt" 'path to file on system
FileOpen(1, filename, OpenMode.Input) 'open file for reading
'try amend
Do While Not EOF(1)
data = LineInput(1)
MsgBox(data)
Loop
I think that I shouldn't be using EOF for this case, but I don't know what else to use as I'm still a beginner. I appreciate any help!
Wouldn't it be easier to read all lines and just skip the last one:
Dim allLines() As String = File.ReadAllLines(filename)
Dim allButLast = allLines.Take(allLines.Length - 1)
The variable allButLast is an IEnumerable(Of String) containing all the lines of the file, except for the last one.
Update:
Here's an example to show each line in a MessageBox:
For Each line As String In allButLast
MessageBox.Show(line)
Next

String sets its Value to "False"

So, I'm currently working on a program that should create Lua-Scripts for the Unitale-Engine. I added a "New Project" button which should create a new project file when you click it. I want this file to contain the default project-file-text. So i did this:
Dim File1 As String = "monster{" & vbNewLine & "COMMENTS=Ribbit, ribbit.;Croak, croak.;Hop, hop.;Meow." & vbNewLine & "COMMANDS=Compliment;Threaten" & vbNewLine & "DEFAULT_SPRITE=None" & vbNewLine & "NAME=Froggit" & vbNewLine & "HP=10" & vbNewLine & "ATK=1" & vbNewLine = "DEF=0" & vbNewLine & "CHECK_MESSAGE=Life is difficult for this enemy." & vbNewLine & "HandleAttack=" & vbNewLine & "OnDeath=" & vbNewLine & "HandleCustomCommand=" & vbNewLine & "}"
Dim File2 As String = vbNewLine & "encounter{" & vbNewLine & "DEFAULT_MUSIC=Fight" & vbNewLine & "ENCOUNTER_TEXT=Froggit hops close." & vbNewLine & "NEXTWAVES=1" & vbNewLine & "WAVETIMER=6" & vbNewLine & "ARENASIZE=155;130" & vbNewLine & "ENEMIES=Froggit" & vbNewLine & "ENEMYPOSITIONS=0;0" & "EncounterStarting=" & vbNewLine & "EnemyDialogueStarting=" & vbNewLine & "EnemyDialogueEnding=" & vbNewLine & "DefenseEnding=" & vbNewLine & "HandleItem=" & vbNewLine & "HandleSpare=" & vbNewLine & "EnteringState=" & vbNewLine & "Update=" & vbNewLine & "}"
Dim File3 As String = vbNewLine & "waves{" & vbNewLine & "1=Do Nothing" & vbNewLine & "}" & vbNewLine & "end"
My.Computer.FileSystem.WriteAllText(My.Computer.FileSystem.SpecialDirectories.MyDocuments & "\UnitaleMaker\Projects\" & PJNBox.Text & ".umproj", File1 & File2 & File3, False)
Yes, that is a lot of text. The problem is, that File1 always sets its value to "False" when it is declared. I thought that is because the string is too long, so I split it to 3 parts, but it doesn't work.
Any help would be apprechiated!
~ Mika // OneByte_
Starting with VB 14 (Visual Studio 2015), you can span String literals across multiple lines. VB 14 also adds String interpolation, which makes for much cleaner code. You could write your code like the following which would have kept you from having made your mistake of & vbNewLine = "DEF=0" &and would overall make the code easier to read.
I am also assuming you forgot a newline in "ENEMYPOSITIONS=0;0" & "EncounterStarting=" and I have indented the parts between the {}. I combined File1, File2, and File3 back into a single string since you stated you broke them up in the question, I assumed you'd rather have it all in one string.
Dim File1 As String = "monster{
COMMENTS = Ribbit, ribbit.;Croak, croak.;Hop, hop.;Meow.
COMMANDS=Compliment;Threaten
DEFAULT_SPRITE=None
NAME=Froggit
HP=10
ATK=1
DEF=0
CHECK_MESSAGE=Life Is difficult For this enemy.
HandleAttack=
OnDeath=
HandleCustomCommand=
}
encounter{
DEFAULT_MUSIC = Fight
ENCOUNTER_TEXT =Froggit hops close.
NEXTWAVES=1
WAVETIMER=6
ARENASIZE=155;130
ENEMIES=Froggit
ENEMYPOSITIONS=0;0
EncounterStarting=
EnemyDialogueStarting=
EnemyDialogueEnding=
DefenseEnding=
HandleItem=
HandleSpare=
EnteringState=
Update=
}
waves{
1 =Do Nothing
}
End"
My.Computer.FileSystem.WriteAllText($"{My.Computer.FileSystem.SpecialDirectories.MyDocuments}\UnitaleMaker\Projects\{PJNBox.Text}.umproj", File1, False)
Please learn to use string.format.
Also I changed & to new line in file2:
"ENEMYPOSITIONS=0;0" & "EncounterStarting="
I just assumed you forgot to add new line there.
Alss Environment.NewLine is the best option for new lines as it is universal.
Dim File1 As String = String.Format("monster{{{0}COMMENTS=Ribbit, ribbit.;Croak, croak.;Hop, hop.;Meow.{0}COMMANDS=Compliment;Threaten{0}DEFAULT_SPRITE=None{0}NAME=Froggit{0}HP=10{0}ATK=1{0}DEF=0{0}CHECK_MESSAGE=Life is difficult for this enemy.{0}HandleAttack={0}OnDeath={0}HandleCustomCommand={0}}}", Environment.NewLine)
Dim File2 As String = String.Format("{0}encounter{{{0}DEFAULT_MUSIC=Fight{0}ENCOUNTER_TEXT=Froggit hops close.{0}NEXTWAVES=1{0}WAVETIMER=6{0}ARENASIZE=155;130{0}ENEMIES=Froggit{0}ENEMYPOSITIONS=0;0{0}EncounterStarting={0}EnemyDialogueStarting={0}EnemyDialogueEnding={0}DefenseEnding={0}HandleItem={0}HandleSpare={0}EnteringState={0}Update={0}}}", Environment.NewLine)
Dim File3 As String = String.Format("{0}waves{{{0}1=Do Nothing{0}}}{0}end", Environment.NewLine)
My.Computer.FileSystem.WriteAllText(My.Computer.FileSystem.SpecialDirectories.MyDocuments & "\UnitaleMaker\Projects\" & PJNBox.Text & ".umproj", File1 & File2 & File3, False)

how to check if the data being entered exists already

here is my code to submit data to my csv file. How do I check to see if the data already exists before saving it.
Dim csvFile As String = My.Application.Info.DirectoryPath & "\HoseData.csv"
Dim outFile As IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter(csvFile, True)
'If My.Computer.FileSystem.FileExists(csvFile) Then
'outFile.WriteLine("job number, sales order number, date, requested by, serial number, hose type, hose size, fitting 1, fitting 2, qty, oal, cut off, offset, crimp 1, crimp 2, cleaned, pigged", False)
'End If
outFile.WriteLine(TextBox1.Text & "," & TextBox2.Text & "," & """" & DateTimePicker1.Text & """" & "," & ComboBox1.Text & "," & TextBox3.Text & "," & ListBox2.Text & "," & ListBox3.Text & "," & TextBox11.Text & "," & TextBox12.Text & "," & NumericUpDown1.TextAlign & "," & TextBox4.Text & "," & TextBox5.Text & "," & TextBox6.Text & "," & TextBox9.Text & "," & TextBox10.Text & "," & ListBox4.Text & "," & ListBox5.Text)
MessageBox.Show("INPUT WAS SAVED")
Dim butt As System.Windows.Forms.Button = DirectCast(sender, System.Windows.Forms.Button)
butt.Enabled = False
'butt.Visible = False
outFile.Close()
Console.WriteLine(My.Computer.FileSystem.ReadAllText(csvFile))
Is this what you're looking for?
Dim fn As String = My.Application.Info.DirectoryPath & "\HoseData.csv"
Dim fileText As String
Dim outString As String = TextBox1.Text & "," & TextBox2.Text & "," & """" & DateTimePicker1.Text & """" & "," & ComboBox1.Text & "," & TextBox3.Text & "," & ListBox2.Text & "," & ListBox3.Text & "," & TextBox11.Text & "," & TextBox12.Text & "," & NumericUpDown1.TextAlign & "," & TextBox4.Text & "," & TextBox5.Text & "," & TextBox6.Text & "," & TextBox9.Text & "," & TextBox10.Text & "," & ListBox4.Text & "," & ListBox5.Text
Using reader As StreamReader = File.OpenText(fn)
fileText = reader.ReadToEnd
End Using
Using outFile As IO.StreamWriter = My.Computer.FileSystem.OpenTextFileWriter(fn, True)
If fileText.Contains(outString) Then
'do stuff when the string is already present, e.g.:
MessageBox.Show("You've already entered that one.")
Else
'do stuff when it isn't, e.g.:
outFile.WriteLine(outString)
End If
End Using

How to add an incremental count (version) to a string (file) in Excel/VBA?

I have tried a lot of different things, and it seems like I cannot get it to work. So basically, this is a small piece of my complete code.
I am using Microsoft Scripting Runtime to save the file, using the FileExists() to check if the file actually exist before saving.
This is working fine if I remove the IF-statement/Loop.
However, now it feels like FileExists won´t find the string, MyFilePath, when I run it with the IF/Loop. (getdirsubparentpath is a function)
Dim week, UserName As String
Dim MyFile, MyFilePath As String
Dim version As Integer
' Current week, XX
week = Format(Date, "ww")
' Username, e.g. niclas.madsen
UserName = Environ$("UserName")
' Initials, first letter of last and surname to caps
' e.g. niclas.madsen would be NM
UserName = UCase(Left(UserName, 1) & Mid(UserName, InStr(UserName, ".") + 1, 1))
' fix filename for saving purpose
MyFile = Replace(Replace("SupplierOrganization_W", "", ""), ".", "_") _
& "" _
& week _
& " " _
& UserName _
& ".csv"
'SupplierOrganization_WXX NM
MyFilePath = getDirSubParentPath & MyFile
' Look for the MyFilePath, if it exists then
' Add "-1" after the week number, if 1 exists, add 2, etc.
If Len(Dir(MyFilePath)) <> 0 Then
version = 0
Do
version = version + 1
MyFilePath = Dir(getDirSubParentPath & "SupplierOrganization_W" & week & "-" & version & " " & UserName & ".csv")
Loop Until Len(Dir(MyFilePath)) < 0
End If
Dim tmpFile, tmpFilePath As String
tmpFile = getDirSubParentPath & "tmp_file.txt"
Dim tmpString As String
'Dim fso As New FileSystemObject
Dim fso As Object 'scripting.filesystemobject
Set fso = CreateObject("scripting.filesystemobject")
If fso.FileExists(MyFilePath) = True Then
Application.ScreenUpdating = False
Open MyFilePath For Input As #1
Open tmpFile For Output As #2
tmpString = Input(LOF(1), 1) 'read the entire file
tmpString = Replace(tmpString, (Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) _
& Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) _
& Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) _
& Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) _
& Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) _
& Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) _
& Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) _
& Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) _
& Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) _
& Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) _
& Chr(34)), "") 'eliminate double quotation and commas in the first line with UTF-8
Print #2, tmpString 'output result
Close #1
Close #2
fso.DeleteFile (MyFilePath) 'delete original file
fso.CopyFile tmpFile, MyFilePath, True 'rename temp file
fso.DeleteFile (tmpFile) 'delete temp file
Application.ScreenUpdating = True
MsgBox "Finished processing file", vbInformation, "Done!"
Else
MsgBox "Cannot locate the file : " & MyFilePath, vbCritical, "Error"
End If
Set fso = Nothing
End Sub
' Get Parent Sub Directory Path
Function getDirSubParentPath()
getDirSubParentPath = ThisWorkbook.Path & Application.PathSeparator & "CSV" & Application.PathSeparator & "Parent" & Application.PathSeparator
End Function
I finally manage to create a solution that seems viable. However, the code could use some cleaning up :) But it gets the job done.
So basically, I am having some issues with the loop. It will return a file named W16-0 (which should actual just be W16). It should only add the "-X" if W16 is found. So the incremental order should be W16, W16-1, W16-2, etc.
What I am doing is that I try to locate if there is a W16-0 and then replace it with W16. Furthermore, it seems like the loop will give me one higher than the amount of files I have. So that is where I also got an error. So if I had a W16-4, it would ask the macro to find and open a file named W16-5, which would obviously not exist.
If somebody could help me clean up the code, I would be really thankful!
Sub RemoveCommasDoubleQ()
'
' Enable a reference to 'Microsft Scripting Runtime'
' under VBA menu option Tools > References
Dim week, UserName As String
Dim MyFile, MyFilePath As String
Dim version As Integer
Dim fso As Object 'scripting.filesystemobject
Set fso = CreateObject("scripting.filesystemobject")
' Current week, XX
week = Format(Date, "ww")
' Username, e.g. niclas.madsen
UserName = Environ$("UserName")
' Initials, first letter of last and surname to caps
' e.g. niclas.madsen would be NM
UserName = UCase(Left(UserName, 1) & Mid(UserName, InStr(UserName, ".") + 1, 1))
' fix filename for saving purpose
MyFile = Replace(Replace("SupplierOrganization_W", "", ""), ".", "_") _
& "" _
& week _
& " " _
& UserName _
& ".csv"
'SupplierOrganization_WXX NM
'MyFilePath = ThisWorkbook.Path & "\CSV\Parent\" & MyFile
MyFilePath = getDirSubParentPath & MyFile
Debug.Print MyFilePath
Debug.Print "BEFORE LOOP"
'version = 1
Do While Len(Dir(MyFilePath)) <> 0
'// If it does, then append a _000 to the name
'// Change _000 to suit your requirement
MyFilePath = getDirSubParentPath & "SupplierOrganization_W" & week & "-" & version & " " & UserName & ".csv"
'// Increment the counter
version = version + 1
'// and go around again
If MyFilePath = getDirSubParentPath & "SupplierOrganization_W" & week & "-0" & " " & UserName & ".csv" Then
MyFilePath = getDirSubParentPath & "SupplierOrganization_W" & week & " " & UserName & ".csv"
Debug.Print MyFilePath
Debug.Print "IF LOOP"
End If
Loop
Debug.Print MyFilePath
Debug.Print "LOOP"
If fso.FileExists(getDirSubParentPath & "SupplierOrganization_W" & week & "-" & version & " " & UserName & ".csv") = False Then
MyFilePath = getDirSubParentPath & "SupplierOrganization_W" & week & "-" & version - 2 & " " & UserName & ".csv"
MsgBox getDirSubParentPath & "SupplierOrganization_W" & week & "-" & version & " " & UserName & ".csv"
End If
fileName = fso.GetFileName(MyFilePath)
Debug.Print fileName
If MyFilePath = getDirSubParentPath & "SupplierOrganization_W" & week & "-0" & " " & UserName & ".csv" Then
MyFilePath = getDirSubParentPath & "SupplierOrganization_W" & week & " " & UserName & ".csv"
Debug.Print MyFilePath
Debug.Print "her it should be 0"
End If
If MyFilePath = getDirSubParentPath & "SupplierOrganization_W" & week & "-" & " " & UserName & ".csv" Then
MyFilePath = getDirSubParentPath & "SupplierOrganization_W" & week & "-" & version & " " & UserName & ".csv"
End If
Debug.Print "HER ER VI"
fileName = fso.GetFileName(MyFilePath)
Debug.Print fileName
Dim tmpFile, tmpFilePath As String
tmpFile = getDirSubParentPath & "tmp_file.txt"
Dim tmpString As String
Debug.Print "------"
Debug.Print MyFilePath
If fso.FileExists(getDirSubParentPath & "SupplierOrganization_W" & week & "-0" & " " & UserName & ".csv") = True Then
MsgBox "Found the W-0"
MyFilePath = getDirSubParentPath & "SupplierOrganization_W" & week & " " & UserName & ".csv"
End If
Debug.Print "Found 0?"
Debug.Print MyFilePath
If fso.FileExists(MyFilePath) = True Then
Application.ScreenUpdating = False
Open MyFilePath For Input As #1
Open tmpFile For Output As #2
tmpString = Input(LOF(1), 1) 'read the entire file
tmpString = Replace(tmpString, (Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) _
& Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) _
& Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) _
& Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) _
& Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) _
& Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) _
& Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) _
& Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) _
& Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) _
& Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) & Chr(34) & Chr(44) & Chr(34) _
& Chr(34)), "") 'eliminate double quotation and commas in the first line with UTF-8
Print #2, tmpString 'output result
Close #1
Close #2
fso.DeleteFile (MyFilePath) 'delete original file
fso.CopyFile tmpFile, MyFilePath, True 'rename temp file
fso.DeleteFile (tmpFile) 'delete temp file
Application.ScreenUpdating = True
MsgBox "Finished processing file", vbInformation, "Done!"
Else
MsgBox "Cannot locate the file : " & MyFile, vbCritical, "Error"
End If
Set fso = Nothing
End Sub