how to make ascii file for accounting software with vbscript and ASP - vbscript

i need to have an ascii file that have several lines in it for accounting.
in everyline i will have the text and numbers for example numbers and spaces with specific length for every column of data
first column is 3 char length
second is 5
third is 10 and etc...
then i need the end of the line to end with CR + LF
how do i do an ascii file from classic asp and vbscript?

You use FSO (FileSystemObject) to work with files in VBScript. This MSDN Page, Working with Files, shows you how to create and write to files.
Here's a page that has a sample that uses VBScript in an ASP page to create a text file.

My guess, you need to manage a text file like a database. If I'm right, you can do it using Text File Driver.
You need a schema.ini file for the data construct configuration and an existing text file (myfile.csv).
schema.ini
[myfile.csv]
Format=FixedLength
CharacterSet=ANSI
ColNameHeader=False
Col1=first Text Width 3
Col2=second Text Width 5
Col3=third Text Width 10
;[myotherfile.csv]
;Format=FixedLength
;CharacterSet=ANSI
; etc.
myfile.csv (maybe not certain but there are three columns per line with the above configuration.)
abcdefghijklmnopqrstu
123123451234567890
Things to do side of ASP are like classical database operations also.
Const adLockReadOnly = 1
Dim adoCon, adoRS
Set adoCon = Server.CreateObject("Adodb.Connection")
adoCon.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="& Server.Mappath(".") & _
";Extended Properties=""text"""
Set adoRS = Server.CreateObject("Adodb.Recordset")
With adoRS
.Open "Select * From [myfile.csv]", adoCon, , adLockReadOnly
While Not .Eof
Response.Write( _
.Fields("first").Value & " - "& _
.Fields("second").Value & " - "& _
.Fields("third").Value & _
"<br />")
.MoveNext
Wend
.Close
End With
Set adoRS = Nothing
'Data insert : new line ends with CR + LF automatically.
adoCon.Execute "Insert Into [myfile.csv] Values('aaa','bbbbb','cccccccccc')"
adoCon.Close
Set adoCon = Nothing

Related

alternate method to do mail merge to create letters for mIllions of employees country wide

