How can I run an RDP file with VBScript? - vbscript

So far I have:
Set objShell = WScript.CreateObject("WScript.Shell")
objShell.Run("""C:\Server01.rdp""")
But when I run it, nothing happens. Is it even possible to run an RDP file with VBScript? If so, then what am I doing wrong?

try calling mstsc.exe with the .rdp file name passed in:
objShell.Run(""mstsc C:\server01.rdp"")

I think you need to run mstsc.exe and pass the rdp file in as an argument.
http://technet.microsoft.com/en-us/library/cc753907%28WS.10%29.aspx

This will work: (In PHP with VBSCRIPT):
<script type="text/vbscript" language="vbscript">
<!--
const L_FullScreenWarn1_Text = "Your current security settings do not allow automatically switching to fullscreen mode."
const L_FullScreenWarn2_Text = "You can use ctrl-alt-pause to toggle your remote desktop session to fullscreen mode"
const L_FullScreenTitle_Text = "Remote Desktop Web Connection "
const L_ErrMsg_Text = "Error connecting to remote computer: "
const L_ClientNotSupportedWarning_Text = "Remote Desktop 6.0 does not support CredSSP over TSWeb."
const L_RemoteDesktopCaption_ErrorMessage = "Remote Desktop Connection"
const L_InvalidServerName_ErrorMessage = "An invalid server name was specified."
sub window_onload()
if not autoConnect() then
msgbox("VB")
end if
end sub
function autoConnect()
Dim sServer
Dim iFS, iAutoConnect
sServer = getQS ("Server")
iAutoConnect = getQS ("AutoConnect")
iFS = getQS ("FS")
if NOT IsNumeric ( iFS ) then
iFS = 0
else
iFS = CInt ( iFS )
end if
if iAutoConnect <> 1 then
autoConnect = false
exit function
else
if IsNull ( sServer ) or sServer = "" then
sServer = window.location.hostname
end if
btnConnect ()
autoConnect = true
end if
end function
function getQS ( sKey )
Dim iKeyPos, iDelimPos, iEndPos
Dim sURL, sRetVal
iKeyPos = iDelimPos = iEndPos = 0
sURL = window.location.href
if sKey = "" Or Len(sKey) < 1 then
getQS = ""
exit function
end if
iKeyPos = InStr ( 1, sURL, sKey )
if iKeyPos = 0 then
sRetVal = ""
exit function
end if
iDelimPos = InStr ( iKeyPos, sURL, "=" )
iEndPos = InStr ( iDelimPos, sURL, "&" )
if iEndPos = 0 then
sRetVal = Mid ( sURL, iDelimPos + 1 )
else
sRetVal = Mid ( sURL, iDelimPos + 1, iEndPos - iDelimPos - 1 )
end if
getQS = sRetVal
end function
sub OnControlLoadError
Msgbox("You wont be able to connect trough Remote Desktop")
end sub
sub OnControlLoad
set Control = Document.getElementById("MsRdpClient")
if Not Control is Nothing then
if Control.readyState = 4 then
BtnConnect()
else
Msgbox("You wont be able to connect trough Remote Desktop")
end if
else
Msgbox("You wont be able to connect trough Remote Desktop")
end if
end sub
sub BtnConnect
Dim serverName
serverName = "<?=$_POST["RDserver"]?>"
serverName = trim(serverName)
On Error Resume Next
MsRdpClient.server = serverName
If Err then
msgbox
L_InvalidServerName_ErrorMessage,0,L_RemoteDesktopCaption_ErrorMessage
Err.Clear
exit sub
end if
On Error Goto 0
Dim ClientUserName
ClientUserName = "<?=trim($_POST["RDuser"])?>"
MsRdpClient.UserName = ClientUserName
MsRdpClient.AdvancedSettings.ClearTextPassword = "<?=trim($_POST["RDpass"])?>"
MsRdpClient.FullScreen = TRUE
resWidth = screen.width
resHeight = screen.height
MsRdpClient.DesktopWidth = resWidth
MsRdpClient.DesktopHeight = resHeight
MsRdpClient.Width = resWidth
MsRdpClient.Height = resHeight
MsRdpClient.AdvancedSettings2.RedirectDrives = FALSE
MsRdpClient.AdvancedSettings2.RedirectPrinters = FALSE
MsRdpClient.AdvancedSettings2.RedirectPorts = FALSE
MsRdpClient.AdvancedSettings2.RedirectSmartCards = FALSE
MsRdpClient.FullScreenTitle = L_FullScreenTitle_Text & "-" & serverName & "-"
MsRdpClient.Connect
end sub
-->
</script>
<object id="MsRdpClient" language="vbscript" onreadystatechange="OnControlLoad" onerror="OnControlLoadError" classid="CLSID:4eb89ff4-7f78-4a0f-8b8d-2bf02e94e4b2" width="800" height="600"></object>
<script language="VBScript">
<!--
sub ReturnToConnectPage()
me.close
end sub
sub MsRdpClient_OnConnected()
end sub
sub MsRdpClient_OnDisconnected(disconnectCode)
extendedDiscReason = MsRdpClient.ExtendedDisconnectReason
majorDiscReason = disconnectCode And &hFF
if (disconnectCode = &hB08 or majorDiscReason = 2 or majorDiscReason = 1) and not (extendedDiscReason = 5) then
ReturnToConnectPage
exit sub
end if
errMsgText = MsRdpClient.GetErrorDescription(disconnectCode, extendedDiscReason)
if not errMsgText = "" then
msgbox errMsgText,0,L_RemoteDesktopCaption_ErrorMessage
end if
ReturnToConnectPage
end sub
-->
</script>
The problem is, that only works in IE, still looking for Firefox / Safari... any luck??

