I'm using the code below to scrape IE and need to update it to work with Edge. Everything I've found on the topic says to use Selenium but wouldn't every user need to install the Selenium libraries? Is Selenium the only option?
I tried using this same code to look for the Edge window but for some reason it doesn't show up in the Windows collection.
Public Function ReadIEText() As String
If HANDLE_ERRORS Then On Error GoTo ErrHandler
Dim objInstances As Object
Dim objIE As Object
Dim strTxt As String
Dim strName As String
Set objInstances = CreateObject("Shell.Application").Windows
If objInstances.COUNT > 0 Then '/// make sure we have instances open.
For Each objIE In objInstances
strName = ""
'Not all windows will have the FullName property
'need to ignore the error by resuming next line
On Error Resume Next
strName = objIE.FullName
' If HANDLE_ERRORS Then On Error GoTo ErrHandler
'See if the window is IE
If Right(strName, 12) = "IEXPLORE.EXE" Then '/// it's internet explorer not windows explorer.
'See if CACS
If Left(objIE.LocationURL, 17) = "https://collectna" Then
'Get the text from the CACS window
strTxt = objIE.Document.frames("mainframe").Document.Body.InnerText
'If the CPR GUI wasn't found try the main document
If InStr(strTxt, "CPR") = 0 Then
'Get the text from the CACS window
strTxt = objIE.Document.Body.InnerText
End If
'Exit loop once CPR GUI view is found
If InStr(strTxt, "CPR") <> 0 Then Exit For
End If
End If
Next
End If
'Return the text from the CACS window
If InStr(strTxt, "CPR") > 0 Then ReadIEText = strTxt
ExitProc:
'Close the Object when done with it!
Set objInstances = Nothing
Set objIE = Nothing
Exit Function
ErrHandler:
RecErr Err.Number, Err.Description, "frmAccountView", "ReadIEText"
Resume ExitProc
End Function
Related
I have an access database which prints a label as a word document. The word document is filled using the information from my access database and then closed. This works on my personal laptop and prints every time. When I transfer this to my work laptop it works the first time and then fails as the document has remained open. The document does not show up in the processes in task manager, my laptop is using office 365 and my work laptop is at office 2016 is this a version issue? Code below. If this is completely wrong could you please suggest the fix
Dim appWord As Word.Application
Dim doc As Word.Document
Dim thepath As String
thepath = CurrentProject.Path
'Avoid error 429, when Word isn't open.
On Error Resume Next
Err.Clear
'Set appWord object variable to running instance of Word.
Set appWord = GetObject(, "Word.Application")
If Err.Number <> 0 Then
'If Word isn't open, create a new instance of Word.
Set appWord = New Word.Application
End If
Set doc = appWord.Documents.Open(thepath & "\label.docx", , False)
'ActiveDocument.Tables(1).Cell(1, 1).va Me.PartNumber
'
'ActiveDocument.FormFields(fldPartNumber). = Me!PartNumber
If Selection.FormFields.Count >= 1 Then
MsgBox Selection.FormFields(1).Name
End If
ActiveDocument.FormFields("Text1").Result = Me.PartNumber
ActiveDocument.FormFields("Text2").Result = Me.SerialNumber
'MsgBox (ActiveDocument.FormFields("Text1").Result)
ActiveDocument.FormFields("Text10").Result = Me.BatchNumber
ActiveDocument.FormFields("Text7").Result = Me.Qty
ActiveDocument.FormFields("Text6").Result = Me.Lifex
ActiveDocument.FormFields("Text3").Result = Me.Station
ActiveDocument.FormFields("Text4").Result = Me.Store
ActiveDocument.FormFields("Text5").Result = Me.Bin
ActiveDocument.FormFields("Text11").Result = Me.Description
'.FormFields("fldCountry").Result = Me.Country
' FormFields("fldPhone").Result = Me.Phone
'.FormFields("fldFax").Result = Me.Fax
activedocuments.FormFields.Visible = True
'ActiveDocument.FormFields.Activate
appWord.DisplayAlerts = False
doc.PrintOut Background = True
appWord.DisplayAlerts = True
'CreateObject("Shell.Application").Namespace(0).ParseName("C:\Boeing Ireland Serviceable Label editable form.docx").InvokeVerb ("Print")
Set doc = Nothing
doc.Close
appWord.Quit (True)
Set appWord = Nothing
Exit Sub
ErrHandler:
MsgBox Err.Number & ": " & Err.Description
'
End Sub
I think that the problem is the order that you are doing things at the end of the code. You should be closing/quitting objects before setting them to nothing. In addition, I would recommend that you have a single exit section that cleans up objects, regardless of whether there is an error or not. Something like:
Sub sFoo
On Error GoTo E_Handle
' Word automation code here
sExit:
On Error Resume Next
doc.Close
Set doc=Nothing
appWord.Quit (True)
Set appWord=Nothing
Exit Sub
E_Handle:
MsgBox Err.Description
Resume sExit
End Sub
Regards,
Ok, the answer here was a known issue in Microsoft Office automation the document was left open due to failing to reference an object. Microsoft issue 189618 was the reference that i used to fix this.
{Cause
Visual Basic has established a reference to Word due to a line of code that calls a Word object, method, or property without qualifying it with a Word object variable. Visual Basic does not release this reference until you end the program. This errant reference interferes with automation code when the code is run more than once.
Resolution
Modify the code so that each call to a Word object, method, or property is qualified with the appropriate object variable.}
My original error catch was to use on error resume next which allowed the real issue Runtime error 426 to be bypassed. This was due to the line of code setting the doc reference as
`enter code here`Set doc = Documents.Open(thepath & "\label.docx",,False,,,,True)'
as it doesn't reference appword it leaves an instance open. Hence my second time round open document. The fix was simple.
Set doc= appword.Documents.Open(thepath & "\label".docx",,False,,,,True) The code now works, below is a fully corrected and cleaned up version of the script which includes Applecores suggestion that was so kindly provided.
Private Sub Command67_Click()
On Error GoTo E_Handle
Dim appwd As Word.Application
Dim doc As Word.Document
Dim thepath As String
thepath = CurrentProject.Path
Set appwd = CreateObject("Word.Application")
appwd.Visible = True
Set doc = appwd.Documents.Open(thepath & "\label.docx", , False, , , , True)
doc.FormFields("Text1").Result = Me.PartNumber
doc.FormFields("Text2").Result = Me.SerialNumber & nullstring
doc.FormFields("Text10").Result = Me.BatchNumber & nullstring
doc.FormFields("Text7").Result = Me.Qty
doc.FormFields("Text6").Result = Me.Lifex
doc.FormFields("Text3").Result = Me.Station
doc.FormFields("Text4").Result = Me.Store
doc.FormFields("Text5").Result = Me.Bin & nullstring
doc.FormFields("Text11").Result = Me.Description
appwd.DisplayAlerts = False
doc.PrintOut Background = True
appwd.DisplayAlerts = True
doc.Close SaveChanges:=wdDoNotSaveChanges
Set doc = Nothing
appwd.Quit
Set appwd = Nothing
Exit Sub
sExit:
On Error Resume Next
doc.Close
Set doc = Nothing
appwd.Quit
Set appwd = Nothing
Exit Sub
E_Handle:
MsgBox Err.Description
Resume sExit
End Sub
I have a problem with the following Code. What happens is that my PPT application crashes while running the code. It does not always happen and it happens in different parts of the code.
I tried the application.wait-method, but it did not work.
help is appreciated since I am already working on this for days -.-. Thanks in advance.
Option Explicit
Public myfilename As String
Sub filepicker()
Dim i As Variant
MsgBox ("In the following dialog please choose the current file")
Dim myfilenamepicker As FileDialog
Set myfilenamepicker = Application.FileDialog(msoFileDialogFilePicker)
myfilenamepicker.InitialFileName = "C:\Users\Michael\Desktop\Test PPT"
myfilenamepicker.Show
If myfilenamepicker.SelectedItems.Count <> 0 Then
myfilename = myfilenamepicker.SelectedItems(1)
End If
End Sub
Sub Saveas_PPT_and_PDF()
Dim PP As PowerPoint.Presentation
Dim sh As Variant
Dim company, strPOTX, strPfad, pptVorlage, newpath, newpathpdf As String
Dim Cell As Range
Dim pptApp As Object
Call filepicker
Application.ScreenUpdating = False
' set the dropdown from which the company Is Selected
Set DropDown.ws_company = Tabelle2
' the company is the value selected in the dropdown, stored in "C2"
company = DropDown.ws_company.Range("C2").Value
On Error Resume Next
Set pptApp = GetObject(, "PowerPoint.Application")
On Error Resume Next
If pptApp Is Nothing Then
Set pptApp = CreateObject("PowerPoint.Application")
End If
On Error GoTo 0
'loop through the companies in the dropdown menu
For Each Cell In DropDown.ws_company.Range(DropDown.ws_company.Cells(5, 3), _
DropDown.ws_company.Cells(Rows.Count, 3).End(xlUp)).SpecialCells(xlCellTypeVisible)
DropDown.ws_company.Range("C2") = Cell
pptVorlage = myfilename
Debug.Print (myfilename)
Set PP = pptApp.Presentations.Open(pptVorlage)
newpath = Replace(myfilename, "AXO", "" & Cell & " AXO")
PP.UpdateLinks
PP.SaveAs newpath
newpathpdf = Replace(newpath, "pptx", "pdf")
Debug.Print (newpathpdf)
PP.ExportAsFixedFormat "" & newpathpdf & "", ppFixedFormatTypePDF, ppFixedFormatIntentPrint
pptApp.Presentations(newpath).Close
Set PP = Nothing
Next
' this part below closes PPT application if there are no other presentation
' object open. If there is at least 1, it leaves it open
If IsAppRunning("PowerPoint.Application") Then
If pptApp.Windows.Count = 0 Then
pptApp.Quit
End If
End If
Set pptApp = Nothing
Set PP = Nothing
End Sub
Function IsAppRunning(ByVal sAppName) As Boolean
Dim oApp As Object
On Error Resume Next
Set oApp = GetObject(, sAppName)
If Not oApp Is Nothing Then
Set oApp = Nothing
IsAppRunning = True
End If
End Function
I don't see anything obviously wrong but I can give you a strategy for debugging.
You will want to test all major manipulations seperately. You will want to run each test in the debugger and have screenupdating on so you can see what happens:
test the filepicker
test GetObject/CreateObject - do you really need it? You already have PowrPoint open it seems;
test your loop with a single hardcoded value. What happens with the focus when opening a presentation?
try without UpdateLinks; try without SaveAs and try without Export (i.e. just open a presentation and close it again).
check if the presentation really closes, otherwise you might end up with lots of open presentations.
test closing the application
test reading from a dropdown box
test the IsAppRunning function. Note that it sets On Error Resume Next but does not reset it. Note it does not set IsAppRunning = False anywhere.
try relevant parts of the above in a loop with and without debugging to see what happens and see if it crashes - there could be a timing problem in the Office application, e.g. trying to manipulate a presentation while it is not yet fully loaded.
Minimising your code can help isolate the area that causes the problem. I hope this helps.
here is the code I am trying to use, the problem is that every time I try to run it Dim pdfjob As PDFCreator.clsPDFCreatorgives me an error of type:
User-defined type not defined
I have gone into tools and added the reference to PDFCreator, which maps to PDFcreator.tlb and yet it still isn't working...
I am at a loss here, not sure whats missing. I installed PDFCreator 2.1 on my PC and I am running windows 8.
Option Explicit
Sub PrintToPDF(ByVal sPDFName As String, ByVal sPDFPath As String)
Dim pdfjob As PDFCreator.clsPDFCreator
Dim sPDFName As String
Dim sPDFPath As String
Dim bRestart As Boolean
'/// Change the output file name here! ///
'sPDFName = "testPDF.pdf"
'sPDFPath = ActiveWorkbook.Path & Application.PathSeparator
'Check if worksheet is empty and exit if so
If IsEmpty(ActiveSheet.UsedRange) Then Exit Sub
'Activate error handling and turn off screen updates
On Error GoTo EarlyExit
Application.ScreenUpdating = False
Set pdfjob = New PDFCreator.clsPDFCreator
'Check if PDFCreator is already running and attempt to kill the process if so
Do
bRestart = False
Set pdfjob = New PDFCreator.clsPDFCreator
If pdfjob.cStart("/NoProcessingAtStartup") = False Then
'PDF Creator is already running. Kill the existing process
Shell "taskkill /f /im PDFCreator.exe", vbHide
DoEvents
Set pdfjob = Nothing
bRestart = True
End If
Loop Until bRestart = False
'Assign settings for PDF job
With pdfjob
.cOption("UseAutosave") = 1
.cOption("UseAutosaveDirectory") = 1
.cOption("AutosaveDirectory") = sPDFPath
.cOption("AutosaveFilename") = sPDFName
.cOption("AutosaveFormat") = 0 ' 0 = PDF
.cClearCache
End With
'Delete the PDF if it already exists
If Dir(sPDFPath & sPDFName) = sPDFName Then Kill (sPDFPath & sPDFName)
'Print the document to PDF
ActiveSheet.PrintOut copies:=1, ActivePrinter:="PDFCreator"
'Wait until the print job has entered the print queue
Do Until pdfjob.cCountOfPrintjobs = 1
DoEvents
Loop
pdfjob.cPrinterStop = False
'Wait until the file shows up before closing PDF Creator
Do
DoEvents
Loop Until Dir(sPDFPath & sPDFName) = sPDFName
Cleanup:
'Release objects and terminate PDFCreator
Set pdfjob = Nothing
Shell "taskkill /f /im PDFCreator.exe", vbHide
On Error GoTo 0
Application.ScreenUpdating = True
Exit Sub
EarlyExit:
'Inform user of error, and go to cleanup section
MsgBox "There was an error encountered. PDFCreator has" & vbCrLf & "has been terminated. Please try again.", vbCritical, vbOKOnly, "Error"
Resume Cleanup
End Sub
I am experiencing an issue with Outlook automation,
To keep it simple I will first show you a shorter version of my code :
Sub test()
Dim GetOutlookApp As Object
Set GetOutlookApp = CreateObject("Outlook.Application")
End Sub
First, I do want to keep the late binding solution.
This sub launch Outlook in the taskbar (small icon). When I double click on it, a message pops up: "No active explorer object found" (title of the window: "Error"). Then the Outlook Inbox window opens when I click on OK.
My script is for end users so I don't want this message appears even if the user just has to click on OK (the rest of the main sub has no one issue).
I have to solve this problem to be able to send an email with outlook and to make sure the email is not in the Outbox folder.
What I am looking for is a way to open outlook, without this message, using late binding.
Below is the full code to open outlook before sending the email (source: ron de bruin). It works perfectly except the outlook message. The message pops up on this line:
obj.Session.GetDefaultFolder(olFolderInbox).Display
I tried AppActivate and others stuffs but I did not succeed and can't find any info on google about that!
Thanks for your help
Sub send_mail ()
Dim OutApp As Object
Set OutApp = OutlookApp() 'OPEN OUTLOOK
'Set OutApp = CreateObject("Outlook.Application") 'OPEN OUTLOOK simple solution
With ActiveSheet.MailEnvelope
...
End With
End sub
Public Function OutlookApp( _
Optional WindowState As Long = olMaximized, _
Optional ReleaseIt As Boolean = True _
) As Object
'***This sub is a part to the global way to open outlook before sending an email (prevent the outbox bug, email stucked into the outbox)
'***Source: http://www.rondebruin.nl/win/s1/outlook/openclose.htm, late binding mode
Static obj As Object
On Error GoTo ErrHandler
Select Case True
Case obj Is Nothing, Len(obj.Name) = 0
Set obj = GetObject(, "Outlook.Application")
If obj.Explorers.Count = 0 Then
InitOutlook:
'Open inbox to prevent errors with security prompts
obj.Session.GetDefaultFolder(olFolderInbox).Display
obj.ActiveExplorer.WindowState = WindowState
End If
Case ReleaseIt
Set obj = Nothing
End Select
Set OutlookApp = obj
ExitProc:
Exit Function
ErrHandler:
Select Case Err.Number
Case -2147352567
'User cancelled setup, silently exit
Set obj = Nothing
Case 429, 462
MsgBox "Err.Number OutlookApp: " & Err.Number
Set obj = GetOutlookApp()
If obj Is Nothing Then
Err.Raise 429, "OutlookApp", "Outlook Application does not appear to be installed."
Else
Resume InitOutlook
End If
Case Else
MsgBox "Error " & Err.Number & ": " & Err.Description, vbCritical, "Unexpected error"
End Select
Resume ExitProc
Resume
End Function
Private Function GetOutlookApp() As Object
'***This sub is a part to the global way to open outlook before sending an email (prevent the outbox bug, email stucked into the outbox)
'***Source: http://www.rondebruin.nl/win/s1/outlook/openclose.htm, late binding mode
'On Error GoTo ErrHandler
Set GetOutlookApp = CreateObject("Outlook.Application")
ExitProc:
Exit Function
ErrHandler:
Select Case Err.Number
Case Else
'Do not raise any errors
Set GetOutlookApp = Nothing
End Select
Resume ExitProc
Resume
End Function
Use the Add method of the Explorers class to create a new instance of the explorer window. Then you need to call the Display method of the Explorer class (not Folder).
Sub DisplayDrafts()
Dim myExplorers As Outlook.Explorers
Dim myOlExpl As Outlook.Explorer
Dim myFolder As Outlook.Folder
Set myExplorers = Application.Explorers
Set myFolder = Application.GetNamespace("MAPI").GetDefaultFolder(olFolderInbox)
Set myOlExpl = myExplorers.Add(myFolder, olFolderDisplayNoNavigation)
myOlExpl.Display
End Sub
This sub launch Outlook in the taskbar (small icon). When I double click on it, a message pops up: "No active explorer object found" (title of the window: "Error"). Then the Outlook Inbox window opens when I click on OK.
Typically you shouldn't see any icons in the task bar. Make sure that you have all the latest updates and service packs installed for the OS and Outlook. Also check out the list of running processes before automating Outlook - make sure that no Outlook instances running at the moment.
See How to automate Outlook from another program for more information.
Using the Eugene Astafiev code I have solved my issue! Thanks Eugene!
Here is the code:
Sub that send the email:
Sub Send_Mail()
'**This sub aims to send the mail that contains the job sheet
'Deactivate the screen updating : increase the speed and looks better
Application.ScreenUpdating = False
'Select the range of data
ActiveSheet.Range(FirstCol_JS & 1 & ":" & LastCol_JS & Firstrow_JS + nb_item_scanned - 1).Select
'Show the envelope on the ActiveWorkbook. This line prevents a bug (Method 'MailEnveloppe' of object '_Worksheet' failed. -2147467259, 80004005)
ActiveWorkbook.EnvelopeVisible = True
'Make sure outlook is opened or open it *****HERE IS WHY MY QUESTION*****
Call OutlookApp <------------------------------------------------
'Email error handling
On Error GoTo ErrorManagement
With ActiveSheet.MailEnvelope
'Subject is the title of the mail
.Item.Subject = "Job Sheet"
'Introduction is the content of the mail
.Introduction = "Hi John," & vbCrLf & _
"..." & vbCrLf & _
"Regards, The computer"
.Item.To = "alias#domain.com"
.Item.Send
End With
'Select the home page (main sheet)
'It is needed to activate the screenupdating so that the userform can be displayed on the sheet1
Application.ScreenUpdating = True
Else
'Normally, this message should never appear
MsgBox "You can't create a job sheet without any item. Nothing was done.", , "Action not allowed"
End If
'Exit sub before the error handling codes
Exit Sub
ErrorManagement:
'Activate the screen updating : be able to show that the outlook interface disappears
Application.ScreenUpdating = True
'Hide the outlook interface
ActiveWorkbook.EnvelopeVisible = False
'Activate the Excel windows so that the msgbox does not appear in the Windows taskbar
'This line is mandatory because the outlook interface is in front of the Excel workbook when it appears, so we have to activate again the Excel worbook
Call ActivateExcel
End Sub
Principal sub that manage to open Outlook
Sub OutlookApp(Optional ReleaseIt As Boolean = True)
'***This sub is a part to the global way to open outlook before sending an email (prevent the outbox bug, email stucked into the outbox)
'***Source: http://www.rondebruin.nl/win/s1/outlook/openclose.htm, late binding mode, and Eugene Astafiev http://stackoverflow.com/questions/31198130/vba-outlook-no-active-explorer-found
'Declaration of an object for outlook. The static mode allows to keep the object when this sub is launched more than one time
Static olObject As Object 'Early binding: Outlook.Application
'Declaration of variable objects to open the outlook window (prevent the email to be stuck in the Outbox folder)
Dim myExplorers As Object 'Early binding: Outlook.Explorers
Dim myOlExpl As Object 'Early binding: Outlook.Explorer
Dim myFolder As Object 'Early binding: Outlook.Folder
'Error handling
On Error GoTo ErrHandler
Select Case True
'If the olObject is nothing then try to create it
Case olObject Is Nothing, Len(olObject.Name) = 0
'This line will work if outlook is already opened, otherwise it will create an error and the code will go to ErrHandler
Set olObject = GetObject(, "Outlook.Application")
'If there is not already one opened windows of outlook
If olObject.Explorers.Count = 0 Then
InitOutlook:
'Open outlook window to prevent the email to be stucked in the Outbox folder (not sent)
Set myExplorers = olObject.Explorers
Set myFolder = olObject.GetNamespace("MAPI").GetDefaultFolder(6) 'olFolderInbox: 6
Set myOlExpl = myExplorers.Add(myFolder, 0) 'olFolderDisplayNoNavigation: 2, olFolderDisplayNormal:0
'Early binding code:
'Set myExplorers = Application.Explorers
'Set myFolder = Application.GetNamespace("MAPI").GetDefaultFolder(olFolderInbox)
'Set myOlExpl = myExplorers.Add(myFolder, olFolderDisplayNoNavigation)
myOlExpl.Display
End If
End Select
'Delete the olObject variable is the ReleaseIt boolean is true
If ReleaseIt = True Then
Set olObject = Nothing
End If
'Possibility to set the OutlookApp function as the outlook object, if OutlookApp is declared like this: "Function OutlookApp(Optional ReleaseIt As Boolean = True) as Object"
'Set OutlookApp = olObject
ExitProc:
Exit Sub
ErrHandler:
Select Case Err.Number
Case -2147352567
'User cancelled setup, silently exit
Set olObject = Nothing
Case 429, 462 '429: outlook was not opened, the Set olObject = GetObject(, "Outlook.Application") code line above did not work
Set olObject = CreateOutlook() 'Launch the CreateOutlook function: CreateOutlook = CreateObject("Outlook.Application")
If olObject Is Nothing Then 'If the outlook object is still empty it means that there is a more serious issue (outlook not installed on the computer for example)
Err.Raise 429, "OutlookApp", "Outlook Application does not appear to be installed."
Else 'If olObject is no more nothing, go back to the code above and open the outlook window
Resume InitOutlook
End If
Case Else 'For any other error numbers
MsgBox "Error " & Err.Number & ": " & Err.Description, vbCritical, "Unexpected error"
End Select
Resume ExitProc
Resume 'For debugging
End Sub
Second sub that manage to open outlook
Private Function CreateOutlook() As Object
'***This sub is a part to the global way to open outlook before sending an email (prevent the outbox bug, email stucked into the outbox)
'***Source: http://www.rondebruin.nl/win/s1/outlook/openclose.htm, late binding mode
'Error handling
On Error GoTo ErrHandler
Set CreateOutlook = CreateObject("Outlook.Application")
ExitProc:
Exit Function
ErrHandler:
Set CreateOutlook = Nothing
Resume ExitProc
Resume 'For debugging
End Function
FYI here is the code to activate the Excel window
Sub ActivateExcel()
'***This sub aims to activate Excel windows (so that it's in front of the windows)
'Set variable title equal to exact application window title
Dim ExcelTitleCaption As String
ExcelTitleCaption = Application.Caption
'Activate Microsoft Excel
AppActivate ExcelTitleCaption
End Sub
Thanks!! Topic solved
I am trying to create a context menu so that when I right-click on someone's name it will query a webpage to bring back their rolodex information. It is not kept in the local contacts. I have it in a webpage.
I have this I found and have been using (snippet of larger sub),
' Configure the button to call the
' DisplayItemMetadata routine when
' clicked. The Parameter property of the
' button is set to the value of the
' EntryID property for the selected
' item, if possible.
With objButton
.Caption = "&Look Up Name"
.FaceId = 1000
.Tag = "DisplayItemMetadata"
If Not IsNull(Selection.Item(1)) Then
On Error GoTo 0
' Just in case the item selected
' doesn't have a valid EntryID.
.Parameter = Selection.Item(1).EntryID
On Error GoTo ErrRoutine
End If
'.OnAction = _
' "Project1.ThisOutlookSession.DisplayItemMetadata"
.OnAction = _
"NavigateToURL(""http://somewebsite"")"
End With
It never calls the NavigateToURL sub. It never calls the function, so I can never get to the below code. No errors. Breakpoints and Debug show it simply ending the With and Sub. I have tried using,
Call NavigateToURL(""http://somewebsite"")
NavigateToURL "http://somewebsite"
Neither work. I get Expected Expression.
Public Sub NavigateToURL(ByVal argURL As String)
MsgBox ("hi")
Const READYSTATE_COMPLETE As Integer = 4
Dim objIE As Object
Set objIE = CreateObject("InternetExplorer.Application")
With objIE
.Visible = False
.Silent = True
.Navigate argURL
Do Until .ReadyState = READYSTATE_COMPLETE
DoEvents
Loop
End With
objIE.Quit
Set objIE = Nothing
End Sub
If there is another way to open a webpage with a context menu? Tooltip?
EDIT: Sorry. I had to find where I got it. It is from Microsoft.
Sub Application_ItemContextMenuDisplay( _
ByVal CommandBar As Office.CommandBar, _
ByVal Selection As Selection)
Dim objButton As Office.CommandBarButton
On Error GoTo ErrRoutine
If Selection.Count = 1 Then
' Add a new button to the bottom of the CommandBar
' (which represents the item context menu.)
Set objButton = CommandBar.Controls.Add( _
msoControlButton)
' Configure the button to call the
' DisplayItemMetadata routine when
' clicked. The Parameter property of the
' button is set to the value of the
' EntryID property for the selected
' item, if possible.
With objButton
.Caption = "&Display metadata"
.FaceId = 1000
.Tag = "DisplayItemMetadata"
If Not IsNull(Selection.Item(1)) Then
On Error GoTo 0
' Just in case the item selected
' doesn't have a valid EntryID.
.Parameter = Selection.Item(1).EntryID
On Error GoTo ErrRoutine
End If
.OnAction = _
"Project1.ThisOutlookSession.DisplayItemMetadata"
End With
End If
EndRoutine:
Exit Sub
ErrRoutine:
MsgBox Err.Number & " - " & Err.Description, _
vbOKOnly Or vbCritical, _
"Application_ItemContextMenuDisplay"
GoTo EndRoutine
End Sub
Private Sub DisplayItemMetadata()
Dim objNamespace As NameSpace
Dim objItem As Object
Dim strEntryID As String
On Error GoTo ErrRoutine
' Retrieve the value of the Parameter property from the
' control that called this routine.
strEntryID = _
Application.ActiveExplorer.CommandBars.ActionControl.Parameter
' If there's no entry ID, we can't easily retrieve the item.
If strEntryID = "" Then
MsgBox "An entry ID could not be retrieved from " & _
"the selected menu item."
Else
' Fetch an item reference using the specified entry ID.
Set objNamespace = Application.GetNamespace("MAPI")
Set objItem = objNamespace.GetItemFromID(strEntryID)
If objItem Is Nothing Then
MsgBox "A reference for the Outlook item " & _
"could not be retrieved."
Else
' Display information about the item.
MsgBox "Message Class: " & objItem.MessageClass & vbCrLf & _
"Size: " & objItem.Size
End If
End If
EndRoutine:
Set objItem = Nothing
Set objNamespace = Nothing
Exit Sub
ErrRoutine:
MsgBox Err.Number & " - " & Err.Description, _
vbOKOnly Or vbCritical, _
"DisplayItemMetadata"
GoTo EndRoutine
End Sub
NOTE: If you provide the code that creates the context menu, I'll gladly test this out, but I'm not going to be able to help much further unless you provide that code.
What I am trying to say in comments above, is that you have specified an argument for OnAction that may not be recognized, and as such, no procedure is being called.
Based only on the example syntax, I assume that this needs a fully-qualified construct of the procedure name. In the example syntax, it has:
.OnAction = "Project1.ThisOutlookSession.SomeProcedure"
But your code omits the Project and Session scope.
Something like .OnAction = "Project1.ThisOutlookSession.NavigateToURL" might work, then.
In the above, I would omit the URL as an argument, which requires you modify the procedure NavigateToURL slightly. since the URL is not changing ever, it is silly to pass this as an argument to the procedure NavigateToURL. Within the NavigateToURL procedure, simply declare this as a Const string.
Public Sub NavigateToURL()
Const argURL as String = "http://somewebsite.com" '## Modify as needed
MsgBox ("hi")
Const READYSTATE_COMPLETE As Integer = 4
Dim objIE As Object
Set objIE = CreateObject("InternetExplorer.Application")
With objIE
.Visible = False
.Silent = True
.Navigate argURL
Do Until .ReadyState = READYSTATE_COMPLETE
DoEvents
Loop
End With
objIE.Quit
Set objIE = Nothing
End Sub