Lotus Notes and VBA Checking Email Address in Public Address Books - vba

I'm trying to figure out how to check whether an e-mail address is in the public address book by using VBA. I found some code on the Web, modified it but the code gives an error 91 at line, "Set doc = view.GetAllDocumentsByKey(ChkEmailAddr)." I think that the problem has to do with the declaration type of the variable "view" or the type of view in the line "Set view = b.GetView("People\By Internet Mail")."
I'm pretty certain that I have all of the proper references activated. "Lotus Notes Domino Objects" and "Lotus Notes Automation Classes" are chosen.
I tried to get a list of views but I couldn't figure out how to do it. Do you see the error in my code or have ideas as to what I could try to do some troubleshooting?
Sub CheckEmailAddress()
Dim books As Variant
Dim view As lotus.NotesView
'Dim view As Object
Dim doc As NotesDocumentCollection
Dim dc As NotesDocument
Dim done As Variant
Dim docarr(3, 50) As Variant
Dim ChkEmailAddr As String
ChkEmailAddr = "user#example.com"
Set Session = CreateObject("Notes.Notessession")
books = Session.AddressBooks
done = False
For Each b In books
' check every public address book,
' unless we're already done
If (b.IsPublicAddressBook) Then
Debug.Print TypeName(b)
Call b.Open("", "")
Debug.Print b.Title
' look up person's last name
' in People view of address book
Set view = b.GetView("People\By Internet Mail")
Debug.Print TypeName(view)
'Debug.Print view
'Set view = b.GetView("main")
'Debug.Print TypeName(view)
Set doc = view.GetAllDocumentsByKey(ChkEmailAddr)
' if person is found, display the phone number item
'from the Person document
If Not (doc Is Nothing) Then
For j = 0 To doc.Count
docarr(0, j) = doc.GetNthDocument(j).Items(11).Text
docarr(1, j) = doc.GetNthDocument(j).Items(93).Text
docarr(2, j) = doc.GetNthDocument(j).Items(95).Text
docarr(3, j) = doc.GetNthDocument(j).Items(14).Text
Next j
End If
End If
Next b
findEmailLotus = docarr
End Sub

