How to identify between ok and cancel button in inputbox - vbscript

Hi Hi I have to write a code where if the user clicks enters something in the input box it should proceed further.If it doesnot enter any value it should throw back the same question again again.This i have already achieved,but my problem is when user click on CANCEl it agains asks the same question whereas it ishould exit .I am very new to VB Script .Plz help me how to handle these buttons?Below is my existing code
Do while x=0
strAnswer = InputBox("Please enter the file extension * For all files:", _
"File Extension")
If strAnswer = "" Then
MsgBox"You must enter an extension."
Else
a=strAnswer
Exit Do
End If
Loop
intRow = 2
'strFileName = "T:\public\Madhumita\New.xls"
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
Set objWorkbook = objExcel.Workbooks.Add()
'objWorkbook.SaveAs(strFileName)
objExcel.Cells(1, 1).Value = "Folder"
objExcel.Cells(1, 2).Value = "File Name"
objStartFolder = "T:\public\Madhumita\Madhu"
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFSO.GetFolder(objStartFolder)
Set colFiles = objFolder.Files
If a="*" Then
For Each objFile in colFiles
objExcel.Cells(intRow, 1).Value = objfolder.Name
objExcel.Cells(intRow, 2).Value = objFile.Name
intRow = intRow + 1
Next
else
For Each objFile in colFiles
m=objFSO.GetExtensionName( objFile.Path )
If m=a Then
objExcel.Cells(intRow, 1).Value = objfolder.Name
objExcel.Cells(intRow, 2).Value = objFile.Name
intRow = intRow + 1
End If
Next
End If
objExcel.Range("A1:B1").Select
objExcel.Selection.Font.Bold = True
objExcel.Cells.EntireColumn.AutoFit
Sub SaveAs()
Application.Dialogs(xlDialogSaveAs).Show
End Sub
objExcel.Quit
MsgBox "Done"

You need to deal with (at least) three cases - InputBox() returns:
an empty value (Empty, vbEmpty) because the user pressed Cancel or closed the dialog
an empty string ("") or a string of blanks (" ")
a (hopefully) valid string
In code:
Option Explicit
Do While True
Dim vInp : vInp = InputBox("ee")
WScript.Echo TypeName(vInp)
Select Case True
Case IsEmpty(vInp)
WScript.Echo "Abort"
Exit Do
Case "" = Trim(vInp)
WScript.Echo "Try again"
Case Else
WScript.Echo "Work with " & vInp
Exit Do
End Select
Loop
sample output:
String
Try again
Empty
Abort
String
Work with aaa
Sorry to say, but the Docs just lie:
If the user clicks OK or presses ENTER, the InputBox function returns
whatever is in the text box. If the user clicks Cancel, the function
returns a zero-length string ("").
It should be:
... If the user clicks Cancel, the function returns an empty value
(TypeName Empty, VarType vbEmpty).

For InputBox(), you can use the default value to determine if the user clicked Cancel or if they clicked OK or hit Enter to continue without entering a value:
Sub Get_TIN()
TIN = Trim(InputBox("Enter the provider TIN:", "Provider TIN", "ex. 123456789"))
If TIN = "" Then 'When CANCEL is clicked because "TIN" will be empty.
MsgBox "You pressed Cancel. Program will now end.", vbExclamation + vbOKOnly, "Macro End"
Exit Sub
End If
If IsEmpty(TIN) = False Then 'When OK is clicked or Enter pressed because default text will be stored. Next, set TIN to "".
TIN = ""
End If
End Sub

I'm using VBS and my investigation into cancel/ok revealed the following:
Cancel returns an empty string AND a zero length string - same thing you say?, apparently not.
Ok returns a zero length string only.
I use the code below to differentiate.
if IsEmpty(nmbr) then 'cancel button pressed ?
nmbr = "x"
end if
if not IsEmpty(nmbr) then 'ok button pressed ?
if len(nmbr) = 0 then
nmbr = "ok"
end if
end if

Related

Send selected files via Email using VBScript [duplicate]

