vb versus vbawhen do i use which tool? cp33-3 presented by

12
VB Versus VBA...When Do I Use Which Tool? Autodesk University 2003— Jerry Winters Pg. 1 CP33-3 VB Versus VBA...When Do I Use Which Tool? CP33-3 Presented by Jerry Winters About this Class Visual Basic is a language used in Visual Basic 6 as well as in VBA. So, if you know Visual Basic, does it really matter which tool you use? Actually, yes. We will explore the differences between using these development environments, when to use which tool, and when to use both tools for a single application. About the Instructor Jerry Winters has been using AutoCAD since 1988. He has written several books on programming AutoCAD with VBA and will be releasing his AutoCAD 2004 VBA book soon. Jerry provides VBA training as well as customization services for customers all over the United States as well as other countries on Earth. He has yet to teach on other planets in the solar system but is not counting out the possibility in the future. This is his second year teaching at Autodesk University. Had his 5th son, Nathan not been born the night before AU 2001, this would have been his third year. His first daughter, Olivia was born October 28th, 2003, so he is very happy to be here this year. He has been happily married for 12 years. If you are counting, that makes 5 sons, 1 daughter, and 1 wife. Also, 8 chickens, 1 cat, 1 turkey named Thanksgiving (he isn’ t feeling very well) and 1 turkey named Christmas (she is very cold right now). Jerry and his 3 oldest sons hold Tae Kwon Do Black Belts. To contact Jerry, please email him at [email protected] or visit his website: www.vbcad.com

Upload: others

Post on 16-Apr-2022

7 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: VB Versus VBAWhen Do I Use Which Tool? CP33-3 Presented by

V B V e r s u s V B A . . . W h e n D o I U s e W h i c h T o o l ? A u t o d e s k U n i v e r s i t y 2 0 0 3 — J e r r y W i n t e r s

Pg. 1 CP33-3

VB Versus VBA...When Do I Use Which Tool? CP33-3

Presented by Jerry Winters About this Class Visual Basic is a language used in Visual Basic 6 as well as in VBA. So, if you know Visual Basic, does it really matter which tool you use? Actually, yes. We will explore the differences between using these development environments, when to use which tool, and when to use both tools for a single application. About the Instructor Jerry Winters has been using AutoCAD since 1988. He has written several books on programming AutoCAD with VBA and will be releasing his AutoCAD 2004 VBA book soon. Jerry provides VBA training as well as customization services for customers all over the United States as well as other countries on Earth. He has yet to teach on other planets in the solar system but is not counting out the possibility in the future. This is his second year teaching at Autodesk University. Had his 5th son, Nathan not been born the night before AU 2001, this would have been his third year. His first daughter, Olivia was born October 28th, 2003, so he is very happy to be here this year. He has been happily married for 12 years. If you are counting, that makes 5 sons, 1 daughter, and 1 wife. Also, 8 chickens, 1 cat, 1 turkey named Thanksgiving (he isn’t feeling very well) and 1 turkey named Christmas (she is very cold right now). Jerry and his 3 oldest sons hold Tae Kwon Do Black Belts. To contact Jerry, please email him at [email protected] or visit his website: www.vbcad.com

Page 2: VB Versus VBAWhen Do I Use Which Tool? CP33-3 Presented by

V B V e r s u s V B A . . . W h e n D o I U s e W h i c h T o o l ? A u t o d e s k U n i v e r s i t y 2 0 0 3 — J e r r y W i n t e r s

Pg. 2 CP33-3

Performance— Drawing Exactly what does that mean? When talking performance, make sure you are talking apples to apples.