Related

how to rename image file name while uploading on web folder

i m using asp classic. i want to rename image file while i upload image on web folder created by me. please help me out of this issue.
If there is a file in targeted folder with same name (like lokesh.jpg) what i am uploading, than new file should b automatically renamed(like lokesh(1).jpg) instead of overwriting
my code is as below:
upload.asp
<%
Class FileUploader
Public Files
Private mcolFormElem
Private Sub Class_Initialize()
Set Files = Server.CreateObject("Scripting.Dictionary")
Set mcolFormElem = Server.CreateObject("Scripting.Dictionary")
End Sub
Private Sub Class_Terminate()
If IsObject(Files) Then
Files.RemoveAll()
Set Files = Nothing
End If
If IsObject(mcolFormElem) Then
mcolFormElem.RemoveAll()
Set mcolFormElem = Nothing
End If
End Sub
Public Property Get Form(sIndex)
Form = ""
If mcolFormElem.Exists(LCase(sIndex)) Then Form = mcolFormElem.Item(LCase(sIndex))
End Property
Public Default Sub Upload()
Dim biData, sInputName
Dim nPosBegin, nPosEnd, nPos, vDataBounds, nDataBoundPos
Dim nPosFile, nPosBound
biData = Request.BinaryRead(Request.TotalBytes)
nPosBegin = 1
nPosEnd = InstrB(nPosBegin, biData, CByteString(Chr(13)))
If (nPosEnd-nPosBegin) <= 0 Then Exit Sub
vDataBounds = MidB(biData, nPosBegin, nPosEnd-nPosBegin)
nDataBoundPos = InstrB(1, biData, vDataBounds)
Do Until nDataBoundPos = InstrB(biData, vDataBounds & CByteString("--"))
nPos = InstrB(nDataBoundPos, biData, CByteString("Content-Disposition"))
nPos = InstrB(nPos, biData, CByteString("name="))
nPosBegin = nPos + 6
nPosEnd = InstrB(nPosBegin, biData, CByteString(Chr(34)))
sInputName = CWideString(MidB(biData, nPosBegin, nPosEnd-nPosBegin))
nPosFile = InstrB(nDataBoundPos, biData, CByteString("filename="))
nPosBound = InstrB(nPosEnd, biData, vDataBounds)
If nPosFile <> 0 And nPosFile < nPosBound Then
Dim oUploadFile, sFileName
Set oUploadFile = New UploadedFile
nPosBegin = nPosFile + 10
nPosEnd = InstrB(nPosBegin, biData, CByteString(Chr(34)))
sFileName = CWideString(MidB(biData, nPosBegin, nPosEnd-nPosBegin))
oUploadFile.FileName = Right(sFileName, Len(sFileName)-InStrRev(sFileName, "\"))
Dim oFileExtension
If sFileName <> "" then
oFileExtension = (Right(sFileName, Len(sFileName)-InStrRev(sFileName, ".")))
If oFileExtension <> "jpg" AND oFileExtension <> "jpeg" AND oFileExtension <> "gif" AND oFileExtension <> "pdf" then
response.write("<h1>Post New File</h1><p><font color=#ff0000>An error has occurred while processing your request.<br><br>We are sorry, Extensions other than JPG, JPEG, Gif, PDF are not allowed to upload<p><b>Click <a href='javascript:history.go(-1);'>here</a> to go back and address the error.</b></font>")
response.end
Exit Sub
End if
end If
nPos = InstrB(nPosEnd, biData, CByteString("Content-Type:"))
nPosBegin = nPos + 14
nPosEnd = InstrB(nPosBegin, biData, CByteString(Chr(13)))
oUploadFile.ContentType = CWideString(MidB(biData, nPosBegin, nPosEnd-nPosBegin))
nPosBegin = nPosEnd+4
nPosEnd = InstrB(nPosBegin, biData, vDataBounds) - 2
oUploadFile.FileData = MidB(biData, nPosBegin, nPosEnd-nPosBegin)
If sfileName <> "" then
If oUploadFile.FileSize > 10000000 Then
response.write("<h1>Post New Image</h1><p><font color=#ff0000>An error has occurred while processing your request.<br><br>We are sorry, Upload file containing 10000000(10mb) bytes only.<p><b>Click <a href='javascript:window:history.go(-1);'>here</a> to go back and address the error.</b></font>")
response.end
Exit Sub
End if
End if
If oUploadFile.FileSize > 0 Then Files.Add LCase(sInputName), oUploadFile
Else
nPos = InstrB(nPos, biData, CByteString(Chr(13)))
nPosBegin = nPos + 4
nPosEnd = InstrB(nPosBegin, biData, vDataBounds) - 2
If Not mcolFormElem.Exists(LCase(sInputName)) Then mcolFormElem.Add LCase(sInputName), CWideString(MidB(biData, nPosBegin, nPosEnd-nPosBegin))
End If
nDataBoundPos = InstrB(nDataBoundPos + LenB(vDataBounds), biData, vDataBounds)
Loop
End Sub
'String to byte string conversion
Private Function CByteString(sString)
Dim nIndex
For nIndex = 1 to Len(sString)
CByteString = CByteString & ChrB(AscB(Mid(sString,nIndex,1)))
Next
End Function
'Byte string to string conversion
Private Function CWideString(bsString)
Dim nIndex
CWideString =""
For nIndex = 1 to LenB(bsString)
CWideString = CWideString & Chr(AscB(MidB(bsString,nIndex,1)))
Next
End Function
End Class
Class UploadedFile
Public ContentType
Public FileName
Public FileData
Public Property Get FileSize()
FileSize = LenB(FileData)
End Property
Public Sub SaveToDisk(sPath)
Dim oFS, oFile
Dim nIndex
If sPath = "" Or FileName = "" Then Exit Sub
If Mid(sPath, Len(sPath)) <> "\" Then sPath = sPath & "\"
Set oFS = Server.CreateObject("Scripting.FileSystemObject")
If Not oFS.FolderExists(sPath) Then Exit Sub
Set oFile = oFS.CreateTextFile(sPath & FileName, True)
For nIndex = 1 to LenB(FileData)
oFile.Write Chr(AscB(MidB(FileData,nIndex,1)))
Next
oFile.Close
End Sub
Public Sub SaveToDatabase(ByRef oField)
If LenB(FileData) = 0 Then Exit Sub
If IsObject(oField) Then
oField.AppendChunk FileData
End If
End Sub
End Class
%>
submit.asp
<!-- #include file="upload.asp" -->
<%
response.buffer = true
Dim Uploader, File, i, j
Set Uploader = New FileUploader
Uploader.Upload()
Dim brandnm, filename
brandnm = Uploader.form("brandname")
Dim objRSa, objCmda, stra
Set objCmda = server.CreateObject("adodb.connection")
Set Objrsa = Server.CreateObject("ADODB.Recordset")
objCmda.open MM_connDUdirectory_STRING
stra = "SELECT * FROM brand"
Objrsa.Open stra,objCmda,1,2
if Uploader.Files.count <> 0 then
File = Uploader.Files.Items()
File(0).SavetoDisk Server.MapPath("upload/brands") 'Folder path where image will save
filename = File(0).Filename
else
filename = ""
End if
Objrsa.addnew
Objrsa.fields("brand_name") = brandnm
Objrsa.fields("brand_createddt") = now()
if filename <>"" then Objrsa.fields("brand_picpath") = filename
For Each File In Uploader.Files.Items
Objrsa("brand_ctype") = File.ContentType
next
Objrsa.Update
Objrsa.Close
Set Objrsa = Nothing
set objCmda = Nothing
%>
Please help me out of this issue.
If you want to rename it to follow a known pattern as in your example ("filename(number).ext"), you must to use a pseudo-code like this:
let counter = 1
let original = file(0).Filename
let current = file(0).Filename
while(current file exists)
current = original-without-extension + (counter) + original-extension
counter = counter + 1
end
However, I think that would be better to store the user provided filename into your database and choose a random-like filename to store the actual file into the filesystem.
let current = userLogin + (currentTime as yyyyMMddHHmmss) + ".uploaded"
By using a bogus file extension you make your application way more secure, as your file will not be interpretable/executable -- imagine a malicious user uploading an .ASP file and executing it.
If this break the image MIME type, you should consider creating another .ASP page read the database to discover the appropriate MIME type based on the user provided file extension, write that content-type and the binary file content.
TL;DR: don't use the user provided file name, create a new one. This will avoid server hacking.

VBScript ADODB.Stream type mismatch

I am writing an HTA application to manage Hyper-V, and I am stuck on the GetVirtualSystemThumbnailImage script. I took the VBScript example from:
https://msdn.microsoft.com/en-us/library/cc160707(v=vs.85).aspx
but that script never actually calls the sub to write the image file. I tried calling the SaveThumbnailImage sub with the arguments being (objOutParams.ImageData), and I get a "Type Mismatch" error on the stream.WriteText line 81. For some reason, the ADODB is rejecting the binary data? I would appreciate any help with this.
option explicit
dim objWMIService
dim managementService
dim fileSystem
const wmiStarted = 4096
const wmiSuccessful = 0
Main()
'-----------------------------------------------------------------
' Main
'-----------------------------------------------------------------
Sub Main()
dim computer, objArgs, strArgs, vmName, vm
set objArgs = WScript.Arguments
if WScript.Arguments.Count = 1 then
computer = Split(objArgs.Unnamed.Item(0),",")(0)
vmName = Split(objArgs.Unnamed.Item(0),",")(1)
else
WScript.Echo "usage: cscript GetVirtualSystemThumbnailImage.vbs hostName,vmName"
WScript.Quit(1)
end if
set fileSystem = Wscript.CreateObject("Scripting.FileSystemObject")
set objWMIService = GetObject("winmgmts:\\" & computer & "\root\virtualization\v2")
set managementService = objWMIService.ExecQuery("select * from Msvm_VirtualSystemManagementService").ItemIndex(0)
set vm = GetComputerSystem(vmName)
if StartVm(vm) then
if GetVirtualSystemThumbnailImage(vm) then
WriteLog "Done"
WScript.Quit(0)
End if
end if
WriteLog "GetVirtualSystemThumbnailImage Failed."
WScript.Quit(1)
End Sub
'-----------------------------------------------------------------
' Retrieve Msvm_VirtualComputerSystem from base on its ElementName
'-----------------------------------------------------------------
Function GetComputerSystem(vmElementName)
' On Error Resume Next
dim query
query = Format1("select * from Msvm_ComputerSystem where ElementName = '{0}'", vmElementName)
set GetComputerSystem = objWMIService.ExecQuery(query).ItemIndex(0)
if (Err.Number <> 0) then
WriteLog Format1("Err.Number: {0}", Err.Number)
WriteLog Format1("Err.Description:{0}",Err.Description)
WScript.Quit(1)
end if
End Function
'-----------------------------------------------------------------
' Save the thumbnail
'-----------------------------------------------------------------
Sub SaveThumbnailImage(thumbnailBytes)
dim stream
Const adTypeText = 2
Const adSaveCreateOverWrite = 2
set stream = CreateObject("ADODB.Stream")
stream.Type = adTypeText
stream.Open
Redim text(ubound(thumbnailBytes) \ 2)
Dim i
for i = lbound(thumbnailBytes) to ubound(thumbnailBytes) step 2
text(i\2) = ChrW(thumbnailBytes(i + 1) * &HFF + thumbnailBytes(i))
next
stream.WriteText text
stream.SaveToFile ".\thumbnail.png", adSaveCreateOverWrite
stream.Close
End Sub
'-----------------------------------------------------------------
' Start the virtual machine
'-----------------------------------------------------------------
Function StartVm(computerSystem)
dim objInParam, objOutParams
StartVm = false
if computerSystem.OperationalStatus(0) = 2 then
StartVm = true
Exit Function
end if
set objInParam = computerSystem.Methods_("RequestStateChange").InParameters.SpawnInstance_()
objInParam.RequestedState = 2
set objOutParams = computerSystem.ExecMethod_("RequestStateChange", objInParam)
if objOutParams.ReturnValue = wmiStarted then
if (WMIJobCompleted(objOutParams)) then
StartVm = true
end if
elseif objOutParams.ReturnValue = wmiSuccessful then
StartVm = true
else
WriteLog Format1("StartVM failed with ReturnValue {0}", wmiStatus)
end if
End Function
'-----------------------------------------------------------------
' Print the thumbnail data
'-----------------------------------------------------------------
Sub PrintThumbnailImage(thumbnailBytes)
dim index
dim i
for index = lbound(thumbnailBytes) to ubound(thumbnailBytes)
WriteLog Format2("{0}:{1} ", index, thumbnailBytes(i))
next
End Sub
'-----------------------------------------------------------------
' Define a virtual system
'-----------------------------------------------------------------
Function GetVirtualSystemThumbnailImage(computerSystem)
dim query, objInParam, objOutParams, virtualSystemsetting
GetVirtualSystemThumbnailImage = false
query = Format1("ASSOCIATORS OF {{0}} WHERE resultClass = Msvm_VirtualSystemsettingData", computerSystem.Path_.Path)
set virtualSystemsetting = objWMIService.ExecQuery(query).ItemIndex(0)
set objInParam = managementService.Methods_("GetVirtualSystemThumbnailImage").InParameters.SpawnInstance_()
objInParam.HeightPixels = 150
objInParam.WidthPixels = 100
objInParam.TargetSystem = virtualSystemsetting.Path_.Path
set objOutParams = managementService.ExecMethod_("GetVirtualSystemThumbnailImage", objInParam)
if objOutParams.ReturnValue = wmiStarted then
if (WMIJobCompleted(objOutParams)) then
GetVirtualSystemThumbnailImage = true
end if
elseif objOutParams.ReturnValue = wmiSuccessful then
Dim strData : strData = objOutParams.ImageData
SaveThumbnailImage(strData)
' PrintThumbnailImage(strData)
GetVirtualSystemThumbnailImage = true
else
WriteLog Format1("GetVirtualSystemThumbnailImage failed with ReturnValue {0}", wmiStatus)
end if
End Function
'-----------------------------------------------------------------
' Handle wmi Job object
'-----------------------------------------------------------------
Function WMIJobCompleted(outParam)
dim WMIJob, jobState
set WMIJob = objWMIService.Get(outParam.Job)
WMIJobCompleted = true
jobState = WMIJob.JobState
while jobState = JobRunning or jobState = JobStarting
WriteLog Format1("In progress... {0}% completed.",WMIJob.PercentComplete)
WScript.Sleep(1000)
set WMIJob = objWMIService.Get(outParam.Job)
jobState = WMIJob.JobState
wend
if (jobState <> JobCompleted) then
WriteLog Format1("ErrorCode:{0}", WMIJob.ErrorCode)
WriteLog Format1("ErrorDescription:{0}", WMIJob.ErrorDescription)
WMIJobCompleted = false
end if
End Function
'-----------------------------------------------------------------
' Create the console log files.
'-----------------------------------------------------------------
Sub WriteLog(line)
dim fileStream
set fileStream = fileSystem.OpenTextFile(".\GetVirtualSystemThumbnailImage.log", 8, true)
' WScript.Echo line
fileStream.WriteLine line
fileStream.Close
End Sub
'------------------------------------------------------------------------------
' The string formatting functions to avoid string concatenation.
'------------------------------------------------------------------------------
Function Format2(myString, arg0, arg1)
Format2 = Format1(myString, arg0)
Format2 = Replace(Format2, "{1}", arg1)
End Function
'------------------------------------------------------------------------------
' The string formatting functions to avoid string concatenation.
'------------------------------------------------------------------------------
Function Format1(myString, arg0)
Format1 = Replace(myString, "{0}", arg0)
End Function

VBScript SMTP Server

I have set this up to auto email through the Outlook client, is it possible to change this code to work directly through an SMTP server? And could anyone possibly help me do it?
Any help would be much appreciated, thanks!
Set app = CreateObject("Excel.Application")
Set fso = CreateObject("Scripting.FileSystemObject")
For Each f In fso.GetFolder("Y:\Billing_Common\autoemail").Files
If LCase(fso.GetExtensionName(f)) = "xls" Then
Set wb = app.Workbooks.Open(f.Path)
set sh = wb.Sheets("Auto Email Script")
row = 2
name = "Customer"
email = sh.Range("A" & row)
subject = "Billing"
the = "the"
LastRow = sh.UsedRange.Rows.Count
For r = row to LastRow
If App.WorkSheetFunction.CountA(sh.Rows(r)) <> 0 Then
SendMessage email, name, subject, TRUE, _
NULL, "Y:\Billing_Common\autoemail\Script\energia-logo.gif", 143,393
row = row + 1
email = sh.Range("A" & row)
End if
Next
wb.Close
End If
Next
Sub SendMessage(EmailAddress, DisplayName, Subject, DisplayMsg, AttachmentPath, ImagePath, ImageHeight, ImageWidth)
' Create the Outlook session.
Set objOutlook = CreateObject("Outlook.Application")
template = FindTemplate()
' Create the message.
Set objOutlookMsg = objOutlook.CreateItem(0)
With objOutlookMsg
' Add the To recipient(s) to the message.
Set objOutlookRecip = .Recipients.Add(EmailAddress)
objOutlookRecip.resolve
objOutlookRecip.Type = 1
' Set the Subject, Body, and Importance of the message.
.Subject = Subject
.bodyformat = 3
.Importance = 2 'High importance
body = Replace(template, "{First}", name)
body = Replace(body, "{the}", the)
if not isNull(ImagePath) then
if not ImagePath = "" then
.Attachments.add ImagePath
image = split(ImagePath,"\")(ubound(split(ImagePath,"\")))
body = Replace(body, "{image}", "<img src='cid:" & image & _
"'" & " height=" & ImageHeight &" width=" & ImageWidth & ">")
end if
else
body = Replace(body, "{image}", "")
end if
if not isNull(AttachMentPath) then
.Attachments.add AttachmentPath
end if
.HTMLBody = body
.Save
.Send
End With
Set objOutlook = Nothing
End Sub
Function FindTemplate()
Set OL = GetObject("", "Outlook.Application")
set Drafts = OL.GetNamespace("MAPI").GetDefaultFolder(16)
Set oItems = Drafts.Items
For Each Draft In oItems
If Draft.subject = "Template" Then
FindTemplate = Draft.HTMLBody
Exit Function
End If
Next
End Function
If you want to send mail directly to an SMTP server, there's no need to go through Outlook in the first place. Just use CDO. Something like this:
schema = "http://schemas.microsoft.com/cdo/configuration/"
Set msg = CreateObject("CDO.Message")
msg.Subject = "Test"
msg.From = "sender#example.com"
msg.To = "recipient#example.org"
msg.TextBody = "This is some sample message text."
With msg.Configuration.Fields
.Item(schema & "sendusing") = 2
.Item(schema & "smtpserver") = "smtp.intern.example.com"
.Item(schema & "smtpserverport") = 25
.Update
End With
msg.Send

import data from web to Excel 2010 worksheet

I am trying to import data from web to Excel worksheet on win 7.
But, I do not know how to finish the left one where is marked .
Sub Ex2Macro()
Ex2 from Macro1 Macro
' Macro changed 17/07/2007 by Dr. B. I. Czaczkes
Dim qt As QueryTable
Dim temp As Variant ' Double
Set qt = ActiveSheet.QueryTables.Add(Connection:= _
"URL;http://finance.yahoo.com/q?s=GBPUSD=X", Destination:=ActiveCell.Range("A1"))
With qt
.Name = "query1"
.BackgroundQuery = False
.SaveData = True
.WebSelectionType = xlSpecifiedTables
.WebFormatting = xlWebFormattingNone
.WebTables = "14"
.WebPreFormattedTextToColumns = True
.WebConsecutiveDelimitersAsOne = True
.Refresh BackgroundQuery:=False
End With
With qt.ResultRange
.ClearContents
.Range("a1").Value = "USD/GBP"
.Range("b1").Value = ? ' here, what I should put so that the queried result
' is printed ?
End With
End Sub
Another piece of code that provide the exchange result.
Sub Ex3Macro()
Dim qt As QueryTable
' Dim temp As Double
Dim temp As Variant
temp = ActiveCell.Value
Set qt = Worksheets("temp").QueryTables.Add(Connection:= _
"URL;http://finance.yahoo.com/currency/convert?amt=" & _
temp & _
"&from=USD&to=GBP&submit=Convert" _
, Destination:=Worksheets("Temp").Range("a1"))
With qt
.Name = "query2"
.BackgroundQuery = False
.SaveData = True
.WebSelectionType = xlSpecifiedTables
.WebFormatting = xlWebFormattingNone
.WebTables = "13"
.WebPreFormattedTextToColumns = True
.WebConsecutiveDelimitersAsOne = True
.Refresh BackgroundQuery:=False
End With
ActiveCell.Range("b1").Value = qt.ResultRange.Range("e3").Value
End Sub
But, no result is printed.
Any help will be appreciated.
Try selecting the Microsoft WinHTTP Services, version 5.1 reference then using this:
Sub HTTPTest()
Dim httpRequest As WinHttpRequest
Dim URL As String, strHTML As String
If httpRequest Is Nothing Then
Set httpRequest = New WinHttp.WinHttpRequest
End If
URL = "http://finance.yahoo.com/q?s=GBPUSD=X"
httpRequest.Open "GET", URL, True
httpRequest.Send
httpRequest.WaitForResponse
strHTML = httpRequest.ResponseText
Set httpRequest = Nothing
'Parse strHTML now to get your value
End Sub

How to create options dialog with VbScript?

I have a third party application that invokes a vsbscript file for certain operations. I would like to put up a user prompt with a choice of options, either a drop down list or checkbox or some such. However, all I can find is the input box option.
I don't think HTAs are an option in my case (unless there is a way to call them from a .vbs file?)
My other thought was some sort of ActiveX control, but I can't locate a built-in one that would be available by default on WindowsXP/Vista.
Anybody have any ideas on how I could accomplish this?
The simple answer is, you really can't. Tmdean's solution is the only way I can think of either. That said, you can spruce up the input box so it doesn't look horrible. Give this a run, I don't think it's an epic fail:
Dim bullet
Dim response
bullet = Chr(10) & " " & Chr(149) & " "
Do
response = InputBox("Please enter the number that corresponds to your selection:" & Chr(10) & bullet & "1.) Apple" & bullet & "2.) Bannana" & bullet & "3.) Pear" & Chr(10), "Select Thing")
If response = "" Then WScript.Quit 'Detect Cancel
If IsNumeric(response) Then Exit Do 'Detect value response.
MsgBox "You must enter a numeric value.", 48, "Invalid Entry"
Loop
MsgBox "The user chose :" & response, 64, "Yay!"
If you would like to use an hta for this it can be done like this.
The VBScript:
Set WshShell = CreateObject("WScript.Shell")
'Run the hta.
WshShell.Run "Test.hta", 1, true
'Display the results.
MsgBox "Return Value = " & getReturn
Set WshShell = Nothing
Function getReturn
'Read the registry entry created by the hta.
On Error Resume Next
Set WshShell = CreateObject("WScript.Shell")
getReturn = WshShell.RegRead("HKEY_CURRENT_USER\Volatile Environment\MsgResp")
If ERR.Number 0 Then
'If the value does not exist return -1
getReturn = -1
Else
'Otherwise return the value in the registry & delete the temperary entry.
WshShell.RegDelete "HKEY_CURRENT_USER\Volatile Environment\MsgResp"
End if
Set WshShell = Nothing
End Function
Then design the hta as desired, and include the following methods
'Call this when the OK button is clicked.
Sub OK_Click
For Each objradiobutton In Opt
If objradiobutton.Checked Then
WriteResponse objradiobutton.Value
End If
Next
window.Close
End Sub
'Call this when the Cancel button is clicked.
Sub Cancel_Click
WriteResponse("CANCEL")
window.Close
End Sub
'Write the response to the registry
Sub WriteResponse(strValue)
Set WshShell = CreateObject("WScript.Shell")
WshShell.RegWrite "HKEY_CURRENT_USER\Volatile Environment\MsgResp", strValue
Set WshShell = Nothing
End Sub
I used a group of radio buttons named "Opt" to make a choice, but you could use any controls you would like.
Because hta's cannot return values, this will create a temperary registry entry. If you are not comforatable messing with the registry, you could also write the result to a temperary text file.
This approach is nice because you can design the hta any way you like, rather than using the supplied inputbox and choosing numbers (thats so DOS).
This could also be nice if you expanded the hta to create itself based on arguments passed to it, like passing in a title, a message to display, an array of options, a set of buttons. That way you could use the same hta any time you needed to get input from the user.
You can use DialogLib to create forms with dropdowns and checkboxes. DialogLib is still in it's ealy stages, but is's allready quite usefull: http://www.soren.schimkat.dk/Blog/?p=189
Try WshShell.Popup. Depending upon your data that may work for you...
Otherwise you could investigate PowerShell.
One option is to script Internet Explorer. You can use VBScript to launch IE and load a local HTML file, and attach a VBScript sub to a form's submit button (or any other JavaScript events), which can then close the IE window as part of its execution.
You can launch an HTA from a VBScript.
Set shell = CreateObject("WScript.Shell")
shell.Run "Test.hta"
EDIT
Since you have full control of the VBScript, could you make the 3rd party VBScript simply call your HTA? You could put the UI and whatever processing code inside of the HTA.
As an example of #TmDean's suggestion, there's this class that I sometimes use which scripts IE (well, it scripted IE6; I haven't tried the more recent incarnations.)
class IEDisplay
'~ Based on original work by Tony Hinkle, tonyhinkle#yahoo.com
private TEMPORARY_FOLDER
private objShell
private objIE
private objFSO
private objFolder
private strName
private streamOut
private objDIV
private numHeight
private numWidth
private numTop
private numLeft
private sub Class_Initialize()
Dim strComputer
Dim objWMIService
Dim colItems
Dim objItem
Dim arrMonitors( 10, 1 )
Dim numMonitorCount
Set objShell = WScript.CreateObject("WScript.Shell")
Set objIE = CreateObject("InternetExplorer.Application")
strComputer = "."
Set objWMIService = GetObject( "winmgmts:\\" & strComputer & "\root\cimv2")
Set colItems = objWMIService.ExecQuery( "Select * from Win32_DesktopMonitor")
numMonitorCount = 0
For Each objItem in colItems
arrMonitors( numMonitorCount, 0 ) = objItem.ScreenHeight
arrMonitors( numMonitorCount, 1 ) = objItem.ScreenWidth
numMonitorCount = numMonitorCount + 1
Next
numHeight = arrMonitors( 0, 0 )
numWidth = arrMonitors( 0, 1 )
Set objFSO = CreateObject("Scripting.FileSystemObject")
TEMPORARY_FOLDER = 2
set objFolder = objFSO.GetSpecialFolder( TEMPORARY_FOLDER )
strName = objFSO.BuildPath( objFolder, objFSO.GetTempName ) & ".html"
WriteFileU strName, Join( Array( "<HTML><HEAD><TITLE>Information</TITLE></HEAD>", _
"<BODY SCROLL='NO'><CENTER><FONT FACE='arial black'> <HR COLOR='BLACK'>", _
"<DIV id='MakeMeAnObject'></DIV>", _
"<HR COLOR='BLACK'></FONT></CENTER></BODY></HTML>" ), vbCRLF ), WF_CREATE
numTop = 0
numLeft = 0
end sub
Sub Init( strPosition )
'NW, N, NE, W, CENTRE, E, SW, S, SE
Select Case strPosition
Case "NW"
numTop = 0
numLeft = 0
Case "N"
numTop = 0
numLeft = ( numWidth / 2 ) - 250
Case "NE"
numTop = 0
numLeft = numWidth - 500
Case "W"
numTop = ( numHeight / 2 ) - 55
numLeft = 0
Case "CENTRE"
numTop = ( numHeight / 2 ) - 55
numLeft = ( numWidth / 2 ) - 250
Case "E"
numTop = ( numHeight / 2 ) - 55
numLeft = numWidth - 500
Case "SW"
numTop = numHeight - 110
numLeft = 0
Case "S"
numTop = numHeight - 110
numLeft = ( numWidth / 2 ) - 250
Case "SE"
numTop = numHeight - 110
numLeft = numWidth - 500
Case Else
numTop = 0
numLeft = 0
End Select
SetupIE( strName )
Set objDIV = objIE.Document.All("MakeMeAnObject")
end sub
private sub Class_Terminate()
'Close IE and delete the file
objIE.Quit
'~ optionally you may want to get rid of the temp file
end sub
public sub Display( strMsg, numMillisec )
objDIV.InnerHTML = strMsg
WScript.Sleep numMillisec
end sub
Private Sub SetupIE(File2Load)
objIE.Navigate File2Load
objIE.ToolBar = False
objIE.StatusBar = False
objIE.Resizable = False
Do
Loop While objIE.Busy
objIE.Width = 500
objIE.Height = 110
objIE.Left = numLeft
objIE.Top = numTop
objIE.Visible = True
objShell.AppActivate("Microsoft Internet Explorer")
End Sub
end class
here is the missing (from the original posting) WriteFileU function
Const WF_APPEND = 1
Const WF_CREATE = 2
Const WF_FOR_APPENDING = 8
Const WF_FOR_WRITING = 2
Const WF_CREATE_NONEXISTING = True
Const CONST_READ = 1, CONST_WRITE = 2, CONST_APPEND = 8
Const AS_SYSTEMDEFAULT = -2, AS_UNICODE = -1, AS_ASCII = 0
Sub WriteFileU( sFilename, sContents, nMode )
Dim oStream
If nMode = WF_APPEND Then
Set oStream = oFSO.OpenTextFile( sFilename, WF_FOR_APPENDING, WF_CREATE_NONEXISTING, AS_UNICODE )
ElseIf nMode = WF_CREATE Then
Set oStream = oFSO.OpenTextFile( sFilename, WF_FOR_WRITING, WF_CREATE_NONEXISTING, AS_UNICODE )
Else
STOP
End If
oStream.Write sContents
oStream.Close
Set oStream = Nothing
End Sub
and then as an example of it's use
set i = new IEDisplay
a = array("NW", "N", "NE", "W", "CENTRE", "E", "SW","S","SE")
for each aa in a
i.init aa
i.display "Here in " & aa & " of screen", 1000
next
Now that's not immediately useful (especially are there are a pile of calls to my own utility routines in there) but it gives a framework. By modifying what HTML is stored, you could add support for listboxes etc.
I know this is eleven years too late, but it sounds like this would be more along the lines of what the original request would be looking for:
Sub CustomMsgBox(msg)
Dim ie, Style, FormExit
Set ie = CreateObject("InternetExplorer.Application")
ie.Navigate "about:blank"
While ie.ReadyState <> 4: WScript.Sleep 100: Wend
ie.Toolbar = False
ie.StatusBar = False
ie.Width = 450
ie.Height = 275
ie.document.body.innerHTML = "<title>Choose a Color</title><p class='msg'>Choose an option:</p>" & "<input type='radio' id='myRadio' name='colors' value='red'>Red</br><input type='radio' id='myRadio' name='colors' value='yellow'>Yellow</br><input type='radio' id='myRadio' name='colors' value='blue'>Blue"
Set Style = ie.document.CreateStyleSheet
Style.AddRule "p.msg", "font-family:calibri;font-weight:bold;"
ie.Visible = True
ie.Quit
End Sub
This code worked for me in an HTA file (that I opened from VBS using WScript.Shell Run). The trick was to get the data back to VBS which I accomplished by having HTA create an XML file that VBS read.
Sub CopySelect(sSrcId, sTargetId)
Dim oTarget: Set oTarget = document.getElementById(sTargetId)
Dim oSrc: Set oSrc = document.getElementById(sSrcId)
Dim j, n, o
oTarget.length = 0
For j = 0 to oSrc.length - 1
Set o = oSrc.options(j)
Set n = document.createElement("option")
n.text = o.text
n.value = o.value
oTarget.add n
Next
End Sub

Resources