Showing posts with label Visual Basic for Applications. Show all posts
Showing posts with label Visual Basic for Applications. Show all posts

2021-05-13

Open a URL using VBA

This is just a quick tip on opening a hyperlink using the default browser in VBA. It uses the ShellExecute Windows API call. Call the OpenHyperlink function shown below with the URL that you want to open.

Private Declare PtrSafe Function ShellExecute Lib "shell32.dll" Alias "ShellExecuteA" ( _
  ByVal hWnd As Long, _
  ByVal lpOperation As String, _
  ByVal lpFile As String, _
  ByVal lpParameters As String, _
  ByVal lpDirectory As String, _
  ByVal nShowCmd As Long _
  ) As Long

Public Function OpenHyperlink(ByRef strHyperlink As String) As Long
    OpenHyperlink = ShellExecute(0, "Open", strHyperlink, vbNullString, vbNullString, vbNormalFocus)
End Function

An example of calling it is:

Call OpenHyperlink("http://blog.xoc.net")

2020-06-17

Creating a Break Timer in PowerPoint using VBA

When I teach live classes, I use the SysInternals Zoomit application, which has a break timer built in. However, I was teaching a online class, and Zoomit did not seem to get along with WebEx. I decided to write a break timer directly into the PowerPoint slides I was using.

The first step is to create a slide at the end of the presentation that looks like this:


In other words, it is a standard slide with a title at the top and bullet points section below. I centered both and removed the bullet, so it just had text on the time. The code below counts on this slide as being the last in the presentation.

Next I brought up the PowerPoint Visual Basic Editor. You can do this with Alt+F11. Insert a module with Insert > Module from the menu. In the module, add this VBA code:

Option Explicit

Private Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal Milliseconds As Long)
Private lngPreviousSlide As Long
Private boolEndBreak As Boolean

Public Sub BreakTimer()
    Dim dtmStart As Date
    Dim dtmEnd As Date
    Dim slidesCollection As slides
    Dim slideBreak As slide
    Dim lngCurrentSlide As Long
   
    dtmStart = Now
    dtmEnd = DateAdd("n", 10, dtmStart)
   
    Set slidesCollection = Application.ActivePresentation.slides
    Set slideBreak = slidesCollection(slidesCollection.Count)
   
    lngCurrentSlide = SlideShowWindows(1).View.slide.SlideIndex
    If lngCurrentSlide = slidesCollection.Count Then
        'On the break slide, end the break early
        boolEndBreak = True
    Else
        ' Go on break
        lngPreviousSlide = lngCurrentSlide
        boolEndBreak = False
        SlideShowWindows(1).View.GotoSlide slidesCollection.Count, msoTrue
        DoEvents
        Do Until (Now > dtmEnd) Or boolEndBreak
            slideBreak.Shapes(2).TextFrame.TextRange.Text = Format(dtmEnd - Now, "n:ss")
            Sleep 900
            DoEvents
        Loop
        SlideShowWindows(1).View.GotoSlide lngPreviousSlide, msoFalse
    End If
End Sub

When this code run, it remembers the current slide, changes the code to the last slide, and starts a 10 minute countdown (Change the 10 in the DateAdd function to another number to do a different number of minutes in your break).

I then went to the master slide (View > Slide Master) and added a small button in the lower right hand corner. To add a button, you need to have the Developer ribbon turned on. Use File > Options > Customize Ribbon and check the checkbox next to Developer in the dialog and press OK. Then switch to your Developer ribbon.

On the Developer ribbon, Click the Command Button icon, then draw the button on the master slide. Then click the Properties button on the ribbon. Set the name of the button to cmdBreak, and select a clock type image file in the Picture property by hitting the ... button on the right. Then double-click on the button you just created. This creates an Event Handler for the button. In the Event Handler, add this code:

Option Explicit

Private Sub cmdBreak_Click()
    Call BreakTimer
End Sub

Close the Master slide. Run your presentation. Whenever you want to call a break, click the button in the lower right of the current slide. It will jump to your break slide and start counting down. At the end of the break, it will jump back to the slide it was on. If you want to end the break early, on the break slide, click the break button and it will end it (the code is re-entrant, so it can be processing and the button is hit again, which executes it a second time while the first instance is still running).

2017-06-03

VBA Runtime Error Codes

I was teaching a VBA (Visual Basic for Applications) class for Excel today, and the question came up, "is there a list of all of the runtime error code numbers and what they mean?" You might be able to find one, but the easiest thing to do is to generate the list. Here is a small piece of VBA code that shows all of the runtime error code numbers and their descriptions.

Public Sub DisplayErrors()
    Dim i As Long
    
    For i = 1 To 65535
        If Error(i) <> "Application-defined or object-defined error" Then
            Debug.Print i & " " & Error(i)
        End If
    Next i
End Sub

When you run the code, it will print the list to the Immediate Window in the VBA Editor. Press Ctrl+G to make the Window visible.

It is possible to get other runtime errors, but only from some component that is called by VBA, not from VBA itself. When I run the code, this is the list that I get:

3 Return without GoSub
5 Invalid procedure call or argument
6 Overflow
7 Out of memory
9 Subscript out of range
10 This array is fixed or temporarily locked
11 Division by zero
13 Type mismatch
14 Out of string space
16 Expression too complex
17 Can't perform requested operation
18 User interrupt occurred
20 Resume without error
28 Out of stack space
35 Sub or Function not defined
47 Too many DLL application clients
48 Error in loading DLL
49 Bad DLL calling convention
51 Internal error
52 Bad file name or number
53 File not found
54 Bad file mode
55 File already open
57 Device I/O error
58 File already exists
59 Bad record length
61 Disk full
62 Input past end of file
63 Bad record number
67 Too many files
68 Device unavailable
70 Permission denied
71 Disk not ready
74 Can't rename with different drive
75 Path/File access error
76 Path not found
91 Object variable or With block variable not set
92 For loop not initialized
93 Invalid pattern string
94 Invalid use of Null
96 Unable to sink events of object because the object is already firing events to the maximum number of event receivers that it supports
97 Can not call friend function on object which is not an instance of defining class
98 A property or method call cannot include a reference to a private object, either as an argument or as a return value
321 Invalid file format
322 Can't create necessary temporary file
325 Invalid format in resource file
380 Invalid property value
381 Invalid property array index
382 Set not supported at runtime
383 Set not supported (read-only property)
385 Need property array index
387 Set not permitted
393 Get not supported at runtime
394 Get not supported (write-only property)
422 Property not found
423 Property or method not found
424 Object required
429 ActiveX component can't create object
430 Class does not support Automation or does not support expected interface
432 File name or class name not found during Automation operation
438 Object doesn't support this property or method
440 Automation error
442 Connection to type library or object library for remote process has been lost. Press OK for dialog to remove reference.
443 Automation object does not have a default value
445 Object doesn't support this action
446 Object doesn't support named arguments
447 Object doesn't support current locale setting
448 Named argument not found
449 Argument not optional
450 Wrong number of arguments or invalid property assignment
451 Property let procedure not defined and property get procedure did not return an object
452 Invalid ordinal
453 Specified DLL function not found
454 Code resource not found
455 Code resource lock error
457 This key is already associated with an element of this collection
458 Variable uses an Automation type not supported in Visual Basic
459 Object or class does not support the set of events
460 Invalid clipboard format
461 Method or data member not found
462 The remote server machine does not exist or is unavailable
463 Class not registered on local machine
481 Invalid picture
482 Printer error
735 Can't save file to TEMP
744 Search text not found
746 Replacements too long