VB is slower than VBA. Why?

L

liu_jz

I wrote a program in VBA. It took about 4s. I wrote this program in VB.
It took 60s. Is VB slower than VBA? Why? How to improve the performance
in VB?

The source code as follows:

Dim gwdApp As Word.Application
Dim gwdDoc As Word.Document
Dim wdRange() As Word.Range
Dim wdField As Word.Field
Dim i As Long
Dim j As Integer
Dim lngRecordCnt As Long
Dim lngFieldCnt As Long
Dim lngRangeStart As Long
Dim lngStep As Long
Dim strFieldName() As String
Dim vntFieldValue() As Variant

.......
For i = 0 To lngRecordCnt - 1
......
wdRange.Copy
Selection.SetRange lngRangeStart, lngRangeStart
'VB gwdApp.Selection.SetRange lngRangeStart, lngRangeStart
Selection.Paste
'VB gwdApp.Selection.Paste
gwdDoc.Bookmarks(strBookmarkName).Delete
Call gwdDoc.Bookmarks.Add(strBookmarkName, gwdDoc.Range(lngRangeStart,
lngStep + lngRangeStart))
For j = 0 To lngFieldCnt - 1
If blnGetFieldByName(gwdDoc.Bookmarks(strBookmarkName).Range,
strFieldName(j), wdField) Then
wdField.Result.Text = vntFieldValue(j)
wdField.Unlink
End If
Next j
......
Next i
 
J

Jezebel

In general, VB is faster. In this case, the bottleneck is the inter-process
communication between VB and Word. You will likely get some improvements if
you a) avoid using the Selection object, and b) use With ... End With
constructions to "minimise the dots". With-End With assists with the
inter-process marshalling and reduces the overhead.
 
L

liu_jz

Jezebel,

I changed the program not to use Selection object. It took 15s. Thanks!

wdRange.Copy
gwdDoc.Range(lngRangeStart, lngRangeStart).Paste
 
L

liu_jz

Another question:
It is very slow when I run this VB program first time. And then it is
fast. Why?
 
J

Jonathan West

Another question:
It is very slow when I run this VB program first time. And then it is
fast. Why?

That is probably because the first time Word has to be loaded. The second
time, Word is already open and your program links to that already-open copy
of Word.

--
Regards
Jonathan West - Word MVP
www.intelligentdocuments.co.uk
Please reply to the newsgroup
Keep your VBA code safe, sign the ClassicVB petition www.classicvb.org
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Top