Sub DrawStringArt() '** The following lines are for VB6 Only. ' Dim MyAcad As AcadApplication ' Set MyAcad = GetObject(, "AutoCAD.Application") ' Dim ThisDrawing As AcadDocument ' Set ThisDrawing = MyAcad.ActiveDocument Dim NumOfPoints As Long Dim LineSt(0 To 2) As Double Dim LineEnd(0 To 2) As Double Dim MyLine As AcadLine Dim X As Long Dim stTime As Double Dim enTime As Double stTime = Timer NumOfPoints = 500 For NumOfPoints = NumOfPoints To 100 Step -100 For X = 1 To NumOfPoints - 1 LineSt(0) = X LineSt(1) = 0 LineEnd(0) = 0 LineEnd(1) = NumOfPoints - X Set MyLine = ThisDrawing.ModelSpace.AddLine(LineSt, LineEnd) MyLine.color = NumOfPoints / 100 LineSt(0) = X LineSt(1) = NumOfPoints LineEnd(0) = 0 LineEnd(1) = X Set MyLine = ThisDrawing.ModelSpace.AddLine(LineSt, LineEnd) MyLine.color = NumOfPoints / 100 LineSt(0) = X LineSt(1) = NumOfPoints LineEnd(0) = NumOfPoints LineEnd(1) = NumOfPoints - X Set MyLine = ThisDrawing.ModelSpace.AddLine(LineSt, LineEnd) MyLine.color = NumOfPoints / 100 LineSt(0) = X LineSt(1) = 0 LineEnd(0) = NumOfPoints LineEnd(1) = X Set MyLine = ThisDrawing.ModelSpace.AddLine(LineSt, LineEnd) MyLine.color = NumOfPoints / 100 Next X Next NumOfPoints enTime = Timer MsgBox enTime - stTime & " seconds to draw string art." End Sub

Page 3: VB Versus VBAWhen Do I Use Which Tool? CP33-3 Presented by

V B V e r s u s V B A . . . W h e n D o I U s e W h i c h T o o l ? A u t o d e s k U n i v e r s i t y 2 0 0 3 — J e r r y W i n t e r s

Pg. 3 CP33-3

Below is a sample of what we are drawing when we run the ‘macro’ “DrawStringArt”.

When we run the actual code, a total of 5,980 lines are drawn. Now for the performance comparison. The message box with “AutoCAD” in the caption is VBA. “StringArt” is VB6 in design mode.

When our VB6 application is compiled, we get a slight boost in performance. So, in the drawing category, it looks like VBA is a clear winner. It is 18.6 times faster than VB6. Of course, we are talking about a difference of only 62 seconds

in this instance, but multiply the numbers out and you will find that when it comes to this drawing example, you can accomplish a task in 2.15 hours using VBA where it would take 40 hours in VB. I vote for the 2.15 hours and taking the rest of the week off.

Page 4: VB Versus VBAWhen Do I Use Which Tool? CP33-3 Presented by

V B V e r s u s V B A . . . W h e n D o I U s e W h i c h T o o l ? A u t o d e s k U n i v e r s i t y 2 0 0 3 — J e r r y W i n t e r s

Pg. 4 CP33-3

Performance— Querying the Drawing OK. So perhaps VB is not the best tool if all you are doing is drawing entities on the screen. How about querying the drawing for data?

Sub DrawCircles() Dim I As Long Dim CirDia As Double Dim CenPt(0 To 2) As Double Randomize For I = 1 To 1000 ThisDrawing.ModelSpace.AddCircle CenPt, 10 * Rnd Next I End Sub Sub GetAvgDia() '** The following lines are for VB6 Only. ' Dim MyAcad As AcadApplication ' Set MyAcad = GetObject(, "AutoCAD.Application") ' Dim ThisDrawing As AcadDocument ' Set ThisDrawing = MyAcad.ActiveDocument Dim MySS As AcadSelectionSet Dim GrpC(0) As Integer Dim GrpV(0) As Variant Dim MyCircle As AcadCircle Dim CircleTot As Double Dim tStart As Double Dim tEnd As Double tStart = Timer GrpC(0) = 0 GrpV(0) = "CIRCLE" Set MySS = ThisDrawing.SelectionSets.Add("AvgDia") MySS.Select acSelectionSetAll, , , GrpC, GrpV For Each MyCircle In MySS CircleTot = CircleTot + MyCircle.Diameter Next tEnd = Timer MsgBox "Average Diameter: " & CircleTot / MySS.Count & vbCr & _ tEnd - tStart & " seconds." MySS.Delete End Sub

If you don’t look closely enough, it may appear that VB is getting closer to VBA when it comes to querying the drawing. However, the VBA time is multiplied by 10-2. The actual result? VBA is nearly 144 times faster than VB. This means that you could work for approx. 15 minutes in VBA and accomplish the same amount of querying work that can be accomplished in 40 hours with VB6.

Page 5: VB Versus VBAWhen Do I Use Which Tool? CP33-3 Presented by

V B V e r s u s V B A . . . W h e n D o I U s e W h i c h T o o l ? A u t o d e s k U n i v e r s i t y 2 0 0 3 — J e r r y W i n t e r s

Pg. 5 CP33-3