This question already has answers here:
VBScript to send email without running Outlook
(2 answers)
Closed 3 years ago.
I want to select files within Windows Explorer and then by pressing a shortcut (assigned to a VBS-script) to send these files with Outlook (2010).
I found two working code snippets:
Code snippet1 (Creating Email):
Dim objOutl
Set objOutl = CreateObject("Outlook.Application")
Set objMailItem = objOutl.CreateItem(olMailItem)
'comment the next line if you do not want to see the outlook window
objMailItem.Display
strEmailAddr = "test#test.com"
objMailItem.Recipients.Add strEmailAddr
objMailItem.Body = "Hi, this is the body.."
objMailItem.Attachments.Add "C:\test.txt"
'objMailItem.Send
Set objMailItem = nothing
Set objOutl = nothing
Code snippet2 (returning paths of the selected files in Windows Explorer):
Function GetSelectedFiles() 'Returns paths as array of strings
Dim FileList, Window, SelectedItem
'avoid duplicates by storing paths in dictionary keys
Set FileList = CreateObject("Scripting.Dictionary")
With CreateObject("Shell.Application")
For Each Window In .Windows
'skip IE Windows
If InStr(1, Window.FullName, "iexplore.exe", vbTextCompare) = 0 Then
For Each SelectedItem In Window.Document.SelectedItems
FileList(SelectedItem.Path) = Null
'MsgBox SelectedItem.Path
Next
End If
Next
End With
GetSelectedFiles = FileList.Keys 'array of paths
End Function
MsgBox "Click OK after selecting the items", vbOKOnly Or vbInformation, "Select a few items"
Dim SelectedFiles
SelectedFiles = GetSelectedFiles
MsgBox "You selected: " & vbNewLine & vbNewLine & Join(SelectedFiles, vbNewLine), vbOKOnly Or vbInformation, "Selected Items"
How to combine these code snippets to achieve my purpose? I tried to give the SelectedItem.Path a variable to add it to the objMailItem.Attachments.Add but it is not working.
I tried the cdo approach but this issue seems to be more complex. I have an office365-account and the configuration settings seems to differ from VBScript to send email without running Outlook.
Yesss I got it working and it is very cool, I love it :-)
Dim x ,objOutl ,objMailItem ,strEmailAddr
Set objOutl = CreateObject("Outlook.Application")
Set objMailItem = objOutl.CreateItem(olMailItem)
'comment the next line if you do not want to see the outlook window
objMailItem.Display
strEmailAddr = "test#test.com"
objMailItem.Recipients.Add strEmailAddr
objMailItem.Subject = "Test"
objMailItem.Body = "Hi, this is the body.."
'in the next line it will jump in to function "GetSelectedFiles"
x=GetSelectedFiles
'comment out the next three lines for sending directly..
'objMailItem.Send
'Set objMailItem = nothing
'Set objOutl = nothing
Function GetSelectedFiles() 'Returns paths as array of strings
Dim FileList, Window, SelectedItem
'avoid duplicates by storing paths in dictionary keys
Set FileList = CreateObject("Scripting.Dictionary")
With CreateObject("Shell.Application")
For Each Window In .Windows
'skip IE Windows
If InStr(1, Window.FullName, "iexplore.exe", vbTextCompare) = 0 Then
For Each SelectedItem In Window.Document.SelectedItems
FileList(SelectedItem.Path) = Null
x = SelectedItem.Path
'next line is just for debugging..
'msgBox x
'The next line was the solution
objMailItem.Attachments.Add x
Next
End If
Next
End With
GetSelectedFiles = x 'array of paths
End Function

How Can I pause speak command in vbscript? I have to play it from the same paused position

