While experimenting with some new code, I pinpointed a particular procedure that was causing a bottleneck. On a 30-page document with about 500 paragraphs, it was taking nearly 10 seconds to run.
After trying all manner of things to figure out what the cause of the delay was, I’m stuck. The problem isn’t that the code is slow — it actually isn’t. Running the Sub directly from the IDE, or directly from the Macros (Alt-F8) dialog results in completely acceptable performance for my purposes (about 1 sec). The problem is that whenever the Sub is run (it’s actually a function that’s part of a bunch of other stuff, but that’s not important) from a keybinding or from a toolbar button, it slows .. way … down.
I’d be interested in finding out if (a). anyone can reproduce this given the code below, and (. if anyone has any ideas what’s going on and how to address it.
Sub BuildParaDataTable() Dim doc As Document Set doc = ActiveDocument Dim k As Long Dim j As Long Dim para As Paragraph Dim vData() As Variant Dim col As Collection ReDim vData(1 To doc.Paragraphs.Count) k = 1 For Each para In doc.Paragraphs Set col = New Collection With col .Add Key:="index", Item:=k .Add Key:="text", Item:=Left(para.Range.Text, para.Range.Characters.Count - 1) ' The following line is the slow one (see below)'---- .Add Key:="style", Item:=Split(para.Style.NameLocal, ",")(0) '<-- .Add Key:="para", Item:=para .Add Key:="ofstyleindex", Item:=1 End With For j = k - 1 To 1 Step -1 If vData(j)("style") = col("style") Then ' Do some other stuff Exit For End If Next j Set vData(k) = col Set col = Nothing k = k + 1 Next para MsgBox vData(10)("index") 'BuildParaDataTable = vData End Sub
The only line that seems to have any significant effect on the performance is the one I’ve noted in the code itself. I first suspected that maybe it was the repeated Split() calls, but if I change the line to the following, it’s not any faster:
.Add Key:="style", Item:=para.Style.NameLocal
I would be willing to accept that this particular experimental code was just inefficient, but it’s killing me that it’s only slow when I run it from a toolbar or a keybinding (or from another macro that’s called in one of those two ways). Hoping another Lounger might be able to provide some insight.
I’ve provided a sample document that illustrates the behavior nicely if you run this macro on it.
Any suggestions are welcome and appreciated.