VBScript Readline method ignoring 3rd IF statement - vbscript

My script doesn't seem to check the "secLine" again for the 3rd if statement. It should remember what's stored in "secLine"....hmmmm
This is the text:
PHL DEPARTURES OVER TUSKY PLEASE FILE:
PHL..DITCH.V312.JIMEE..WAVEY..SHLEP..ACK..DIRECT
SCRIPT:
If InStr(firLine, "PHL DEPARTURES OVER TUSKY PLEASE") Then
secLine = objFile.ReadLine
If InStr(secLine, "JFK..PUT..BOS..DIRECT") or InStr(secLine, "PHL..DITCH.J225.JFK..PUT..BOS..DIRECT") Then
trans507="TUSKY"
ind507="1"
bunch of code
If Instr(secLine, "WAVEY..SHLEP..ACK..DIRECT") Then
ind507="2"
bunch of code
End If
End If
End If

Make sure that the first IF succeeds (right now your published data don't match the literal).
Don't use the shortened version(s) of the IF statement. Always use
If ... Then
...
End If
Make sure your indentation truly reflects the script's structure.
In code:
If InStr(firLine, "PHL DEPARTURES OVER TUSKY PLEASE") Then
secLine = objFile.ReadLine
If InStr(secLine, "JFK..PUT..BOS..DIRECT") or InStr(secLine, "PHL..DITCH.J225.JFK..PUT..BOS..DIRECT") Then
trans507="TUSKY"
ind507="1"
End If
If Instr(secLine, "WAVEY..SHLEP..ACK..DIRECT") Then
ind507="2"
End If
End If

Related

Using Find Method in Vbscript for search Word file. Can find character but not replace

I am trying to search through Word documents and try to find a certain character. The ± character to be precise. The code can find the character because I have it print to screen if it found it. But it is unable to replace the character.
I have even tried searching for a random string I knew was in the files such as "3" and replacing it with something random such as "dog". But nothing works. It still finds the characters but does not replace.
Option Explicit
Dim objWord, objDoc, objSelection, oFSO, folder, jj, file
Set objWord = CreateObject("Word.Application")
objWord.Visible = False: objWord.DisplayAlerts = False
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set folder = oFSO.GetFolder("C:\Users\Desktop\myFolder")
For Each file In folder.Files
objWord.Documents.Open file.path, False, True ' path, confirmconversions, readonly
Set objDoc = objWord.ActiveDocument
Set objSelection = objWord.Selection
objSelection.Find.Forward = True
objSelection.Find.MatchWholeWord = False
objSelection.Find.Text = ChrW(177)
objSelection.Find.Replacement.Text = "ChrW(177)"
objSelection.Find.Execute
If objSelection.Find.Found = True then
Wscript.echo "Character Found"
End If
objDoc.close
Next
objWord.Quit
The problem is that the code in the question doesn't specify that a replacement should take place. This is set in the Execute method, as a parameter.
Since this is VBScript rather than VBA it's not possible to use the enumerations (such as wdReplaceAll). Instead, it's necessary to specify the numeric equivalent of an enumeration. VBA without enumerations...
objSelection.Find.Execute Replace:=2, Forward:=True, Wrap:=0
However, VBScript doesn't accept named arguments, so all the arguments need to be specified by position, with "empty commas" if nothing should be specified.
objSelection.Find.Execute , , , , , , , 0, , , 2
To discover the numeric equivalent consult either the VBA Object Library (F2 in the VBA Editor), the Language Reference or use the Immediate Window (Ctrl+G) in the VBA Editor like this: ?wdReplaceAll then press Enter.
objSelection.Find.Execute
should be
objSelection.Find.Execute Replace:=wdReplaceAll, Forward:=True, Wrap:=wdFindContinue
(assuming you want to replace all occurrences
This code running inside a word module will replace all "cat" with "dog"
Sub test()
Dim objdoc As Document
Dim objSelection As Range
Set objdoc = ActiveDocument
Set objSelection = Selection.Range
With objSelection.Find
.Forward = True
.MatchWholeWord = False
.Text = "Cat"
.Replacement.Text = "Dog"
.Execute Replace:=wdReplaceAll, Forward:=True, Wrap:=wdFindContinue
If .Found Then
Debug.Print "Found"
End If
End With
End Sub
However you're running in vbscript using late binding, so possibly there's a type issue - you're selection object may not be a range but a variant?

VBS in HTA Do and Loop

I have the below VB which works but I would like it to work in a HTA.
I cant seem to get it to carry out the loop section any ideas would be appreciated.
The script is used to write labels in ZPL with a StartNumber and EndNumber and the range between will print out on labels.
'Wscript.Echo ZPLText
ObjZebra.Write(ZPLText)
'Loop Counter
StartNumber = StartNumber + 1
'Loop Condition
Loop Until StartNumber > 0 + EndNumber
Wscript.sleep 500
objZebra.Close
Set objZebra = Nothing
End If
End If
Loop
End Function
Your code is still ill formatted. And it doesn't use proper syntax either.
I suggest you get a copy of script56.chm contained in scrdocen.exe (as long it is possible). and look at the do .. loop :
Repeats a block of statements while a condition is True or until a condition becomes True.
Do [{While | Until} condition]
[statements]
[Exit Do]
[statements]
Loop
Or, you can use this syntax:
Do
[statements]
[Exit Do]
[statements]
Loop [{While | Until} condition]

Reading and writing an INI file

I have been toying with the below script to be able to read settings for use with my HTA (creating a game launcher).
Here is my current HTA:
http://pastebin.com/skTgqs5X
It doesn't quite work, it complains of the WScript object being required. While I understand Echo will not work like that in a HTA I am having trouble modifying the code so it will work. Even just removing all Echo references it still has an issue with objOrgIni on line 200 of the below code (with the WScript references removed):
http://pastebin.com/pGjv4Gh1
I don't even need that level of error checking as the INI will exist etc, I just need a simple way to read from and write to an INI in my scripting. Any help you guys can give me in achieving that would be great, it's a little advanced for me just yet, but I'd love an explanation as to why it fails.
There is no easy way to use INI files with VBScript. You'd have to write the functionality yourself or find some existing code that does it.
But do you really need an INI specifically or just a way to save settings? You could just keep all of your settings in a Dictionary object and serialize it as needed.
For example, here are two functions -- LoadSettings and SaveSettings -- that do just that.
Public Function LoadSettings(strFile)
Set LoadSettings = CreateObject("Scripting.Dictionary")
Dim strLine, a
With CreateObject("Scripting.FileSystemObject")
If Not .FileExists(strFile) Then Exit Function
With .OpenTextFile(strFile)
Do Until .AtEndOfStream
strLine = Trim(.ReadLine())
If InStr(strLine, "=") > 0 Then
a = Split(strLine, "=")
LoadSettings.Add a(0), a(1)
End If
Loop
End With
End With
End Function
Sub SaveSettings(d, strFile)
With CreateObject("Scripting.FileSystemObject").CreateTextFile(strFile, True)
Dim k
For Each k In d
.WriteLine k & "=" & d(k)
Next
End With
End Sub
Imagine you had the following settings file saved at c:\settings.txt:
Count=2
Name=Obama
You'd use the functions above like this:
Const SETTINGS_FILE = "c:\settings.txt"
Dim Settings
Set Settings = LoadSettings(SETTINGS_FILE)
' Show all settings...
WScript.Echo Join(Settings.Keys, ", ") ' => Count, Name
' Query a setting...
WScript.Echo Settings("Count") ' => 2
' Update a setting...
Settings("Count") = Settings("Count") + 1
' Add a setting...
Settings("New") = 1
' Save settings...
SaveSettings Settings, SETTINGS_FILE

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

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