How Can I pause speak command in vbscript? I have to play it from the same paused position.
Code block:
Dim Speak, Path
Path = "string"
Path = "C:\Users\sony\Desktop\TheReunion.txt"
const ForReading = 1
Set objFileToRead = CreateObject("Scripting.FileSystemObject").OpenTextFile(Path,ForReading)
strFileText = objFileToRead.ReadAll()
Set Speak=CreateObject("sapi.spvoice")
Speak.Speak strFileText
objFileToRead.Close
Set objFileToRead = Nothing
You need to call the speak method asynchronously before using the pause and resume methods as mentioned by LotPings in the comments.
Code:
Dim Speak, Path
Path = "string"
Path = "C:\Users\sony\Desktop\TheReunion.txt"
const ForReading = 1
Set objFileToRead = CreateObject("Scripting.FileSystemObject").OpenTextFile(Path,ForReading)
strFileText = objFileToRead.ReadAll()
Set Speak=CreateObject("sapi.spvoice")
Speak.Speak strFileText,1 '1=Asynchronous. Click the link below for other possible values "SpeechVoiceSpeakFlags"
'Due to async call to speak method, we can proceed with the code execution while the voice is being played in the background. Now we can call pause and resume methods
wscript.sleep 5000 'voice played for 5000ms
Speak.pause 'paused
wscript.sleep 4000 'remains paused for 4000ms
Speak.resume 'resumes
objFileToRead.Close
Set objFileToRead = Nothing
SpeechVoiceSpeakFlags
Intrigue in this led me to take inspiration from Kira's answer and develop it somewhat (in a bad, novice kind of way), to achieve the pause/resume objective interactively, the code below works for me, and hopefully it's of some help to you...
option explicit
dim strpath, fso, strfile, strtxt, user, voice, flag
flag = 2
call init
sub init
do while len(strpath) = 0
strpath = inputbox ("Please enter the full path of txt file", "Txt to Speech")
if isempty(strpath) then
wscript.quit()
end if
loop
'strpath = "C:\Users\???\Desktop\???.txt"
set fso = createobject("scripting.filesystemobject")
on error resume next
set strfile = fso.opentextfile(strpath,1)
if err.number = 0 then
strtxt = strfile.readall()
strfile.close
call ctrl
else
wscript.echo "Error: " & err.number & vbcrlf & "Source: " & err.source & vbcrlf &_
"Description: " & err.description
err.clear
call init
end if
end sub
sub ctrl
user = msgbox("Press ""OK"" to Play / Pause", vbokcancel + vbexclamation, "Txt to Speech")
select case user
case vbok
if flag = 0 then
voice.pause
flag = 1
call ctrl
elseif flag = 1 then
voice.resume
flag = 0
call ctrl
else
call spk
end if
case vbcancel
wscript.quit
end select
end sub
sub spk
'wscript.echo strtxt
set voice = createobject("sapi.spvoice")
voice.speak strtxt,1
flag = 0
call ctrl
end sub

This VBS file is not working [duplicate]