Performance— Number Crunching

Sub NumberCrunch() Dim MyAvg As Double Dim I As Double Dim tStart As Double Dim tEnd As Double tStart = Timer Dim NumOfCalcs As Long NumOfCalcs = 10000000 For I = 1 To NumOfCalcs MyAvg = (MyAvg + Rnd * 10) / 2 Next I tEnd = Timer MsgBox tEnd - tStart & " seconds for " & _ NumOfCalcs & " calculations." End Sub

VBA with 1,000,000 calculations and 10,000,000 calcs.

VB Edit Mode VB Compiled

VB redeems itself a little when it comes to number crunching. We are performing a simple calculation a bunch of times. In the left column, we are doing it 1,000,000 times and in the right column, 10,000,000 times. In this number crunching test, we find that VB is 1.2 times faster than VBA.

Page 6: VB Versus VBAWhen Do I Use Which Tool? CP33-3 Presented by

V B V e r s u s V B A . . . W h e n D o I U s e W h i c h T o o l ? A u t o d e s k U n i v e r s i t y 2 0 0 3 — J e r r y W i n t e r s

Pg. 6 CP33-3

Performance— FileSystemObject

Private Sub CommandButton1_Click() Dim MyFSO As New Scripting.FileSystemObject Dim MyFolder As Folder Dim MyFile As File Dim FolderName As String Dim tStart As Double Dim tEnd As Double tStart = Timer FolderName = "c:\winnt\system32" Set MyFolder = MyFSO.GetFolder(FolderName) For Each MyFile In MyFolder.Files ListBox1.AddItem MyFile.Name Next tEnd = Timer MsgBox "FSO: " & tEnd - tStart & " seconds." & vbCr & _ ListBox1.ListCount & " files found in " & FolderName End Sub

In this example, we are using FileSystemObject to get all of the files in a specified directory and put their names in a list box. Make sure you add a reference to Microsoft Scripting Runtime. This is necessary for FSO to work.

VBA VB Edit Mode VB Compiled VB Compiled is 1.26 times faster than VBA.

Page 7: VB Versus VBAWhen Do I Use Which Tool? CP33-3 Presented by

V B V e r s u s V B A . . . W h e n D o I U s e W h i c h T o o l ? A u t o d e s k U n i v e r s i t y 2 0 0 3 — J e r r y W i n t e r s

Pg. 7 CP33-3

Performance-Using the Right Tool No, we are not talking about the right tool between VBA and VB. We are talking about the right code tool.

In a previous example, we used FSO to get the file names in the c:\winnt\system32 directory. In this example, we are getting not only the filename but also the file size, date, and file type. This example is in VBA.

If we only get the file name as we had done in the previous example, we see an even greater difference in the performance between using the Windows API and the File System Object. The API is 15 times faster than FSO in this example. Of course, using FSO requires a very small amount of code. The following couple of pages will display the code necessary for each method.

Page 8: VB Versus VBAWhen Do I Use Which Tool? CP33-3 Presented by

V B V e r s u s V B A . . . W h e n D o I U s e W h i c h T o o l ? A u t o d e s k U n i v e r s i t y 2 0 0 3 — J e r r y W i n t e r s

Pg. 8 CP33-3

FSO Code

Private Sub CommandButton2_Click() Dim tstart As Single Dim tend As Single Dim fso As FileSystemObject Dim path As String Set fso = New FileSystemObject ListView2.ListItems.Clear tstart = Timer AddFiles fso.GetFolder("c:\winnt\system32"), ListView2 tend = Timer TextBox3.Text = ListView2.ListItems.Count & " files found" TextBox4.Text = Round(tend - tstart, 6) & " seconds" End Sub Private Sub AddFiles(fn As folder, lv As ListView) Dim fi As File Dim itmX As ListItem With lv For Each fi In fn.Files Set itmX = .ListItems.Add(, , fi.Name) itmX.SubItems(1) = fi.Size itmX.SubItems(2) = fi.DateLastModified itmX.SubItems(3) = fi.Type Next fi End With End Sub

