I want to have a URL in the helpfile part of the VBScript MsgBox() function. How do I do that?
Here is the code:
Dim error
Dim helpPath
helpPath = "http://www.example.com/example-support-page"
error = MsgBox("There was an error doing whatever.", vbSystemModal + vbCritical, "Uh oh!")
helpPath = MsgBox("", vbSystemModal + vbMsgBoxHelpButton, "", helpPath)
I used this answer and it worked:
Not sure of any way to get a hyperlink into a msgbox. However, you can format your msgbox as 'Oops - shall we go to the help page?' and use Yes/No buttons then code the 'Yes' option as and open() command with the URL as the parameter to invoke the browser to open via the OS. No reason why that would not work.
- Vanquished Wombat
(I copied and pasted it because I can't seem to mark a comment as an answer.)
Related
My first time being here.
I have a VB Project, and I want it to Auto Copy when the Link is changed. But I don't want it to copy at start. I tried making this, but I got the "Expression Expected" error.
Code:
If txtImgurLink.Text = "Imgur URL" Then
End If
If Else Then
Clipboard.SetText(txtImgurLink.Text)
You put an If followed by an Else, and that's not allowed on VB.
Try this instead:
If txtImgurLink.Text <> "Imgur URL" Then
Clipboard.SetText(txtImgurLink.Text)
End If
This question already has an answer here:
While Running the vba script i am getting error Microsoft VBScript runtime error: object required : 'DoCmd'
(1 answer)
Closed 8 years ago.
Hi Any one please help me..
while running the vba script i am getting error--object DoCmd need to create.
My script is given below..
ExecuteInsert
Sub ExecuteInsert()
Dim sheetPath
Dim dbs, DbFullName, acc
Set acc = CreateObject("Access.Application")
DbFullName = "D:\G\Diamond\FINAL MS-Access\Demo\MS-Access project.accdb"
Set dbs = acc.DBEngine.OpenDatabase(DbFullName, False, False)
dbs.Execute "Delete from TempRoadMap"
sheetPath = "C:\Users\270784\Desktop\CSPRV scheduled work - 2014 through 1-26-14.xlsx"
DoCmd.TransferSpreadsheet acImport, acSpreadsheetTypeExcel97, "TempRoadMap", sheetPath, True
MsgBox "Imported Sheet1 from " & sheetPath & " Successfully!"
dbs.Execute "Delete from RoadMap"
dbs.Execute "INSERT INTO [RoadMap] ( Release_Name,SPRF,SPRF_CC,Estimate_Type,PV_Work_ID,SPRF_Name,Estimate_Name,Project_Phase,CSPRV_Status,Scheduling_Status,Impact_Type,Onshore_Staffing_Restriction,Applications,Total_Appl_Estimate,Total_CQA_Estimate,Estimate_Total,Requested_Release,Item_Type,Path) SELECT [TempRoadMap.Release Name], [TempRoadMap.SPRF], [TempRoadMap.Estimate (SPRF-CC)],[TempRoadMap.Estimate Type],[TempRoadMap.PV Work ID],[TempRoadMap.SPRF Name],[TempRoadMap.Estimate Name],[TempRoadMap.Project Phase],[TempRoadMap.CSPRV Status],[TempRoadMap.Scheduling Status],[TempRoadMap.Impact Type],[TempRoadMap.Onshore Staffing Restriction],[TempRoadMap.Applications],[TempRoadMap.Total Appl Estimate],[TempRoadMap.Total CQA Estimate],[TempRoadMap.Estimate Total],[TempRoadMap.Requested Release],[TempRoadMap.Item Type],[TempRoadMap.Path] FROM [TempRoadMap] "
dbs.Close
MsgBox "Done"
End Sub
Assuming that by "...through cmd prompt..." you mean to imply that you are running this script as part of a VBScript file, here are the changes you would want to make:
DoCmd is a child of an Access.Application, and it can only be referenced globally in the scope of an Access database. To reference it in VBScript, you must explicitly use an Access.Application instance, which you have as variable acc. Modify the beginning of the DoCmd line like so:
acc.DoCmd.TransferSpreadsheet
VBScript won't recognize Access constants like acImport or acSpreadsheetTypeExcel97, so you will have to replace them with their actual values. A quick look through msdn reveals that acImport is 0 and acSpreadsheetTypeExcel97 doesn't exist, but acSpreadsheetTypeExcel8 (Excel 97 format) is 8. So now the DoCmd line looks like:
acc.DoCmd.TransferSpreadsheet 0, 8, "TempRoadMap", sheetPath, True
VBScript does not have MsgBox - this is only available through VBA. Instead, you can use Wscript.Echo. For example, the last line would be: WScript.Echo "Done"
If you still have issues after making those changes, please let me know with a comment below.
VBScript certainly does have msgbox and echo is not part of vbscript but of Windows Scripting Host.
I am working on porting a project in Windows over to OSX. I have overcome issues with VBA for OSX Word 2011 not allowing you to send POSTs to a server and have figured out how to return a string result from an external script. Now I have to insert an image in my Word file from a URL that is built using the return of my external script.
The current attempt is as follows, and works in Windows but crashes Word in OSX:
Selection.InlineShapes.AddPicture FileName:=File_Name, _
LinkToFile:=False, SaveWithDocument:=True
After doing some research, it looks like MS may have disabled this functionality in OSX as a "security risk". I still need to make it work. Does anybody know of a way within VBA for Office 2011 to make this work, or barring that a workaround? I am trying to avoid writing the image file to the disk if possible.
UPDATE: I have created a Python script for getting the image file from a URL, but I still do not know how to get this image from the Python script into VBA, and from there into the Word document at the location of the cursor. The important bits of the script are below. The image is read in as a PIL object and I can show it using img.show() just fine, but I am not sure what filetype this is or how to get VBA to accept it.
# Import the required libraries
from urllib2 import urlopen, URLError
from cStringIO import StringIO
from PIL import Image
# Send request to the server and receive response, with error handling!
try:
# Read the response and print to a file
result = StringIO(urlopen(args.webAddr + args.filename).read())
img = Image.open(result)
img.show()
except URLError, e:
if hasattr(e, 'reason'): # URL error case
# a tuple containing error code and text error message
print 'Error: Failed to reach a server.'
print 'Reason: ', e.reason
elif hasattr(e, 'code'): # HTTP error case
# HTTP error code, see section 10 of RFC 2616 for details
print 'Error: The server could not fulfill the request.'
print 'Error code: ', e.code
Note that in the above, args.webAddr and args.filename are passed to the script using the argparse library. This script works, and will show the image file that I expect. Any ideas on how to get that image into Word 2011 for OSX and insert it under the cursor?
Thanks a lot!
Edit: updated the link to the project since migrating to github.
Old question, but no answer, and I see the same crash here when the image is at an http URL. I think you can use the following workaround
Sub insertIncludePictureAndUnlink()
' Put your URL in here...
Const theImageURL As String = ""
Dim f As Word.Field
Dim r As Word.Range
Set f = Selection.Fields.Add(Range:=Selection.Range, Type:=wdFieldIncludePicture, Text:=Chr(34) & theImageURL & Chr(34), PreserveFormatting:=False)
Set r = f.Result
f.Unlink
Set f = Nothing
' should have an inlineshape in r
Debug.Print r.InlineShapes.Count
' so now you can do whatever you need, e.g....
r.Copy
Set r = Nothing
End Sub
I'm trying the following code:
Try ' DOESN'T WORK
Throw 2 ' How do I throw an exception?
Catch ex
'What do I do here?
End Try
but I'm getting the error Statement expected in the catch clause.
Does anyone know how I can catch/throw exceptions in VBScript using try/catch? (I am not looking for solutions with On Error Do X.)
Handling Errors
A sort of an "older style" of error handling is available to us in VBScript, that does make use of On Error Resume Next. First we enable that (often at the top of a file; but you may use it in place of the first Err.Clear below for their combined effect), then before running our possibly-error-generating code, clear any errors that have already occurred, run the possibly-error-generating code, and then explicitly check for errors:
On Error Resume Next
' ...
' Other Code Here (that may have raised an Error)
' ...
Err.Clear ' Clear any possible Error that previous code raised
Set myObj = CreateObject("SomeKindOfClassThatDoesNotExist")
If Err.Number <> 0 Then
WScript.Echo "Error: " & Err.Number
WScript.Echo "Error (Hex): " & Hex(Err.Number)
WScript.Echo "Source: " & Err.Source
WScript.Echo "Description: " & Err.Description
Err.Clear ' Clear the Error
End If
On Error Goto 0 ' Don't resume on Error
WScript.Echo "This text will always print."
Above, we're just printing out the error if it occurred. If the error was fatal to the script, you could replace the second Err.clear with WScript.Quit(Err.Number).
Also note the On Error Goto 0 which turns off resuming execution at the next statement when an error occurs.
If you want to test behavior for when the Set succeeds, go ahead and comment that line out, or create an object that will succeed, such as vbscript.regexp.
The On Error directive only affects the current running scope (current Sub or Function) and does not affect calling or called scopes.
Raising Errors
If you want to check some sort of state and then raise an error to be handled by code that calls your function, you would use Err.Raise. Err.Raise takes up to five arguments, Number, Source, Description, HelpFile, and HelpContext. Using help files and contexts is beyond the scope of this text. Number is an error number you choose, Source is the name of your application/class/object/property that is raising the error, and Description is a short description of the error that occurred.
If MyValue <> 42 Then
Err.Raise(42, "HitchhikerMatrix", "There is no spoon!")
End If
You could then handle the raised error as discussed above.
Change Log
Edit #1:
Added an Err.Clear before the possibly error causing line to clear any previous errors that may have been ignored.
Edit #2:
Clarified.
Edit #3:
Added comments in code block. Clarified that there was expected to be more code between On Error Resume Next and Err.Clear. Fixed some grammar to be less awkward. Added info on Err.Raise. Formatting.
VBScript doesn't have Try/Catch. (VBScript language reference. If it had Try, it would be listed in the Statements section.)
On Error Resume Next is the only error handling in VBScript. Sorry. If you want try/catch, JScript is an option. It's supported everywhere that VBScript is and has the same capabilities.
Try Catch exists via workaround in VBScript:
http://web.archive.org/web/20140221063207/http://my.opera.com/Lee_Harvey/blog/2007/04/21/try-catch-finally-in-vbscript-sure
Class CFunc1
Private Sub Class_Initialize
WScript.Echo "Starting"
Dim i : i = 65535 ^ 65535
MsgBox "Should not see this"
End Sub
Private Sub CatchErr
If Err.Number = 0 Then Exit Sub
Select Case Err.Number
Case 6 WScript.Echo "Overflow handled!"
Case Else WScript.Echo "Unhandled error " & Err.Number & " occurred."
End Select
Err.Clear
End Sub
Private Sub Class_Terminate
CatchErr
WScript.Echo "Exiting"
End Sub
End Class
Dim Func1 : Set Func1 = New CFunc1 : Set Func1 = Nothing
Sometimes, especially when you work with VB, you can miss obvious solutions. Like I was doing last 2 days.
the code, which generates error needs to be moved to a separate function. And in the beginning of the function you write On Error Resume Next. This is how an error can be "swallowed", without swallowing any other errors. Dividing code into small separate functions also improves readability, refactoring & makes it easier to add some new functionality.
I'm installing a network printers using vbscript and I want to show a friendly error if the queue doesn't exist or the printer server is unavailable, can I do this with VBScript? My code is below.
Dim net
Set net = CreateObject("WScript.Network")
net.AddWindowsPrinterConnection "\\printsrv\HPLaser23"
net.SetDefaultPrinter "\\printsrv\HPLaser23"
Many thanks for the help
Steven
Add the line:
On Error Resume Next ' the script will "ignore" any errors
Before your code
and then do an:
if Err.Number <> 0 then
' report error in some way
end if
On Error GoTo 0 ' this will reset the error handling to normal
After your code
It's normally best to try to keep the number of lines of code between the On Error Resume Next and the On Error GoTo 0 to as few as possible, since it's seldom good to ignore errors.