I am trying to make the cancel function work for my array it works for a simple input box but Array(InputBox( does not like it very much.
Working code.
If strVarValue = vbNullString Then
MsgBox ("User canceled!")
WScript.Quit
End If
What I need help with
strIPAddress = Array(InputBox("IP address"))
If strIPAddress = vbNullString Then
MsgBox ("User canceled!")
WScript.Quit
End If
Doesn't like the Array hence why I'm getting type mismatch.
Do the conversion only if the user did not press "Cancel":
userInput = InputBox("IP address")
If userInput = "" Then
MsgBox ("User canceled!")
WScript.Quit
End If
strIPAddress = Array(userInput)
Also, if you want to distinguish between "user pressed Cancel" and "user pressed OK without entering a value" you need to check if the variable is Empty:
userInput = InputBox("IP address")
If IsEmpty(userInput) Then
MsgBox ("User canceled!")
WScript.Quit
ElseIf userInput = "" Then
MsgBox ("Missing input!")
WScript.Quit 1
End If
strIPAddress = Array(userInput)

Recordset Operation is Not allowed when object is closed VBS

In the code bellow I get an error on the line reading recset.Close.
Char: 5
Error: Operation is not allowed when the object is closed.
Code: 800A0E78
Source: ADODB.Recordset
If the program reaches the line PQ_ID_number = InputBox("Enter PQ Database ID number, Do not use / ? < > \ : * | !", "PQ ID Number", "Replace Text") it seems to work fine (taking manual input) but when it tries to get the ID from the URL of a browser (automaticaly) it gives the error.
valid_name = 0
Dim objInstances, objIE, counterTab
Do While valid_name = 0 'Flag to exit the loop if the Id number has content in the SQL Database'
'-----------------------------------------------------------------------------------------'
Set objInstances = CreateObject("Shell.Application").windows
If objInstances.Count > 0 Then '/// make sure we have IE instances open.
'Loop through each tab.'
For Each objIE In objInstances
'Split the url of current tab using /'
splitURL = Split(objIE.LocationURL,"/")
'Count how many sub strings are in the URL when split'
counter = UBound(splitURL)
if counter = 7 Then
lastSplit = Split(splitURL(7),".")
lastURL = splitURL(0) & "//" & splitURL(2) & "/" & splitURL(3) & "/" & splitURL(4) & "/" & splitURL(5) & "/" & splitURL(6) & "/" & lastSplit(0)
if lastURL = "URL" Then
Set IE = objIE
counterTab = counterTab + 1
end if
end if
'End if
Next
Else
'If no internet explorer window is open.'
MsgBox "No Internet Explorer window found."
wscript.quit
End if
'Check if no [] is open in internet explorer'
if IsObject(IE) Then
url = Split(IE.LocationURL,"=")
url2 = Split(url(1),"&")
PQ_ID_number = url2(0)
else
MsgBox "No incident found."
wscript.quit
end if
'counterTab counts how many [] are open. If there is more than 1, ask for confirmation of last [] number.'
if counterTab > 1 Then
confirm = msgbox("Please confirm Incident ID: " & incidentID,vbYesNo,"Confirmation")
'If no is pressed, ask for manual entry.'
if confirm = vbNo Then
PQ_ID_number = InputBox("Enter PQ Database ID number, Do not use / ? < > \ : * | !", "PQ ID Number", "Replace Text")
On Error Resume Next
If PQ_ID_number = False Then
wscript.quit
End If
end if
end if
'-----------------------------------------------------------------------------------------'
'Open connection in Database'
dbConnectStr = "connection string"
Set con = CreateObject("ADODB.Connection")
Set recset = CreateObject("ADODB.Recordset")
con.Open dbConnectStr
'Get PQ Database title and status of incident number provided.
SQL_String = "Select title, status_id from incident_TBL where incident_ID = " & PQ_ID_number
recset.Open SQL_String, con
title = recset.Fields(0).Value
incidentStatus = recset.Fields(1).Value
con.Close
recset.Close
If title = False Then 'check if PQ_ID given has content in SQL Database
wscript.echo "Invalid PQ Database ID number, please type correct number"
valid_name = 0
Else
valid_name = 1
End If
Loop
Thanks for the help!
you need close Recordset first and only after that close connection
con.Close
recset.Close
change to:
recset.Close
con.Close

how to make sure that all textbox are filled before saving in VB 6.0

I'm new to vb and trying to figure things out via searching the net or asking colleagues but now I hit a dead end. I want to have my program to make sure that all my textboxes are filled before saving into the db.
Here is my code:
Private Sub CmdSave_Click()
Set rs = New ADODB.Recordset
With rs
.Open "Select * from table1", cn, 2, 3
If LblAdd_Edit.Caption = "ADD" Then
If MsgBox("Do you want to save this new rocord?", vbQuestion + vbYesNo, "FJD Inventory") = vbNo Then: Exit Sub
.AddNew
!Type = TxtName.Text
!System = txtsys.Text
!acc = TxtAcc.Text
!owner = TxtOwn.Text
!dept = TxtDpt.Text
!svctag = txtSvcTag.Text
.Update
Else
If MsgBox("Do you want to save this changes?", vbQuestion + vbYesNo, "FJD Inventory") = vbNo Then: Exit Sub
Do While Not .EOF
If LvList.SelectedItem.Text = !Type Then
!Type = TxtName.Text
!System = txtsys.Text
!acc = TxtAcc.Text
!owner = TxtOwn.Text
!dept = TxtDpt.Text
!svctag = txtSvcTag.Text
.Update
Exit Do
Else
.MoveNext
End If
Loop
End If
End With
Form_Activate
Save_Cancel
End Sub
I was trying to add the following
If TxtName.Text = "" Or txtsys.Text = "" Or TxtAcc.Text = "" Or TxtOwn.Text = "" Or TxtDpt.Text = "" Or txtSvcTag.Text = "" Then
MsgBox("All Fields Required", vbCritical, "Error") = vbOK: Exit Sub
When I run the program I get a compile error
function or call on the left-hand side of assignment must return a variant or object. I use that msgbox function all the time but now its the line I get an error
If TxtName.Text = "" Or txtsys.Text = "" Or TxtAcc.Text = "" Or TxtOwn.Text = "" Or TxtDpt.Text = "" Or txtSvcTag.Text = "" Then
If MsgBox("All Fields Required", vbCritical, "Error") = vbOK Then Exit Sub
Here is a generic solution. It uses a function to check each textbox on the form and demonstrates using the function. I also compare the text length rather than the text to an empty string because (in general) numeric comparisons are faster than string comparisons.
Private Sub Command1_Click()
If ValidateTextFields Then
MsgBox "Your changes have been saved."
Else
MsgBox "All fields are required."
End If
End Sub
Private Function ValidateTextFields() As Boolean
Dim ctrl As Control
Dim result As Boolean
result = True 'set this to false if a textbox fails
For Each ctrl In Me.Controls
If TypeOf ctrl Is TextBox Then
If Len(ctrl.Text) = 0 Then
result = False
Exit For 'bail on the first failure
End If
End If
Next ctrl
ValidateTextFields = result
End Function
In VB6, you can use Trim() function so that spaces not considered as characters.
If (Trim$(txtGOSID.Text) = "") Then
msgBox "Please provide input.", vbExclamation
With the $ sign, Trim() returns a String value directly; without the $
sign, Trim() returns a Variant with a sub-type of String.

Resources