API Code Private Const MAX_PATH As Long = 260 Private Const INVALID_HANDLE_VALUE = -1 Private Const FILE_ATTRIBUTE_DIRECTORY As Long = &H10 Private Const SHGFI_TYPENAME As Long = &H400 Private Type SHFILEINFO hIcon As Long iIcon As Long dwAttributes As Long szDisplayName As String * MAX_PATH szTypeName As String * 80 End Type Private Type SYSTEMTIME wYear As Integer wMonth As Integer wDayOfWeek As Integer wDay As Integer wHour As Integer wMinute As Integer wSecond As Integer wMilliseconds As Integer End Type Private Type FILETIME dwLowDateTime As Long dwHighDateTime As Long End Type Private Type WIN32_FIND_DATA dwFileAttributes As Long

Page 9: VB Versus VBAWhen Do I Use Which Tool? CP33-3 Presented by

V B V e r s u s V B A . . . W h e n D o I U s e W h i c h T o o l ? A u t o d e s k U n i v e r s i t y 2 0 0 3 — J e r r y W i n t e r s

Pg. 9 CP33-3

ftCreationTime As FILETIME ftLastAccessTime As FILETIME ftLastWriteTime As FILETIME nFileSizeHigh As Long nFileSizeLow As Long dwReserved0 As Long dwReserved1 As Long cFileName As String * MAX_PATH cAlternate As String * 14 End Type Private Type FILE_PARAMS fAtributes As Long sFileRoot As String sFileNameExt As String End Type Private Declare Function FindClose Lib "kernel32" (ByVal hFindFile As Long) As Long Private Declare Function FindFirstFile Lib "kernel32" Alias "FindFirstFileA" _ (ByVal lpFileName As String, lpFindFileData As WIN32_FIND_DATA) As Long Private Declare Function FindNextFile Lib "kernel32" Alias "FindNextFileA" _ (ByVal hFindFile As Long, lpFindFileData As WIN32_FIND_DATA) As Long Private Declare Function FileTimeToLocalFileTime Lib "kernel32" _ (lpFileTime As FILETIME, lpLocalFileTime As FILETIME) As Long Private Declare Function FileTimeToSystemTime Lib "kernel32" _ (lpFileTime As FILETIME, lpSystemTime As SYSTEMTIME) As Long Private Declare Function SystemTimeToVariantTime Lib "oleaut32" _ (psystime As SYSTEMTIME, pvtime As Double) As Long Private Declare Function StrFormatByteSizeW Lib "SHLWAPI" _ (ByVal qdwLow As Long, ByVal qdwHigh As Long, pwszBuf As Any, ByVal cchBuf As Long) As Long Private Declare Function ShGetFileInfo Lib "shell32" Alias "SHGetFileInfoA" _ (ByVal pszPath As String, ByVal dwFileAttributes As Long, psfi As SHFILEINFO, _ ByVal cbSizeFileInfo As Long, ByVal uFlags As Long) As Long Private Sub CommandButton1_Click() Dim tstart As Double Dim tend As Double Dim FP As FILE_PARAMS ListView1.ListItems.Clear tstart = Timer With FP .sFileRoot = "c:\winnt\system32" .sFileNameExt = "*.*" End With Call GetFileInformation(FP) tend = Timer TextBox1.Text = ListView1.ListItems.Count & " files found" TextBox2.Text = Round(tend - tstart, 6) & " seconds" End Sub Private Sub UserForm_Initialize() CommandButton1.Caption = "API - Non-recursive" CommandButton2.Caption = "FileSystemObject" With ListView1 .ColumnHeaders.Add , , "Filename" .ColumnHeaders.Add , , "Size" .ColumnHeaders.Add , , "Date" .ColumnHeaders.Add , , "Type" .View = lvwReport .Sorted = False End With With ListView2

Page 10: VB Versus VBAWhen Do I Use Which Tool? CP33-3 Presented by

V B V e r s u s V B A . . . W h e n D o I U s e W h i c h T o o l ? A u t o d e s k U n i v e r s i t y 2 0 0 3 — J e r r y W i n t e r s

Pg. 10 CP33-3