Hi here I am reposting my query..
I have more than million records of employee in oracle table having emp id , name,designation ,office Id and address.
I need to generate letter for each employee using word template(include company logo image), and save it as pdf..
Single pdf for each office, containing letters pertaining to employees of that office...
I have written a batch file to extract data from oracle using pls all and save it in CSV.
Then I call open word document with open_document macro to merge CSV data with word template to generate letters and then save result as pdf
Batch file is
——————————————————
For /f "delims=" %%x in (office I’d.txt) do (
sqlplus userid/pass#emp #createcsv.sql %%x
move /Y %%x.lst %%x.CSV
echo %%x > datasourcename.txt
"C:\Program Files\Microsoft Office\root\Office16\winword.exe" /x /q newtemp.dotm
———————-—————————————
My dotm file contains macro named open_document to perform mail merge and close document after saving pdf file.
This works fine at home PC.. but in office coz macros are disabled,open_document is not working.
To over come that. I write macro code to vbscript file. And called it from batch file.
vbscript :::---
Dim strPath
Dim strDataSource
Dim strTemplate
Dim doc
Dim wrdApp
Set args = Wscript.Arguments
Set wrdApp = CreateObject("Word.Application")
wrdApp.Options.Pagination = False ' suppress pagination
With CreateObject("WScript.Shell")
strPath=.CurrentDirectory
End With
strDataSource = args.Item(0)
strTemplate = "Annexure11.dot"
'Start Word using mailmerge template
wrdApp.Documents.Open (strPath & "\" & strTemplate)
Set oMergeDoc = wrdApp.ActiveDocument
Set oMerge = oMergeDoc.MailMerge
oMerge.MainDocumentType = 0
msgBox "Before Open Datasource"
oMerge.OpenDataSource strPath & "\" & strDataSource &".csv"
msgBox "After Open Datasource"
oMerge.Destination = 0 ' 0 = wdSendToNewDocument
omerge.SuppressBlankLines=True
omerge.DataSource.FirstRecord=1
omerge.DataSource.LastRecord=-16
If omerge.State=2 then oMerge.Execute pause= false
'Do not display the mail merge document
wrdApp.Visible = False
'Save mail merge document as doc and pdf
wrdApp.ActiveDocument.SaveAs strPath & "\"& arg(0) &".pdf" , 17
wrdApp.ActiveDocument.SaveAs strPath &".doc"
omergedoc.Close False
wrdApp.Quit
Set wrdApp = Nothing
GetObject(, "Word.Application").Quit False
when I run the above code, I get msgbox with msg "Before Open Datasource" but never gets msg "After Open Datasource"
*Please suggest some alternate method to get desired output.

Visual Basic Compare Files Task

I currently have this code that will compare between two files only if each file has one column:
Const ForReading = 1
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile1 = objFSO.OpenTextFile("C:\Users\Downloads\Define Kickouts\Metadata_Account.txt", ForReading)
strCurrentDevices = objFile1.ReadAll
objFile1.Close
Set objFile2 = objFSO.OpenTextFile("C:\Users\Downloads\Define Kickouts\DataFile_Account.txt", ForReading)
Do Until objFile2.AtEndOfStream
strAddress = objFile2.ReadLine
If InStr(strCurrentDevices, strAddress) = 0 Then
strNotCurrent = strNotCurrent & strAddress & vbCrLf
End If
Loop
objFile2.Close
Wscript.Echo "Addresses without current devices: " & vbCrLf & strNotCurrent
Set objFile3 = objFSO.CreateTextFile("C:\Users\Downloads\Define Kickouts\Differences.txt")
objFile3.WriteLine strNotCurrent
objFile3.Close
However, I'm trying to figure out a way to create the script where the user can define which columns in the date file to compare against the same set of metadata files.
For example, in the data file, if we want to compare Account, Entity, and Department members, in the script, we would type in columns 1, 4, 5 based on the position in the headers...
Account, Project, Practice, Entity, Department
GL1000,P5000,PP2000,USA,D120
GL2000,P6000,PP3000,CANADA,D220
Then, the script will compare 'always' against the first column in each metadata file...
Account.csv
First column sample values:
GL5000,blah,blah,blah
GL1000,blah,blah,blah
Entity.csv
First column sample values:
ASIA,blah,blah,blah
CANADA,blah,blah,blah
Department.csv
First column sample values:
D100,blah,blah,blah
D200,blah,blah,blah
The output file will have kick-outs from the data file that aren't in the metadata files for each column.
Account Kickout.txt
GL2000
Entity Kickout.txt
USA
Department Kickout.txt
D120
D220
Any help would be appreciated!

VBS Readline - using instr(), to match data whilst ignoring extra spaces

I'm trying to find a way to enhance the reliability of my script. It already works but can be thrown off with a simple extra space in the imported text file.
So I'd like to change my script to Readline if I can find a way to do something like:
Example of text in the .txt file:
FLIGHTS OVER TUSKY PLEASE FILE:
AT OR WEST OF A LINE RBV..LLUND..BAYYS..PUT..DIRECT
FLIGHTS OVER EBONY PLEASE FILE:
AT OR WEST OF A LINE RBV..LLUND..BAYYS..PUT..DIRECT
I know the following doesn't work but if there was a simple modification this would be good.
set WshShell = WScript.CreateObject("WScript.Shell")
Return = WshShell.Run("C:\Downloads\software\putty.exe -load "testing")
set objFSO = CreateObject("Scripting.FileSystemObject")
set objFile = objFSO.OpenTextFile("C:\Users\AW\Desktop\Entries1.txt")
strLine = objFile.ReadAll
If InStr(strLine1, "OVER TUSKY PLEASE") and InStr(strLine2, "BAYYS..PUT..DIRECT") Then
trans307="TUSKY"
ind306="4"
WHAT I'M USING NOW:
I edit the text file in notepad++ to FIND & REPLACE "\n" with "" and "\r" with " " and then it's all one text string and I search for strings within that string.
If InStr(strLine, "FLIGHTS OVER TUSKY PLEASE FILE: AT OR WEST OF A LINE ..RBV..LLUND..BAYYS..PUT..DIRECT") _
or InStr(strLine, "FLIGHTS OVER TUSKY PLEASE FILE: AT OR WEST OF A LINE RBV..LLUND..BAYYS..PUT...DIRECT") Then
trans308C="TUSKY"
ind308C="4"
Problem: If the creators of the text file put another space " " anywhere in this line "AT OR WEST OF A LINE RBV..LLUND..BAYYS..PUT..DIRECT" the script will not identify the string. In the above example I have had to create another or InStr(strLine, "") statement with an extra space or with a couple of dots.
UPDATE:
I will try something like:
set objFSO = CreateObject("Scripting.FileSystemObject")
set objFile = objFSO.OpenTextFile("C:\Users\AW\Desktop\Entries1.txt")
strLine1 = objFile.Readline(1)
strLine2 = objFile.Readline(2)
If InStr(strLine1, "FLIGHTS OVER TUSKY") and InStr(strLine2, "RBV..LLUND..BAYYS..PUT..DIRECT") Then
trans1="TUSKY"
ind1="4"
and see if I can get that to read 2 lines at a time, and loop through the text file.
If you're scared of regex and looking for an alternative, you could create a clunky function to add to your script. Based on your samples, it would seem that fullstops are also never normally used for normal purposes and tend to represent spaces. (I would recommend using Regex instead!)
Using these presumptions, you could create a clunky function like this, that looks for fullstops, and converts them to spaces, removing extra spaces.. Obviously, this relies heavily on your input source files not changing too much - you really should be using a regex to work this stuff out properly.
You could test for the basic expected results using something like the function below.
For example say you had a line of text set in firLine with multiple spaces or fullstops, the function would recognize this:
firLine = "THIS.IS.A.TEST..YOU...SEE MULTIPLE SPACES"
if instr(sanitize(firLine),"THIS IS A TEST YOU SEE MULTIPLE SPACES") then
wscript.echo "Found it"
End If
Here's the clunky function that you could just paste at the end of your script:
Function sanitize(srStr)
Dim preSanitize, srC, spaceMarker
preSanitize = ""
for srC = 1 to len(srStr)
if mid(srStr, srC, 1) = "." then
preSanitize = preSanitize & " "
else
preSanitize = preSanitize & mid(srStr, srC, 1)
End If
spaceMarker = false
sanitize = ""
for srC = 1 to len(preSanitize)
If mid(preSanitize, srC, 1) = " " then
if spaceMarker = false then
sanitize = sanitize & mid(preSanitize, srC, 1)
spaceMarker = true
End If
else
sanitize = sanitize & mid(preSanitize, srC, 1)
spaceMarker = false
End If
Next
End Function
InStr() is a good tool for checking whether a strings contains a fixed/literal string or not. To allow for variation, you should use Regular Expressions (see this or that).
First of all, however, you should work on your specs. Describe in plain words and with some samples what you consider (not) to be a match.
E.g.: A string containing the words "FLIGHTS", "OVER", and "TUSKY" in that order with at least one space in between is a match - "FLIGHTS OVER TUSKY", "FLIGHTS OVER TUSKY"; "FLIGHTS OVER TUSKANY" is a 'near miss' - what about "AIRFLIGHTS OVER TUSKY"?
GREAT NEWS! I finally figured out how to do this.
Here is a snippet from "Entries1.txt"
FLIGHTS OVER BRADD KANNI PLEASE FILE:
VIA J174.RIFLE..ACK..DIRECT
OR RBV.J62.ACK..DIRECT
FLIGHTS OVER KANNI WHALE PLEASE FILE:
VIA J174.RIFLE..ACK..DIRECT OR
FLIGHTS OVER WHALE PLEASE FILE:"
ETC, ETC
set WshShell = WScript.CreateObject("WScript.Shell")
set objFSO = CreateObject("Scripting.FileSystemObject")
set objFile = objFSO.OpenTextFile("C:\Users\AW\Desktop\Entries1.txt")
Do until objFile.AtEndOfStream
firLine = objFile.ReadLine
If InStr(firLine, "FLIGHTS OVER KANNI WHALE PLEASE") Then
secLine = objFile.ReadLine
If InStr(secLine, "J174.RIFLE..ACK..DIRECT") Then
'I'm going to change the below once I piece it all together.
WScript.Echo "works"
Else WScript.Echo "Not found"
'cut, paste and modify all my "IF" statements below
End If
End If
loop

Renaming pdf files with a batch file

I need to either write a batch file or a vbscript that will rename files. I need to keep everything in the file name up to the second "." but delete what comes after the second dot.
This is a sample of what the file names look like:
nnnnnnnnnnnnnnnn.xxxxxxxx.dddddddddd.pdf
n= 16 numbers 0-9
x= date in this format ex:02232008
d= 10 numbers 0-9, this is the part of the file name that I want to delete.
I need the d's from the sample above to be deleted but keep the rest of the file name the same. I need to be able to run this batch file on a folder that contains about 3,000 pdf files. It can either be put right back into the same folder or outputted into a different folder.
FOR /F "USEBACKQ delims=. tokens=1-4" %%F IN (`DIR /B /A-D "C:\Path\To\PDFs\"`) DO (
REN "%%~fF.%%G.%%H.%%I" "%%F.%%G.%%I"
)
If you have files that vary in how many periods there are, just need to add a simple argument to count how many period delimiters exist then execute.
In VBScript, you can use something like
' the file paths. hardcoded, but you could alternatively collect these via command line parameters
Const IN_PATH = "path\to\directory"
Const OUT_PATH = "path\to\another\directory"
' check that the directories exist. you could create them instead, but here
' it just throws an error as that's easier
dim fso: set fso = CreateObject("Scripting.FileSystemObject")
if not fso.FolderExists(IN_PATH) then
err.raise 1,, "Path '" & IN_PATH & "' not found"
end if
if not fso.FolderExists(OUT_PATH) then
err.raise 1,, "Path '" & OUT_PATH & "' not found"
end if
dim infolder: set infolder = fso.GetFolder(IN_PATH)
dim file
for each file in infolder.files
dim name: name = file.name
dim parts: parts = split(name, ".")
' we're expecting a file format of a.b.c.pdf
' so we should have 4 elements in the array (zero-indexed, highest bound is 3)
if UBound(parts) = 3 then
' rebuild the name with the 0th, 1st and 3rd elements
dim newname: newname = parts(0) & "." & parts(1) & "." & parts(3)
' use the move() method to effect the rename
file.move fso.buildpath(OUT_PATH, newname)
else
' log the fact that there's an erroneous file name
WScript.Echo "Unexpected file format: '" & name & "'"
end if
next 'file
You would run it in a batch file thus, redirecting output to a log file
cscript rename-script.vbs > logfile.txt
This assumes that you can simply rely on the period to delimit the parts of the file name rather than the specifics of the format of the delimited parts.
To rearrange the date, which I think is in the parts(1) array element, you can simply extract each bit of the string because it's in a specific format:
'date in format mmddyyyy
dim month_, day_, year_, date_
month_ = left(parts(1), 2)
day_ = mid(parts(1), 3, 2)
year_ = right(parts(1), 4)
date_ = year_ & month_ & day_ ' now yyyymmdd
so when rebuilding the filename, you can replace parts(1) with the new formatted date
dim newname: newname = parts(0) & "." & date_ & "." & parts(3)
Using StringSolver, a semi-automatic renaming tool, just rename the first file, check that the generalized renaming is ok, and then accept it on all other files.
> move 1234567890123456.02232008.1946738250.pdf 1234567890123456.02232008.pdf
Get the explanation:
> move --explain
the file name until the end of the second number + the extension
If you are satisfied, you can run the semi-automated tool using move --auto or the succint version:
> move
DISCLAIMER: I am a co-author of this free software made for academic purposes.

How do I escape a semicolon in VB script?

I have a vbscript file that is reading a file and sending each line to a terminal program. When it comes to a semicolon in the middle of the string, it splits the semicolon at the string.
I have been using this code for quite sometime with other strings with no problems. There is one string per line in the file the script is reading.
The string in the file that is causing the problem is: 2101;99PSP
Here is the code I am using (with a terminal emulation program called Reflections):
Sub NarcoticOrderableItemTurnOff()
''# Constants used by OpenTextFile()
Const ForReading = 1
Const ForWriting = 2
Const ForAppending = 8
Const ICON_INFO = 64 ''# Information message; displays 'i' icon.
Set wshshell = CreateObject("WScript.Shell")
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objTextFile = _
objFSO.OpenTextFile("P:\NarcoticOrderableItems.txt", ForReading)
Session.Transmit "^Orderable Item Edit (CPRS)" & vbCr
Do Until objTextFile.AtEndOfStream
strNextLine = objTextFile.ReadLine
arrC2oderableItemList = Split(strNextLine, ";", 3)
'arrServiceList(0) = Area of Use
'arrServiceList(2) = Printer for that area of use
With Session
.WaitForString "Select ORDERABLE ITEMS NAME:"
.Transmit arrC2oderableItemList(0) & vbCr
.WaitForString "//"
.Transmit "N" & vbCr
.WaitForString "//"
.Transmit vbCr
.WaitForString "//"
.Transmit vbCr
.WaitForString "//"
.Transmit vbCr
End With
Loop
objTextFile.close
Session.MsgBox "All done! C2 Orderable Items turned off!", vbExclamation
''#ErrorHandler:
''# Session.MsgBox Err.Description, vbExclamation + vbOKOnly
End Sub
I think it might have something with the following row of code to do:
arrC2oderableItemList = Split(strNextLine, ";", 3)
If this problem string is the whole line from the file you're reading:
2101;99PSP
The problem is that you're trying to get 3 items from every line and this one only has 2. To account for lines that don't have a 3rd item you should remove the 3rd parameter from your Split function and then check the UBound of the Array before using the 3rd item.
arrC2oderableItemList = Split(strNextLine, ";")
If UBound(arrC2oderableItemList) >= 2 Then
''# There are 3 items or more in the Array (O-based)
''# Can do something with arrC2oderableItemList(2)
Else
''# There are only 2 items (or less) in the Array
''# Do not use arrC2oderableItemList(2)
End If
If you are splitting the lines at semicolons but the text contains extra semicolons, you would have to
search for extra semicolons
change them to a pattern that would not normally be found in the text
split your line
change the pattern from step 2 back to semicolons
Or take the easy route and don't allow extra semicolons in the files your reading.
Posting a few example lines (including the problem line) would allow somebody to help you in writing code to search for the extra semicolons.
If (2101;99PSP) is all that is on the line see Shawn Steward's answer.

Resources