Reputation: 129
I have a script as a counter subscribing to the file C:\tmp\yourtextfile.txt:
Set myFSO = CreateObject ("Scripting.FileSystemObject")
Licznik_ID = myFSO.OpenTextFile ("C:\tmp\yourtextfile.txt"). ReadAll
Licznik_ID + 1 = Licznik_ID
myFSO.OpenTextFile ( "C:\tmp\yourtextfile.txt", 2, True) .write (Licznik_ID)
how to do that instead of counting the counter in such a way:
1 2 3 4 5 6 7 8 9 10 11 e.t.c.
the Counter in the following way to read and save the file to C:\tmp\yourtextfile.txt?
00000001 00000002 00000003 00000004 00000005 00000006 00000007 00000008 00000009 00000010 00000011 e.t.c.
Upvotes: 2
Views: 425
Reputation: 42192
You need to first read the text, get the last part with split, convert it to a number, add 1, concatanate that that tot the string and write to the file. Here your adapted script
Function PadZeros(s, l)
PadZeros = Right("00000000" & s, l)
End Function
Dim myFSO, Licznik_ID, txt, arr
Set myFSO = CreateObject ("Scripting.FileSystemObject")
txt = myFSO.OpenTextFile ("C:\tmp\yourtextfile.txt").ReadAll
arr = split(txt, " ")
Licznik_ID = arr(UBound(arr))
txt = txt & " " & PadZeros(CInt(Licznik_ID)+1, 8)
myFSO.OpenTextFile ("C:\tmp\yourtextfile.txt", 2, True).write (txt)
As an extra: since I'm switched to Ruby here the equivalent in that language to show you the power of Ruby
filename = "C:/tmp/yourtextfile.txt"
txt = File.read(filename)
txt += " %08d" % ((txt.split.last.to_i)+1).to_s
File.write(filename, txt)
or as a single line
File.read(filename).tap {|txt| File.write(filename, txt + " %08d" % ((txt.split.last.to_i)+1))}
It's pretty much explaining itself, the %08d is a formatting template for the string which takes the number and adds until 8 leading zero's, the tap method enumerates the object, in this case the last line of the file
Upvotes: 2
Reputation: 19641
First of all, have you tested this code? because it shouldn't work..
You should replace this line Licznik_ID + 1 = Licznik_ID
with Licznik_ID = Licznik_ID + 1
.
Now, in order to pad the number with leading zeros in vbscript, you'll have to write a function for that. You can use the following code:
Function LPad(str, l)
Dim n : n = 0
If l > Len(str) Then n = l - Len(str)
LPad = String(n, "0") & str
End Function
Set myFSO = CreateObject ("Scripting.FileSystemObject")
Licznik_ID = myFSO.OpenTextFile ("C:\tmp\yourtextfile.txt").ReadAll
Licznik_ID = Licznik_ID + 1
myFSO.OpenTextFile("C:\tmp\yourtextfile.txt", 2, True).write(LPad(Licznik_ID, 8))
Where LPad(Licznik_ID, 8)
adds leading zeros to your number to produce an eight digit number. You can replace 8
with the preferred digit numbers.
Hope that helps :)
Upvotes: 0