.ColumnHeaders.Add , , "Filename" .ColumnHeaders.Add , , "Size" .ColumnHeaders.Add , , "Date" .ColumnHeaders.Add , , "Type" .View = lvwReport .Sorted = False End With End Sub Private Function GetFileType(sFileName As String) As String Dim shinfo As SHFILEINFO Call ShGetFileInfo(sFileName, 0&, shinfo, Len(shinfo), SHGFI_TYPENAME) GetFileType = shinfo.szTypeName End Function Private Function GetFileDate(CT As FILETIME) As String Dim st As SYSTEMTIME If FileTimeToSystemTime(CT, st) Then GetFileDate = Format$(DateSerial(st.wYear, st.wMonth, st.wDay), _ "Short Date") Else GetFileDate = "" End If End Function Private Function FileTimeToVBDate(ftFile As FILETIME) As Date Dim ftLocal As FILETIME Dim st As SYSTEMTIME Dim dbl As Double Call FileTimeToLocalFileTime(ftFile, ftLocal) Call FileTimeToSystemTime(ftLocal, st) Call SystemTimeToVariantTime(st, dbl) FileTimeToVBDate = dbl End Function Private Sub GetFileInformation(FP As FILE_PARAMS) Dim WFD As WIN32_FIND_DATA Dim hFile As Long Dim sPath As String Dim sRoot As String Dim itmX As ListItem Dim lv As ListView Dim sSize As String Set lv = ListView1 sRoot = QualifyPath(FP.sFileRoot) sPath = sRoot & FP.sFileNameExt hFile = FindFirstFile(sPath, WFD) If hFile <> INVALID_HANDLE_VALUE Then With lv Do If (WFD.dwFileAttributes And vbDirectory) = 0 Then Set itmX = .ListItems.Add(, , WFD.cFileName) sSize = Space$(30) Call StrFormatByteSizeW(WFD.nFileSizeLow, _ WFD.nFileSizeHigh, ByVal StrPtr(sSize), 30) itmX.SubItems(1) = sSize itmX.SubItems(2) = FileTimeToVBDate(WFD.ftLastWriteTime) itmX.SubItems(3) = GetFileType(sRoot & WFD.cFileName) End If Loop While FindNextFile(hFile, WFD) End With hFile = FindClose(hFile) End If End Sub

Page 11: VB Versus VBAWhen Do I Use Which Tool? CP33-3 Presented by

V B V e r s u s V B A . . . W h e n D o I U s e W h i c h T o o l ? A u t o d e s k U n i v e r s i t y 2 0 0 3 — J e r r y W i n t e r s

Pg. 11 CP33-3

Private Function QualifyPath(sPath As String) As String If Right$(sPath, 1) <> "\" Then QualifyPath = sPath & "\" Else QualifyPath = sPath End If End Function So, the code you choose to use can have a significant impact on the performance of your application. The API example here takes a great deal more code to accomplish the task but is much faster. So, enter your code once and re-use it again and again.

Page 12: VB Versus VBAWhen Do I Use Which Tool? CP33-3 Presented by

V B V e r s u s V B A . . . W h e n D o I U s e W h i c h T o o l ? A u t o d e s k U n i v e r s i t y 2 0 0 3 — J e r r y W i n t e r s

Pg. 12 CP33-3

Other VBA / VB Issues to Consider I imagine I could write a book on the subject because there is so much to consider here. It would take hundreds of pages to explain all of the issues and that is not practical in this forum. So, I will list the items we will discuss here and you can take notes as we discuss and show examples of the issues discussed. If you didn’t attend AU, I hope to see you next year and you can get the details on all of these items. ? Development speed ? End use of application— 1 time use or multiple uses, 1 user or many, OS issues on multiple machines ? Code re-use ? VBA procedure execution ? Debugging— step through procedures independent of entry point ? VBA debugging on foreign machine— have user step through code ? Application distribution ? Dealing with different versions of AutoCAD ? Password protection (VBA) versus compilation (VB) ? Native controls available for use ? Native control differences ? DLL / Active X control creation in VB for use in VBA ? Native Tools— AddIn Manager (API Viewer) ? VBA bloating ? GetObject / CreateObject ? Multiple instances of AutoCAD running ? Portability (using DLL created in VB in AutoCAD or Excel or Word or … ..) ? VBA— 1 file solution, VB— many referenced files solution ? Is AutoCAD functionality primary? Will users that don’t have AutoCAD want to use your application? ? Modeless vs Modal dialog boxes (Must see to understand) ? Is AutoCAD running? ? VB— Program, VBA 0 Macros ? Application launch options ? Registry writing native to VB6 As you can see, there are a huge variety of issues that can be considered when deciding on which development environment to use. VB has it’s strengths. VBA has it’s strengths. At times, VB will be the winner, other times, VBA the winner, and other times, you may choose to use VB and VBA for a single application. I hope the information presented here has been instructive as well as entertaining. If you have questions, feel free to email me at [email protected] or visit my website at www.vbcad.com Thanks! Jerry Winters President, VB CAD