I'm sorry to say this, but you have a lot of issues here. Whoever wrote that code that you started from did not know what he or she was doing.
First of all, unless you are requiring that the Notes client is running while your code is running, you should be using Lotus.NotesSession instead of Notes.NotesSession. (The former corresponds to the "Lotus Notes Domino Objects", and uses COM to talk to the Notes APIs, and the latter corresponds to the "Lotus Notes Automation Classes, and uses OLE to talk to the Notes client to talk to the APIs - hence the requirement that the client must be running.)
Secondly, you haven't mentioned what version of Lotus Notes you are dealing with, but more recent versions (8 and above) include the NotesDirectory class, which includes a LoookupNames method that would probably be a better solution for you than writing your own code to loop through address books.
Third, after doing your set view operation, you really ought to be doing an If Not view is Nothing test. That will tell you whether or not you actually have a problem opening the view.
Fourth, doc is a really bad variable name for the return value from GetAllDocumentsByKey. In 20+ years of writing Notes code, I can say that anybody reading Notes code expects the variable name doc to always refer to a single document. You are getting a NotesDocumentCollection, not a single document. Do yourself a favor and change it to docs or dc, or just about anything except doc.
Fifth, using GetNthDocument in this context is usually not recommended. It performs very badly in large collections. Even worse, however, is that you are calling it four times when you could be making only one call per iteration. Instead of a For loop, consider changing it to a call to GetFirstDocument followed by While Not doc is Nothing loop that retrieves your item values and stores them in your array, and then calls getNextDocument at the bottom of the loop.
Sixth, that code referencing .Items(11), .Items(93)... that's just plain wrong. The available items within any given document are variable because Notes is schemaless. Those item numbers will refer to different fields for different people - i.e., essentially random values. That can't possibly be what you want. You should be using getFirstItem() calls with the actual names of the items that you really want to be putting in your array. You will need to study the field names used in the Domino Directory to figure this out. I recommend NotesPeek as a good tool for exploring Notes databases and/or just opening up the Domino Directory in the Domino Designer client and looking at the Person form (and associated subforms) to figure out what you need.
As to the actual error you asked about, my guess is that by adding the recommended test of If Not view Is Nothing you will gain more information, but perhaps not enough. You haven't mentioned what your debug prints are generating, but I believe there are some cases where the title is available even if the database was not successfully opened, so I don't think you should trust that as a test of whether the call worked. In fact, you really shouldn't just be doing a Call db.open("","") call. You should be doing an If db.open("","") = true to test whether it actually worked.

For people who know lotus notes, it's trival. For those that don't, there might be an easier way using web access.
Request this address
Keep your cookies
http://server/names.nsf?login&username=MYUSERNAM&password=MYPASSWORD
Then access this url and look for a 404 status or a 200 status
http://server/names.nsf/($Users)/email#domain.com?opendocument
Of course, that requires that you have web access enabled on your server and in many cases putting your password in your code is bad, and it won't work if your servers are configured in some ways.
Before coding, test it on your server.

Related

How to hold a reference to the items matched by `querySelectorAll`, in a variable, that allows you to access its methods?

Intro:
Some of you may have noticed that something has broken in relation to the querySelectorAll method of MSHTML.HTMLDocument from MSHTML.Dll (via a Microsoft HTML Document Library reference). This, I believe, has happened in the last month. It may not affect all users and I will update this Q&A as I get more info on which versions etc are affected. Please feel free to comment below with your set-up and whether working or not for both late-bound and early-bound (as per code in answer)
Accessing DispStaticNodeList methods:
Traditionally, at least in my experience, it has been the norm to hold a reference to the DispStaticNodeList, which is what querySelectorAll returns, in a generic late-bound Object type:
E.g.
Dim nodeList1 As Object
Set nodeList1 = html.querySelectorAll("a")
where html is an instance of MSHTML.HTMLDocument.
As you can see from the Locals window, you get the expected nodeList shown:
You could then access the list of the document's elements, that match the specified group of selectors, with .item(index), and get the number of items matched with .Length. E.g.
Debug.Print nodeList1.item(0).innerText
Debug.Print nodeList1.Length
What happens now?
Attempts to access the methods, via late bound Object, and its underlying interfaces, lead to either an Object required, when using the .item() method call, or Null when querying the .Length(). E.g.
nodeList1.item(0).innertext ' => Run-time error '424': Object required
Debug.Print nodeList1.Length ' => Null
This happens when you hold a reference through assigning to a variable.
What you can do:
You can use With and work off html, avoiding the Object class
With html.querySelectorAll("a")
For i = 0 To .Length - 1
Debug.Print .Item(i).innerText
Next
End With
So, I think the problem is very much about the Object data type and its underlying interfaces. And possibly, something about this has broken in relation to MSHTML, and most likely, the now no longer supported, Internet Explorer, which sits in the background:
However, this is not desirable, as you parse, and re-parse, the same HTML, during the loop, losing much of the efficiency that its gained by choosing css selectors over traditional methods e.g. getElementsByClassName. Those traditional methods remain intact.
Why do some of us care?
Modern browsers (and even IE8 onwards) support faster node matching through use of css selectors. It seems reasonable to assume that this carried over into the DOM parsers with MSHTML.HTMLDocument. So, you have faster matching, combined with more expressive and concise syntax (none of those long chained method calls e.g. getElementsByClassName("abc")(0).getElementsByTagName("def")(0).....), the ability to return more desired nodes, without repeated calls (in the prior example you will only get def as children of the first element with class abc, rather than all children, with tag def, of all elements with class abc, which you would get with querySelectorAll(".abc def"). And, you lose the flexibility to specify much more complex and specific patterns for node matching e.g. querySelectorAll(".abc > def + #ghi). For those interested, you can read more about those selectors on MSDN.
Question:
So, how does one avoid re-parsing, and hold the reference to the returned list of matched nodes? I have found nothing on the internet, despite quite a bit of searching, that documents this recent change in behaviour. It is also a very recent change and that likely only affects a small user base.
I hope the above satisfies the need to demonstrate research into the problem.
My set-up:
OS Name Microsoft Windows 10 Pro
Version 10.0.19042 Build 19042
System Type x64-based PC
Microsoft® Excel® 2019 MSO (16.0.13929.20206) 32-bit (Microsoft Office Professional Plus)
Version 2104 Build 13929.20373
mshtml.dll info as per image
Not affected (TBD):
Office Professional plus 2013. Win 7, 32 bit, MSHTML.dll 11.0.9600.19597
Do not despair VBA web-scrapers (I know there are a few!) We can still have the luxury of css selectors and the benefits, though admittedly somewhat limited in VBA, that they bring.
To the rescue:
MSHTML, gratias IE, offers a number of scripting object interfaces . One of which is the IHTMLDOMChildrenCollection interface, which inherits from IDispatch, and which:
provides methods to access items in the collection.
This includes the .Length property and access to items via .item(index).
Dim nodeList2 As MSHTML.IHTMLDOMChildrenCollection
Set nodeList2 = html.querySelectorAll("a")
Debug.Print nodeList2.Length ' => n
Debug.Print nodeList2.Item(0).innerText
This is supported on clients Windows XP +, and servers from Windows 2000 Server onwards.
VBA:
Public Sub ReviewingNodeListMethods()
'' References (VBE > Tools > References):
''Microsoft HTML object Library
''Microsoft XML library (v.6 for me)
Dim http As MSXML2.XMLHTTP60, html As MSHTML.HTMLDocument 'XMLHTTP60 is for Excel 2016. Change according to your version e.g. XMLHTTP for 2013)
Set http = New MSXML2.XMLHTTP60: Set html = New MSHTML.HTMLDocument
With http
.Open "GET", "http://books.toscrape.com/", False
.send
html.body.innerHTML = .responseText
End With
Dim nodeList1 As Object, nodeList2 As MSHTML.IHTMLDOMChildrenCollection
Set nodeList1 = html.querySelectorAll("a")
Set nodeList2 = html.querySelectorAll("a")
Debug.Print nodeList1.Length ' => Null
Debug.Print nodeList2.Length ' => 94
Debug.Print nodeList2.Item(0).innerText
' Dim i As Long
'
' With html.querySelectorAll("a")
' For i = 0 To .Length - 1
' Debug.Print .Item(i).innerText
' Next
' End With
'' ================Warning: This will crash Excel -============================
' Dim node As MSHTML.IHTMLDOMNode
'
' For Each node In nodeList2
' Debug.Print node.innerText
' Next
'' ================Warning: This will crash Excel -============================
End Sub
N.B. There is still the underlying problem of the collection enumeration method; it causes Excel to crash if you attempt a For Each e.g.
Dim node As MSHTML.IHTMLDOMNode
For Each node In nodeList2
Debug.Print node.innerText
Next
Updating your old Questions/Answers:
You can use this SEDE query to identify potential candidates for revision. Enter your userid and the search term "querySelectorAll"
Or simply use the following in the search bar:
querySelectorAll user:<userid> is:answer ; querySelectorAll user:<userid> is:question

SolidWorks VBA - Translating API Help into useable code

I'd like to do what feels like a fairly simple task, and I've found the specific API Help pages which should make it clear, but, I can't actually make things work.
The Key steps that I would like to achieve are:
Rename the active document
Update References to this document to accommodate new name
Save active document.
This help page shows the Usage for renaming the doc, and under the "Remarks" heading, includes links to the next two steps, mentioning them off hand as if implementing them would be easy.
https://help.solidworks.com/2020/English/api/sldworksapi/SolidWorks.Interop.sldworks~SolidWorks.Interop.sldworks.IModelDocExtension~RenameDocument.html?verRedirect=1
The trouble is, I'm a bit of a VBA beginner - usually I get by with the 'record' function, and then tidying things up from there - but undertaking the steps above manually doesn't result in anything being recorded at all for one reason or another.
Assuming I am able to pass in the item to be renamed (I'll define a variable at the start of the Sub for this e.g. swModel = swApp.ActiveDoc), and the new name (NewName = "NEW NAME HERE"), How would I translate the Help API into a Sub that I can actually run?
Two of them suggest declaring as a Function, and one as a Public Interface - I've never used these before - do these just run in a standard Module? Do I need to write a 'master Sub' to call the different functions sequentially, or could these be included directly in the sub, if they're only to be used once?
[Feeling a little lost - it's demoralizing when the help files aren't all that helpful]
Let me know if there's any more information missing that I can add to improve my question - as I said, I'm fairly new to this coding thing...
The "record" function is sometimes a good point to start but there are a lot of functions it can't recognize while you execute them manually.
The API Help is then useful to find out how to use a specific function.
In almost every example the use of a specific method (e.g. RenameDocument) is only shown abstract. There is always a instance variable which shows you the object-type needed to call this method. So you can use these in every sub you want, but beforehand need access to the specific instance objects.
For your example the RenameDocument method is called with an object of the type IModelDocExtension. First thing for you to do is to get this object and then you can call the method as described in the help article.
Under Remarks in the article you find additional information for what you maybe have to do before or after calling a method.
For your example it is mentioned that the renaming takes permanently place after saving the document.
And finally here is what you want to do with some VBA code:
Dim swApp As SldWorks.SldWorks
Dim swModel As ModelDoc2
Sub main()
' get the solidworks application object
Set swApp = Application.SldWorks
'get the current opened document object
Set swModel = swApp.ActiveDoc
' get the modeldocextension object
Dim swModelExtension As ModelDocExtension
Set swModelExtension = swModel.Extension
Dim lRet As Long
lRet = swModelExtension.RenameDocument("NEW NAME")
If lRet = swRenameDocumentError_e.swRenameDocumentError_None Then
MsgBox "success renaming"
Else
MsgBox "failed with error: " & lRet
End If
End Sub
Afterwars you have to process the return value to check for errors described in this article: https://help.solidworks.com/2020/English/api/swconst/SolidWorks.Interop.swconst~SolidWorks.Interop.swconst.swRenameDocumentError_e.html

How to find and disable a content control by tag to delete it and its contents?

I have the unfortunate task of being forced to design a Word-based electronic production card for the unit at my company, even though I've never worked with VBA. I would much rather have done this in Excel since I wouldn't have to wrestle with content control and hard-to-find locations in various tables over the pages, but the company's documentation-system forces this particular one to be in Word.
My issue is that for proper form of the production card I need to use tables, and I need the production card to be dynamic to limit its size to what operations that are relevant for a specific order. My chosen solution is to create a full form, and to use a user form/prompt where they can choose which parts to use and which parts to ommit, and the ommitted ones will then be deleted. Part of reason for the solution is because that is how their previous (and Excel-based) production card works, so it would make it more familiar for the end user.
Because MS Word is finicky I need to use content control within these tables to not have the end user accidentally destroy half of it, but after a full workday I still cannot figure out how find and shut off the content control of the cells in tables that I want to delete. I do have the content controls tagged since that seems like the only reasonable way to find them.
This is my current code for the subprocedure, but for some reason I cannot get the ID through the ccID line, even though I have verified that the string supplied as argument is correct.
Private Sub DeleteCCByTag(ccTag As String)
Dim cc As ContentControl
Dim ccID As String
ccID = ThisDocument.SelectContentControlsByTag(ccTag).Item(1).ID
'MsgBox ccID 'Debug prompt
Set cc = ThisDocument.ContentControls(ccID)
cc.LockContentControl = False
cc.LockContents = False
cc.Delete (False)
End Sub
First of all- your code is working find for me but...
ContentControls tag is case-sensitive which could be a problem in your situation
You could solve your problem without searching for ID value in this way:
Private Sub DeleteCCByTag_Alternative(ccTag As String)
Dim cc As ContentControl
Set cc = ThisDocument.SelectContentControlsByTag(ccTag).Item(1)
With cc
.LockContentControl = False
.LockContents = False
.Range.Delete 'to delete CC content
.Delete (False)
End With
End Sub
CC.Delete in your code deletes only ContentControl objects itself but not its content. To delete content you need to add additional line which I did in my code above.
I would add this as a comment to KazJaw's answer but I don't have the rep.
According to Microsoft's documentation, if you pass True to the Delete method it removes both the content control and its contents.
So: just get the Item as KazJaw showed, without jumping through the hoop of getting its ID:
Set cc = ThisDocument.SelectContentControlsByTag(ccTag).Item(1)
then call .Delete(True) on it.

Get the number of pages in a Word document

I am making lots of changes to a Word document using automation, and then running a VBA macro which - among other things - checks that the document is no more than a certain number of pages.
I'm using ActiveDocument.Information(wdNumberOfPagesInDocument) to get the number of pages, but this method is returning an incorrect result. I think this is because Word has not yet updated the pagination of the document to reflect the changes that I've made.
ActiveDocument.ComputeStatistics(wdStatisticPages) also suffers from the same issue.
I've tried sticking in a call to ActiveDocument.Repaginate, but that makes no difference.
I did have some luck with adding a paragraph to the end of the document and then deleting it again - but that hack seems to no longer work (I've recently moved from Word 2003 to Word 2010).
Is there any way I can force Word to actually repaginate, and/or wait until the repagination is complete?
I just spent a good 2 hours trying to solve this, and I have yet to see this answer on any forum so I thought I would share it.
https://msdn.microsoft.com/en-us/vba/word-vba/articles/pages-object-word?f=255&MSPPError=-2147217396
That gave me my solution combined with combing through the articles to find that most of the solutions people reference are not supported in the newest versions of Word. I don't know what version it changed in, but my assumption is that 2013 and newer can use this code to count pages:
ActiveDocument.ActiveWindow.Panes(1).Pages.Count.
I believe the way this works is ActiveDocument selects the file, ActiveWindow confirms that the file to be used is in the current window (in case the file is open in multiple windows from the view tab), Panes determines that if there is multiple windows/split panes/any other nonsense you want the "first" one to be evaluated, pages.count designates the pages object to be evaluated by counting the number of items in the collection.
Anyone more knowledgeable feel free to correct me, but this is the first method that gave me the correct page count on any document I tried!
Also I apologize but I cant figure out how to format that line into a code block. If the mods want to edit my comment to do that be my guest.
Try (maybe after ActiveDocument.Repaginate)
ActiveDocument.BuiltinDocumentProperties(wdPropertyPages)
It is causing my Word 2010 to spend half-second with "Counting words" status in status bar, while ActiveDocument.ComputeStatistics(wdStatisticPages) returns the result immediately.
Source: https://support.microsoft.com/en-us/kb/185509
After you've made all your changes, you can use OnTime to force a slight delay before reading the page statistics.
Application.OnTime When:=Now + TimeValue("00:00:02"), _
Name:="UpdateStats"
I would also update all the fields before this OnTime statement:
ActiveDocument.Range.Fields.Update
I found a possible workaround below, if not a real answer to the topic question.
Yesterday, the first ComputeStatistics line below was returning the correct total of 31 pages, but today it returns only 1.
The solution is to get rid of the Content object and the correct number of pages is returned.
Dim docMultiple As Document
Set docMultiple = ActiveDocument
lPageCount = docMultiple.Content.ComputeStatistics(wdStatisticPages) ' Returns 1
lPageCount = docMultiple.ComputeStatistics(wdStatisticPages) ' Returns correct count, 31
ActiveDocument.Range.Information(wdNumberOfPagesInDocument)
This works every time for me. It returns total physical pages in the word.
I used this from within Excel
it worked reliably on about 20 documents
none were longer than 20 pages but some were quite complex
with images and page breaks etc.
Sub GetlastPageFromInsideExcel()
Set wD = CreateObject("Word.Application")
Set myDoc = wD.Documents.Open("C:\Temp\mydocument.docx")
myDoc.Characters.Last.Select ' move to end of document
wD.Selection.Collapse ' collapse selection at end
lastPage = wD.Selection.Information(wdActiveEndPageNumber)
mydoc.close
wd.quit
Set wD = Nothing
End Sub
One problem I had in getting "ComputeStatistics" to return a correct page count was that I often work in "Web Layout" view in Word. Whenever you start Word it reverts to the last view mode used. If Word was left in "Web Layout" mode "ComputeStatistics" returned a page count of "1" page for all files processed by the script. Once I specifically set "Print Layout" view I got the correct page counts.
For example:
$MSWord.activewindow.view.type = 3 # 3 is 'wdPrintView', 6 is 'wdWebView'
$Pages = $mydoc.ComputeStatistics(2) # 2 is 'wdStatisticPages'
You can use Pages-Object and its properties such as Count. It works perfect;)
Dim objPages As Pages
Set objPage = ActiveDocument.ActiveWindow.Panes(1).Pages
QuantityOfPages = ActiveDocument.ActiveWindow.Panes(1).Pages.Count
Dim wordapp As Object
Set wordapp = CreateObject("Word.Application")
Dim doc As Object
Set doc = wordapp.Documents.Open(oFile.Path)
Dim pagesCount As Integer
pagesCount = doc.Content.Information(4) 'wdNumberOfPagesInDocument
doc.Close False
Set doc = Nothing

How do I use Google.GData.Client.AtomLinkCollection.FindService method to get the list of worksheets in a Google Spreadsheet?

I'm trying to write code that talks to Google Spreadsheets. We do a bunch of processing on our end and then pass data out to our client into this spreadsheet and I want to automate it. This seems like it should be easy.
On this page, Google says "Given a SpreadsheetEntry you've already retrieved, you can print a list of all worksheets in this spreadsheet as follows:"
AtomLink link = entry.Links.FindService(GDataSpreadsheetsNameTable.WorksheetRel, null);
WorksheetQuery query = new WorksheetQuery(link.HRef.ToString());
WorksheetFeed feed = service.Query(query);
foreach (WorksheetEntry worksheet in feed.Entries)
{
Console.WriteLine(worksheet.Title.Text);
}
Following along at home, I start with:
Dim link As AtomLink = Entry.Links.FindService(GDataSpreadsheetsNameTable.WorksheetRel, "")
Dim wsq As New WorksheetQuery(link.HRef.ToString)
and when execution gets to that second line, I find that "Object reference not set to instance of an object." The FindService method is returning nothing. And when I look at GDataSpreadsheetsNameTable.WorksheetRel, it's a constant value of "http://schemas.google.com/spreadsheets/2006#worksheetsfeed"
I'm not really at the point where I even grok what it wants to be doing. E.g., what's a feed? Is a worksheet really what I think it is based on Excel nomenclature? That kind of stuff. But I see a couple of things that might be causing my issue:
The C# method call "...FindService(GDataSpreadsheetsNameTable.WorksheetRel, null);" I'm not sure about that null. It demands a string, so I used "" in my VB, but I'm not sure that's right.
That schemas.google.com URI doesn't seem to be live. At least, if I punch it into a browser, I get server not found. But again, I don't exactly know what it's trying to do.
So, any thoughts? Anyone have VB code that reads Google Spreadsheets and time to instruct a newbie? I'm surprised to find that there's essentially no useful sample code floating around the net.
Thanks for reading!
So, of course, right after I posted this I found some inspiration over here. Manually iterating across the collections works just fine, even if it's not the preferred way to do this. I'm still keen to hear info from others related to this, so feel encouraged to help out even though I'm maybe over this one hurdle.
For Each Entry In mySprShFeed.Entries
If Entry.Title.Text = "spreadsheetNameSought" Then
For Each link As AtomLink In Entry.Links
If link.Rel = GDataSpreadsheetsNameTable.WorksheetRel Then
Dim wsf As WorksheetFeed = service.Query(New WorksheetQuery(link.HRef.ToString))
For Each worksheet In wsf.Entries
Console.WriteLine(worksheet.Title.Text)
Next
End If
Next
End If
Next