With the following block of code, which accesses an html span element, I am unable to check for errors. When I leave the input box empty and press "ok," the value of Err.Number doesn't change. I have user error checking enabled (On Error Resume Next) and I am checking to make sure that Err.Number is not equal to 0 (an error is ocurring). The error is being thrown, but the value of Err.Number is not changing, and this happens both when On Error Resume Next is on as well as when it is off). By the way, what is the default value of Err.Number? How does that value differ from the value of Err.Number after the Err object is cleared? If I am doing anything wrong or stating any wrong information, please inform me.
On Error Resume Next
Dim updateRate
updateRate = 0
RatePrompt()
Sub RatePrompt
updateRate = InputBox("Please enter an update rate (milliseconds)", "Update Rate")
If Err <> 0 Then
Err.Clear()
MsgBox "No Input Was Specified. Please Specify An Input."
RatePrompt()
Else If updateRate > 2000 then
rateDecision = MsgBox ("Consider entering a lower update rate" & vbCrLf & "Would you like to revise update rate?", _
vbYesNo, "Quiclock Alert")
If rateDecision = vbYes then
RatePrompt()
End If
Else If updateRate < 0 then
MsgBox "Update Rate Not Valid. The Default Value of 0 Milliseconds Will Be Used."
updateRate = 0
Else If updateRate = "" then
MsgBox "Update Rate Adjustment Cancelled. The Default Value of 0 Milliseconds Will Be Used."
updateRate = 0
Else
End If
End If
End If
End If
End Sub
TimerStart()
Sub TimerStart
timerID = window.setTimeout("TimeUpdate", updateRate, "VBScript")
End Sub
Sub TimeUpdate
clockOutput.innerHTML = Time()
window.clearTimeout(timerID)
TimerStart()
End Sub
I have spent a large amount of time researching this problem, but have not come to a conclusion. Thanks for the help.
Try next logic skelet for your script:
Dim updateRate, rateRevision
updateRate = InputBox("Please enter an update rate (milliseconds)", "Update Rate")
If IsEmpty( updateRate) Then
'`Cancel` (or equivalent `Esc` or red `×`) pressed/clicked
Else
If IsNumeric( updateRate) Then
updateRate = CLng( updateRate) 'convert string to a Variant of subtype Long
If updateRate > 2000 Then
' do not bother a user by an additional input: offer a value change right now
rateRevision = InputBox ("Consider entering a lower update rate" _
& vbCrLf & "Would you like to revise update rate?", _
"Quiclock Alert", updateRate)
If IsNumeric( rateRevision) Then
rateRevision = CLng( rateRevision)
If rateRevision > 0 Then updateRate = rateRevision
Else
' keep the value > 2000
End If
ElseIf updateRate < 0 Then
updateRate = 0
Else
''
End If
Else
'non-numeric input, use e.g. default value of zero
updateRate = 0
End If
TimerStart()
End If
An explanation and observation to the code:
There is a mistake in the InputBox Function reference. In fact: if the user clicks Cancel (or the red × or presses Esc), then the function returns an empty value, which looks like a zero-length string ("") due to automatic subtype conversion. See the 32213674.vbs script output below.
Comparison Operators (VBScript) reference shows how expressions are compared or what results from the comparison, depending on the underlying subtype; particularly: if one expression is numeric and the other is a string then the numeric expression is less than the string expression.
32213674.vbs script:
option explicit
On Error GoTo 0
Dim sValInput
Call doOutput( True, sValInput)
Do While True
sValInput = InputBox( _
"Please enter any value (and `OK`) to see its features:" & vbCR _
& "a date-like value, e.g. " & FormatDateTime( Now, vbShortDate) & vbCR _
& "a time-like value, e.g. " & FormatDateTime( Now, vbShortTime) & vbCR _
& "a number-like value, e.g. 123456" & vbCR _
& "a string of your choice" & vbCR _
& "an empty string (i.e. only click `OK`)" & vbCR _
& "or press `Esc` or click red `×` or `Cancel` button to exit the loop" _
, "InputBox test loop")
Call doOutput( False, sValInput)
If IsEmpty( sValInput) Then Exit Do
Loop
Sub doOutput( bHeader, sVal)
If Instr(1, Wscript.FullName, "cscript.exe", vbTextCompare) > 0 Then
If bHeader Then
Wscript.Echo sHead()
Else
Wscript.Echo sLine( sVal)
End If
Else
If bHeader Then
Else
MsgBox( sHead() & vbCR & sLine( sVal))
End If
End If
End Sub
Function sHead()
sHead = "Empty?" & vbTab & "Number?" & vbTab & _
"Date?" & vbTab & "VarType" & vbTab & "TypeName" & "[value]"
End Function
Function sLine( sValue)
sLine = IsEmpty( sValue) & vbTab & IsNumeric( sValue) & vbTab & _
IsDate( sValue) & vbTab & VarType( sValue) & vbTab & _
TypeName( sValue) & vbTab & "[" & sValue & "]"
End Function
Output:
==>cscript //NOLOGO D:\VB_scripts\SO\32213674.vbs
Empty? Number? Date? VarType TypeName[value]
False False True 8 String [2015-08-26]
False False True 8 String [22:01:05]
False True False 8 String [123456]
False False False 8 String [qwertz]
False False False 8 String []
True True False 0 Empty []
Related
When I use this code:
Private Sub Application_ItemSend(ByVal Item As Object, Cancel As Boolean)
Dim retMB As Variant
Dim strBody As String
Dim iIndex As Long
On Error GoTo handleError
iIndex = InStr(Item.Body, "attach", "attachment")
If iIndex > 0 And Item.Attachments.Count = 1 Then
retMB = MsgBox("Forgot attachment?" & vbCrLf & vbCrLf & "Continue?", vbQuestion + vbYesNo + vbDefaultButton2 + vbMsgBoxSetForeground)
If retMB = vbNo Then Cancel = True
End If
handleError:
If Err.Number <> 0 Then
MsgBox "Sending with no attachments!" & Err.Description, vbExclamation, "ERROR!!!"
End If
End Sub
I want to get the "Forgot attachment?" dialog box with the message. Except I only get the "Sending with no attachments!" dialog box. Why doesn't the reminder dialog appear when the email doesn't have an attachment?
Your check must be Item.Attachments.Count = 0.
I am attempting to write a small script in VBScript just purely for my home use, which is run prior to a scheduled backup in Macrium Reflect.
I am stuck on one seemingly small issue and that is error handling when the Network Drive is physically disconnected, i.e. the cable is not attached.
At the moment the script check to see if the Drive is already attached, if the drive is not attached then a message is displayed telling the user to connect the cable and press YES.
Now, all things being well the user would have connected the cable as asked and then pressed the YES button but I want to catch the times when YES was pressed before attaching the drive's cable.
Within the code there's an 'On Error Resume Next' which masks this eventuality, so I comment out this line & indeed I get an Error 'The Network Path Was Not Found' on line 40:
objNetwork.MapNetworkDrive strDriveLetter, strRemotePath, _
I want to use this caught error to display an alert to the user that the drive has not yet been connected, please connect and retry & KEEP RETRYING until the drive is actually connected.
My problem is I cannot seem to find where to add any error handling code to display this message.
Here's my code:
Option Explicit
Dim strDriveLetter, strRemotePath, strUser, strPassword, strProfile, strName, objNetwork, objShell, CheckDrive, AlreadyConnected, intDrive
' The section sets the variables.
strDriveLetter = "X:"
strRemotePath = "\\192.168.1.1\shared"
strUser = "user"
strPassword = "password"
strProfile = "true"
strName = "Backup Drive"
' This sections creates two objects:
' objShell and objNetwork and counts the drives
Set objShell = CreateObject("WScript.Shell")
Set objNetwork = CreateObject("WScript.Network")
Set CheckDrive = objNetwork.EnumNetworkDrives()
' This section deals with a For ... Next loop
' See how it compares the enumerated drive letters
' with strDriveLetter
On Error Resume Next
AlreadyConnected = False
For intDrive = 0 To CheckDrive.Count - 1 Step 2
If CheckDrive.Item(intDrive) =strDriveLetter _
Then AlreadyConnected = True
Next
If AlreadyConnected = False Then
Dim result
result = MsgBox("A Backup Is Now Due But The Drive Is Not Connected." & vbNewLine & vbNewLine & "Please Connect The Drive & Press YES To Continue." & vbNewLine & vbNewLine & "If You Wish To Postpone Backup Then Press NO Now.", 4 + 32, "BACKUP DRIVE NOT CONNECTED")
If result = 7 Then
WScript.Quit
Else
Call MapDRV
End If
Sub MapDRV()
Set objNetwork = WScript.CreateObject("WScript.Network")
objNetwork.MapNetworkDrive strDriveLetter, strRemotePath, _
strProfile, strUser, strPassword
Set objShell = CreateObject("Shell.Application")
objShell.NameSpace(strDriveLetter).Self.Name = strName
End Sub
WScript.Quit
The error handling code is something along these lines:
If Err.Number <> 0 Then
'error handling:
'ALERT USER HERE
Err.Clear
End If
Any help would be appreciated
Err Object (VBScript) reference does not give useful guide. You need to trap an error or success separate for every run-time error prone action.
Common rule (best practice): keep error handling disabled via On Error GoTo 0 and enable it only for suspected actions.
For instance, there could me more than one reason why MapNetworkDrive method could fail (server off-line, user blocked, wrong/changed password etc.):
Sub MapDRV
Dim errResult
Set objNetwork = WScript.CreateObject("WScript.Network")
errResult = ""
On Error Resume Next
objNetwork.MapNetworkDrive strDriveLetter, strRemotePath _
, strProfile, strUser, strPassword
If Err.Number = 0 Then
On Error GoTo 0
Set objShell = CreateObject("Shell.Application")
objShell.NameSpace(strDriveLetter).Self.Name = strName
Else
errResult = Err.Number & " 0x" & Hex(Err.Number) & " " & Err.Source
errResult = errResult & vbNewLine & Err.Description
On Error GoTo 0
MsgBox errResult, vbOKOnly + vbCritical, "Error occurred"
End If
End Sub
The whole script then could look as follows:
Option Explicit
On Error GoTo 0
Dim strResult: strResult = Wscript.ScriptName
Dim strDriveLetter, strRemotePath, strUser, strPassword, strProfile , strName _
, objNetwork, objShell, CheckDrive, AlreadyConnected, intDrive
' The section sets the variables.
strDriveLetter = "X:"
strRemotePath = "\\192.168.1.1\shared"
strUser = "user"
strPassword = "password"
strProfile = "true"
strName = "Backup Drive"
' This sections creates two objects:
' objShell and objNetwork and counts the drives
Set objShell = CreateObject("WScript.Shell")
Set objNetwork = CreateObject("WScript.Network")
' This section deals with a For ... Next loop
' See how it compares the enumerated drive letters with strDriveLetter
Dim result, toShare
AlreadyConnected = False
Do While AlreadyConnected = False
strResult = strResult & vbNewLine & "--- new check"
AlreadyConnected = False
Set CheckDrive = objNetwork.EnumNetworkDrives()
For intDrive = 0 To CheckDrive.Count - 1 Step 2
If CheckDrive.Item(intDrive) = strDriveLetter Then
AlreadyConnected = True
toShare = CheckDrive.Item(intDrive + 1)
End If
strResult = strResult & vbNewLine & CheckDrive.Item(intDrive)
strResult = strResult & vbTab & CheckDrive.Item(intDrive + 1)
Next
If AlreadyConnected Then Exit Do
result = MsgBox("A Backup Is Now Due But The Drive Is Not Connected." _
& vbNewLine & vbNewLine & "If you wish to ..." _
& vbNewLine & vbTab & "... postpone backup then press ABORT." _
& vbNewLine & vbTab & "... backup to " & strRemotePath & " then press RETRY." _
& vbNewLine & "Otherwise, please connect the drive & press IGNORE to continue." _
, vbAbortRetryIgnore + vbQuestion, "BACKUP DRIVE NOT CONNECTED")
Select Case result
Case vbAbort
Call scriptQuit
Case vbRetry
Call MapDRV
Case Else
' The Case Else clause is not required
End Select
Loop
strResult = strResult & vbNewLine & "copy here to " & toShare
Sub MapDRV
' no need to redefine: WshNetwork Object is already defined
' Set objNetwork = WScript.CreateObject("WScript.Network")
Dim errResult
On Error Resume Next
objNetwork.MapNetworkDrive strDriveLetter, strRemotePath _
, strProfile, strUser, strPassword
If Err.Number = 0 Then
On Error GoTo 0
Set objShell = CreateObject("Shell.Application")
objShell.NameSpace(strDriveLetter).Self.Name = strName
Else
errResult = Err.Number & " 0x" & Hex(Err.Number) & " " & Err.Source
errResult = errResult & vbNewLine & Err.Description
On Error GoTo 0
MsgBox errResult, vbOKOnly + vbCritical, "Error occurred"
strResult = strResult & vbNewLine & vbNewLine & errResult
End If
End Sub
Call scriptQuit
Sub scriptQuit
Wscript.Echo strResult
Wscript.Quit
End Sub
Please note that strResult variable is there merely for debugging purposes to see next output:
==> cscript D:\VB_scripts\SO\37776762.vbs
37776762.vbs
--- new check
Y: \\S-PC\VB_scripts_help
-2147024843 0x80070035 WSHNetwork.MapNetworkDrive
The network path was not found.
--- new check
Y: \\S-PC\VB_scripts_help
--- new check
Y: \\S-PC\VB_scripts_help
X: \\S-PC\test
copy here to \\S-PC\test
==>
Above output corresponds to next actions:
run script
1st --- new check found Y: mapped disk; then invoked Retry action failed (network path was not found);
2nd --- new check found Y: mapped disk again; then mapped disk X: manually and then invoked Ignore action;
3rd --- new check found Y: and X: mapped disks;
Do While loop exited and script continues to next action.
For completeness, following output shows invoked Abort action:
==> net use x: /delete
x: was deleted successfully.
==> cscript D:\VB_scripts\SO\37776762.vbs
37776762.vbs
--- new check
Y: \\S-PC\VB_scripts_help
==>
I'm trying to make a script to connect a network printer to a user computer.
The script uses the computer name who needs the printer as a parameter.
Printers names are similar their printserver name, eg. server_USA has printers like printer_USA01, printer_USA02.
But it's throwing the error "Sub or Function not defined" when arrives at the first like... why ?
Set shl = WScript.CreateObject("WScript.Shell")
strName = Wscript.Arguments.Item(0)
'input Printer name
strPrinter = InputBox("Please enter share name of printer to install:", _
"Add network printer")
if strPrinter = "" then
msgbox "Can't be empty."
WScript.quit
elseif strPrinter Like "printer_USA*" then
strServer = server_USA
elseif strPrinter Like "printer_SPAIN*" then
strServer = server_SPAIN
else
'Printer name NOT registered, input printserver manually:
strServer = inputbox("Please enter the name of the printserver","printserver")
if strServer = "" then
msgbox "Can't be empty."
WScript.quit
End if
End if
'ADD
shl.run "RUNDLL32 PRINTUI.DLL,PrintUIEntry /ga /c\\" & strName & " /n\\" & strServer & "\" & strPrinter
there is no Like operator in VBScript. You could use Instr.
if strPrinter = "" then
msgbox "Can't be empty."
WScript.quit
elseif Instr( 1, strPrinter, "printer_USA", vbTextCompare ) > 0 then
strServer = server_USA
The vbTextCompare constant ( value=1) is used to Perform a textual comparison
you can use StrComp to have same result in this way
If StrComp(strPrinter,"printer_USA",vbTextCompare)=0 then
strServer = server_USA
End IF
equal 0 mean zero different between strPrinter and printer_USA with ignore the letter case because we use vbTextCompare .
You can replace vbTextCompare with 1 and you will have same result.
If letter case is important you can use vbBinaryCompare or 0.
A way to do that with select case. This version of instr() is case sensitive, but other versions aren't. instr() returns the position of the found substring, which here is always one.
select case 1
case instr(strPrinter, "") + 1
wscript.echo "empty"
case instr(strPrinter, "printer_USA")
wscript.echo "server_USA"
case instr(strPrinter, "printer_SPAIN")
wscript.echo "server_SPAIN"
case instr(strPrinter, "printer_ITALY"), instr(strPrinter, "printer_RUSSIA")
wscript.echo "other known ones"
case else
wscript.echo "not registered"
end select
I used the following alternative (VBScript Regular Expressions)…
Uses slightly different syntax from LIKE but easiest solution to make a match successfully similar to LIKE operator.
dim regExp
set regExp=CreateObject("VBScript.RegExp")
regExp.IgnoreCase = true
regExp.Global = true
regxp.Pattern = ".*Test Pattern.*" ' example only, basic pattern
if regExp.Test(MyString) then
' match successful
end if
I have this file that makes a computer say something. I want it to loop with a VbCancel function. I get this error. Code so far:
Do
Dim Message, Speak
Message=InputBox("Enter text","Speak")
Set Speak=CreateObject("sapi.spvoice")
MsgBox ("You entered: " & Speak)
Speak.Speak Message
If Len(Speak) = 0 Then
MyMessageBox = MsgBox("Click Yes if you mean to Cancel." & vbCrLf & _
"If you mean to enter a zero length string, click No.", vbYesNo, "DO YOU MEAN TO CANCEL?")
If MyMessageBox = vbYes Then
MsgBox "Operation Cancelled"
Exit Sub
End If
Loop
BTW the error is Invalid exit statement
I'm working on Windows 7
Dim Message, Speak
Do
Message=InputBox("Enter text","Speak")
Set Speak=CreateObject("sapi.spvoice")
MsgBox ("You entered: " & Message)
Speak.Speak Message
If Len(Message) = 0 Then
MyMessageBox = MsgBox("Click Yes if you mean to Cancel." & vbCrLf & _
"If you mean to enter a zero length string, click No.", vbYesNo, "DO YOU MEAN TO CANCEL?")
If MyMessageBox = vbYes Then
MsgBox "Operation Cancelled"
Exit Do
End If
End If
Loop
You had several issues here
Exit Sub is for subroutines. You were trying to exit a Do loop
Speak is an object. I dont know if it has a string property but it is not itself a string. Both Len(Speak) and "You entered: " & Speak has Speak changed to Message.
You were missing an End If
I moved the Dim statements out of the loop. No point recreating the object over and over again.
Dim Message, Speak
Do
Message=InputBox("Enter text","Speak")
Set Speak=CreateObject("sapi.spvoice")
MsgBox ("You entered: " & Message)
Speak.Speak Message
If Len(Message) = 0 Then
MyMessageBox = MsgBox("Click Yes if you mean to Cancel." & vbCrLf & _
"If you mean to enter a zero length string, click No.", vbYesNo, "DO YOU MEAN TO CANCEL?")
If MyMessageBox = vbYes Then
MsgBox "Operation Cancelled"
Exit Do
End If
End If
Loop
hey guys i know this may sound stupid, but i am stuck with this question in my head...im really new to this wscript or vbscripting....at the time of writing i figured out how to open IE using wscript...heres the code
Set WshShell = WScript.CreateObject("WScript.Shell")
Return = WshShell.Run("iexplore.exe www.bbc.co.uk", 1)
but i cant figure out how to check if firefox is installed, then open firefox, if chrome is installed, open chrome, and the same thing goes for all the browser types.....
Update:
I did a little research and thought why not check the registry for that, so i came up with this script for checking the registry, now i dont know why but this always gives the same output "key does not exists" event though i have this registry in my system
keyTest = keyExists("HKEY_LOCAL_MACHINE\SOFTWARE\Mozilla\Mozilla Firefox")
If keyTest = False Then
wscript.echo "Key does not exist"
Elseif keyTest = True then
wscript.echo "Key exists"
End if
Function keyExists (RegistryKey)
If (Right(RegistryKey, 1) <> "\") Then
RegistryKeyExists = false
Else
On Error Resume Next
WshShell.RegRead RegistryKey
Select Case Err
Case 0:
keyExists = true
Case &h80070002:
ErrDescription = Replace(Err.description, RegistryKey, "")
Err.clear
WshShell.RegRead "HKEY_ERROR\"
If (ErrDescription <> Replace(Err.description, _
"HKEY_ERROR\", "")) Then
keyExists = true
Else
RegistryKeyExists = false
End If
Case Else:
keyExists = false
End Select
On Error Goto 0
End If
End Function
Problems in your example:
In keyExists(), a variable named RegistryKeyExists is being used for the return value from the function when keyExists is intended.
The Shell object variable WshShell is never instantiated via CreateObject().
The value of the registry key of interest does not end with a backslash.
Here's my streamlined version of your code which I believe accomplishes your objective:
Option Explicit ' programming with your seatbelt on :-)
Dim keys(4)
keys(0) = "HKEY_LOCAL_MACHINE\SOFTWARE\Mozilla\Mozilla Firefox"
keys(1) = "HKEY_LOCAL_MACHINE\SOFTWARE\Mozilla\Mozilla Firefox\"
keys(2) = "HKEY_LOCAL_MACHINE\Bad\Key\"
keys(3) = "BAD\Root\On\This\Key\Causes\Exception"
keys(4) = "HKLM\SOFTWARE\Microsoft\Internet Explorer\"
On Error Resume Next
Dim i, key
For i = 0 To UBound(keys)
key = keyExists(keys(i))
If Err Then
WScript.Echo "An exception occurred reading registry key" _
& " '" & keys(i) & "':" _
& " [" & Err.Number & "] " _
& Err.Description _
& ""
Else
If keyExists(keys(i)) Then
WScript.Echo "Key *exists*: [" & keys(i) & "]"
Else
WScript.Echo "Key does *not* exist: [" & keys(i) & "]"
End If
End If
WScript.Echo "--"
Next
Function keyExists (RegistryKey)
Dim keyVal, errNum, errDesc
keyExists = False
On Error Resume Next
Dim WshShell : Set WshShell = CreateObject("WScript.Shell")
keyVal = WshShell.RegRead(RegistryKey)
Select Case Err
Case 0
keyExists = True
Case &h80070002
' key does not exist
Case Else
errNum = Err.Number
errDesc = Err.Description
On Error GoTo 0
Err.Raise vbObjectError + 1, "WScript.Shell", _
"Something went wrong reading the registry:" _
& " [" & Hex(errNum) & "] " & errDesc
End Select
On Error GoTo 0
Set WshShell = Nothing
End Function
' End
Generally following code can be used to find out to get List of All Installed Software.
Here I have used Message box to display this list, you can use if condition to find out desired software is installed or not............
' List All Installed Software
Const HKLM = &H80000002 'HKEY_LOCAL_MACHINE
strComputer = "."
strKey = "SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall\"
strEntry1a = "DisplayName"
Set objReg = GetObject("winmgmts://" & strComputer & _
"/root/default:StdRegProv")
objReg.EnumKey HKLM, strKey, arrSubkeys
For Each strSubkey In arrSubkeys
intRet1 = objReg.GetStringValue(HKLM, strKey & strSubkey, _
strEntry1a, strValue1)
If strValue1 <> "" Then
MsgBox VbCrLf & "Display Name: " & strValue1
End If
Next
I have tried this code on machine & found that,it just listing Firefox browser, even when i have installed chrome & IE.So this regular method wont work surely for everyone. After that I have checked registry and found that,all browser are listed on.....
HKEY_LOCAL_MACHINE\SOFTWARE\Clients\StartMenuInternet\
So we can write code to find is is particular browser is installed or not.
Following sample code to check if Chrome & Firefox is installed or not and if installed open it with URL passed
Set WshShell = CreateObject("WScript.Shell")
Const HKEY_LOCAL_MACHINE = &H80000002
strComputer = "."
Set oReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & _
strComputer & "\root\default:StdRegProv")
strKeyPath = "SOFTWARE\Clients\StartMenuInternet\chrome.exe\shell\open\command\"
strValueName = ""
oReg.GetStringValue HKEY_LOCAL_MACHINE,strKeyPath,strValueName,strValue
If InStr(1,strValue,"chrome",vbTextCompare) Then WshShell.Run("chrome www.google.com")
strKeyPath = "SOFTWARE\Clients\StartMenuInternet\FIREFOX.EXE\shell\open\command\"
strValueName = ""
oReg.GetStringValue HKEY_LOCAL_MACHINE,strKeyPath,strValueName,strValue
If InStr(1,strValue,"firefox",vbTextCompare) Then WshShell.Run("firefox www.google.com")
Similarly you can modify this code for IE, Opera & Safari
Hope this helps.......