Содержание
- Autocad не работает vba
- Приложение AutoCAD VBA и особенности работы с ним
- Не работает VBA в Civil 3d 2013
- AutoCAD
- Проблема
- Решение
Autocad не работает vba
- Отметить как новое
- Закладка
- Подписаться
- Отключить
- Подписка на RSS-канал
- Выделить
- Печать
- Отчет
Не запускается макрос VBA для Autocad 2015. Хотя в версии Autocad 2010 все работает, работает также и в Autocad 2008. Запуск макроса осуществляется: Загрузить проект — Запустить макрос VBA. Появляется фатальная ошибка: Unhandled Access Violation Writing 0xbda53ac Exception at bda53ach и вылетает Автокад. Возможно, макрос vba не адаптирован под новую версию автокада. Как запустить макрос vba в Autocad 2015?
- Отметить как новое
- Закладка
- Подписаться
- Отключить
- Подписка на RSS-канал
- Выделить
- Печать
- Отчет
Не запускается макрос VBA для Autocad 2015. Хотя в версии Autocad 2010 все работает, работает также и в Autocad 2008. Запуск макроса осуществляется: Загрузить проект — Запустить макрос VBA. Появляется фатальная ошибка: Unhandled Access Violation Writing 0xbda53ac Exception at bda53ach и вылетает Автокад. Возможно, макрос vba не адаптирован под новую версию автокада. Как запустить макрос vba в Autocad 2015?
3. Если макрос не адаптирован, то вероятно он не будет работать. Так что обращайтесь к разработчику макроса.
Находите сообщения полезными? Поставьте «НРАВИТСЯ» этим сообщениям! | Do you find the posts helpful? «LIKE» these posts!
На ваш вопрос успешно ответили? Нажмите кнопку » УТВЕРДИТЬ РЕШЕНИЕ » | Have your question been answered successfully? Click «ACCEPT SOLUTION» button.
Alexander Rivilis / Александр Ривилис
Programmer & Teacher & Helper / Программист — Учитель — Помощник
Facebook | Twitter | LinkedIn
Источник
Приложение AutoCAD VBA и особенности работы с ним
Visual Basic for Applications (VBA) — это язык программирования, встроенный во многие приложения, включая офисные программы, САПР, графические редакторы и многие другие. VBA является упрощенной версией языка Visual Basic, имеет схожий с ним синтаксис. Среда программирования VBA обычно встроена в саму программу, поэтому пользователь может сразу начинать писать программы или загружать готовые приложения для работы.
При разработке языка VBA его авторы ориентировались на обычных пользователей, а не на профессиональных программистов, поэтому создавать программы на VBA достаточно просто и быстро.
Из преимуществ языка VBA можно отметить легкость его освоения и простоту использования, универсальность (изучив VBA для AutoCAD пользователь без труда изучит, например, VBA для Microsoft Word или Excel). Главный недостаток языка VBA – проблемы с обратной совместимостью разных версий.
В AutoCAD также есть встроенная поддержка языка VBA, для этого служит отдельный модуль AutoCAD VBA Enabler. С помощью программ на VBA можно обращаться ко всем объектам AutoCAD, примитивам чертежа, общаться между AutoCAD и сторонними приложениями и многое другое. Другими словами, с помощью языка VBA можно создавать программы любой сложности, которые позволят расширить функциональность системы, автоматизировать рутинные операции и многое другое.
Важным отличием VBA для AutoCAD от VBA для других программ является то, что в нем программы хранятся не внутри файлов, а во внешних файлах с расширением DVB.
В последних версиях AutoCAD модуль VBA Enabler не входит в дистрибутив и не устанавливается вместе с самим AutoCAD. Чтобы получить возможность работать с VBA в AutoCAD, вам необходимо скачать и установить AutoCAD VBA Enabler со специальной страницы в интернете
Важно то, что при выборе модуля VBA Enabler нужно обратить внимание на версию AutoCAD и его разрядность. Например, модуль VBA для AutoCAD 2018 32-x не будет работать в среде AutoCAD 2018 64-x.
После скачивания, распаковки и установки модуля AutoCAD VBA Enabler в программе AutoCAD появится возможность работать с приложениями на языке VBA.
Окно редактора VBA (VBA IDE) запускается командой VBAIDE.
Оно стандартное для языка VBA и ничем не отличается от VBA в других программах.
Обратите внимание, что двоичный формат файлов проектов VBA в AutoCAD не совместим с форматом проектов Visual Basic. Однако, в VBA для AutoCAD можно импортировать формы, модули и классы, хранящиеся в файлах форматов FRM, BAS и CLS соответственно.
Список команд, предназначенных для работы с программами VBA:
- VBALOAD служит для загрузки проекта VBA
- VBAUNLOAD выгружает проект из AutoCAD
- VBARUN служит для запуска макроса из командной строки
- VBAIDE открывает окно редактора VBA, в котором можно писать, запускать и отлаживать программы
- VBAMAN открывает менеджер VBA
- VBASTMT выполняет команду VBA в командной строке.
Источник
Не работает VBA в Civil 3d 2013
16.12.2012, 07:40 #2

16.12.2012, 10:01 #4

20.12.2012, 11:08 #6
Civil 2013 имеет еще много косяков. Я бы подождал его использовать. Протестировал в одном проекте — то поверхность ни с того ни с сего перекорежит, то при очередном сохранении выскакивает сообщение, что в файле ошибка и нужно использовать команду «Восстан». Добило то, что при печати во время указания рамки если подвигать/попридвигать экран пишет «Печать невозможна, файл занят другим процессом» (или что-то навроде того).
И еще пересохранить в старой версии файл с поверхностями не удастся — только как прокси-объект.
Короче лучше подождать SP1
20.12.2012, 12:19 #7

Добило то, что при печати во время указания рамки если подвигать/попридвигать экран пишет «Печать невозможна, файл занят другим процессом» (или что-то навроде того).
20.12.2012, 17:21 #9
От VBA конечно отклонился, извиняюсь. Имел в виду, что Civil 2013 все может не работать из-за его недороботок.
Цитата:
Сообщение от AlexeySh
Короче лучше подождать SP1
Что его ждать он уже в раздаче.
Чистую систему месяц назад ставил, а SP1 через неделю вышел — невезуха
А у меня нажатие Enter не помогало. Тогда вопрос не по теме: В SP1 косяк с рамкой пропал?
Не дождался, поставил и посмотрел — косяк не пропал. Вывод мой такой — недоработали они 2013 (хотя и приятные вещички появились). Скорее всего и с VBA тоже косяк.

Сейчас нет времени устанавливать, переустанавливать. много срочной работы. На выходных обязательно займусь и отпишусь что получилось. Мне кажется, не хватает чего-то в системе, хотя и SP1 может быть виноват. А пока буду ждать Ваших ответов. Может кто сталкивался с похожей проблемой?
Offtop: У Autodesk, по моему, с конца 2008 г. пошло все как-то не так. Чтобы остаться среди ведущих они вынуждены были глубже внедряться в ГИС, да и в свои решения внедрять много нового из параметрического моделирования и графической обработки. Только делают они это в основном собственными силами вместо привлечения сторонних фирм и интеграции их решений как модулей (например Bentley). Само математическое ядро развивать некогда, поэтому недостающий функционал «навешивают сбоку» и ошибки порой также исправляют. Не удивительно, ведь за пару лет не наберешь достаточное для данных задач количество программистов и чтобы они еще смогли совместно работать. Я думаю в ближайшее время не стоит от Autodesk ждать «чудо».

Всех с наступившим Новым Годом, удачи и отличного отдыха!
Как и обещал, все попробовал. Извините за длительное ожидание, праздники, сами понимаете.
Источник
AutoCAD
Автор:
Проблема
Решение
Из-за появления вредоносных приложений, использующих AutoLISP® и VBA, в пакет обновления 1 для AutoCAD® 2013 включены элементы управления для нескольких новых мер безопасности. Аналогичные пакеты обновления будут выпущены для вертикальных приложений на основе AutoCAD.
Эти новые элементы управления касаются следующих продуктов с установленным пакетом обновления 1:
- AutoCAD 2013
- AutoCAD® 2013 for Mac®
- Вертикальные приложения на основе AutoCAD 2013
AutoCAD LT® не работает с приложениями AutoLISP и VBA и не требует этих мер безопасности.
Что делают новые элементы управления?
Новые элементы управления предоставляют указанные ниже меры безопасности.
- Минимизация вероятности загрузки и запуска недопустимых или вредоносных приложений AutoLISP и VBA благодаря определению местоположения папки, из которой эти приложения загружаются автоматически (системная переменная AUTOLOADPATH).
- Ограничение влияния вредоносных приложений AutoLISP и VBA с помощью отключения автозагрузки таких приложений по умолчанию (системная переменная AUTOLOAD).
- Упрощение процесса очистки благодаря полному отключению AutoLISP при запуске (запуск с параметром /nolisp).
Управление автоматической загрузкой через указание расположения папки
Системная переменная AUTOLOADPATH управляет папками, из которых AutoCAD автоматически загружает следующие файлы AutoLISP и VBA:
Значением по умолчанию для переменной AUTOLOADPATH является пустая строка («») или точка (.). Если задано одно из этих значений, автоматическая загрузка повторяет поведение из более ранних версий. Файлы из списка автоматически загружаются без ограничений в следующем порядке:
- Папка запуска AutoCAD
- Папка текущего чертежа
- Папки в пути поиска вспомогательных файлов AutoCAD
Не рекомендуется устанавливать этот параметр по умолчанию, поскольку вредоносные приложения могут предполагать наличие перечисленных выше папок.
Для минимизации возможности загрузки вредоносных приложений всегда задавайте для системной переменной AUTOLOADPATH значение уникальной папки, в которой находятся разрешенные приложения.
Если указывается несколько папок, используйте точку с запятой в качестве разделителя. Значение переменной AUTOLOADPATH сохраняется в каждом именованном профиле.
Примечание. Для внесения изменений в acad.dvb удалите исходную программу AutoCAD 2013 VBA Enabler и скачайте и установите последнюю версию модуля AutoCAD 2013 VBA, обновленного с учетом изменений, внесенных в пакет обновления 1 для AutoCAD 2013.
Управление автоматической загрузкой приложений AutoLISP и VBA
Для управления автоматической загрузкой приложений AutoLISP и acad.dvb при запуске используйте системную переменную AUTOLOAD:
- Если для AUTOLOAD задано значение 0, автоматическая загрузка ранее указанных файлов AutoLISP и acad.dvb не происходит, что удобно при отладке.
- Если для AUTOLOAD задано значение 1, процесс автозагрузки восстанавливается и зависит от значения системной переменной AUTOLOADPATH.
Отключение загрузки всех приложений AutoLISP
Чтобы предотвратить загрузку любых приложений AutoLISP, используйте переключатель запуска /nolisp для отключения AutoLISP в текущем сеансе AutoCAD, включая все файлы LSP, FAS и VLX.
Если система уже подверглась действию вредоносного приложения, этот параметр позволяет выполнять отладку и очистить установку и все затронутые файлы.
Доступная только для чтения системная переменная LISPENABLED показывает, включен ли AutoLISP в текущем сеансе AutoCAD. Если LISPENABLED имеет значение 0, AutoLISP был отключен переключателем запуска /nolisp.
Примечание. Отключение AutoLISP также предотвращает работу Express Tools и некоторых инструментов команд AutoCAD. Использовать эту возможность можно только в крайних случаях.
Более подробную информацию об использовании переключателей запуска для решения проблемы см. в статье Параметры запуска AutoCAD.
Изменение процесса автозагрузки acad2013.lsp и acad2013doc.lsp
Файлы acad2013.lsp и acad2013doc.lsp теперь будут загружаться только из их папок установки по умолчанию:
Изменения в диалоговом окне «Параметры»
При установке значения 0 для переменной AUTOLOAD или LISPENABLED параметр «Загружать acad.lsp с каждым чертежом» на вкладке «Система» (соответствует системной переменной ACADLSPASDOC) становится недоступным.
Более подробную информацию об этих элементах управления см. в ознакомительных сведениях по AutoCAD 2013 с пакетом обновления 1.
Рекомендуемый ход выполнения установки и восстановления
Для наилучшей защиты от вредоносных приложений AutoLISP и VBA задайте переменную AUTOLOADPATH для уникальной папки и установите значение 1 для параметра AUTOLOAD.
Если вредоносное приложение, выполняемое при запуске, уже внедрилось в программный продукт, выполните приведенные ниже действия.
- Запустите программный продукт на основе AutoCAD с помощью переключателя /nolisp.
- Найдите и удалите все вредоносные коды.
- Восстановите все поврежденные файлы.
- Задайте уникальную папку для переменной AUTOLOADPATH и установите значение 1 для AUTOLOAD.
После выполнения этих действий можно удалить переключатель запуска /nolisp из свойств значка программы на рабочем столе и возобновить работу приложения на основе AutoCAD.
Примечание. Чтобы использовать последние обновления и функции безопасности, пользователям рекомендуется выполнить обновление до последней версии программы.
Источник
Nyme,
I know that error codes 0 — 512 are VBA eror codes
see list below. I was looking for AutoCad error codes
numbers like -2145386420. The only way I know of ACad error codes is to cause erros. I handle lots of error
like this
err.clear
on error resume next
Set objBlockRef = .ModelSpace.InsertBlock(insertionPnt, strDwgWithPath, 1#, 1#, 1#, 0)
If err <> 0 then
msgbox » error inserting block » & strDwgWithPath
err.clear
end If
Fred C
‘ ************************************************
‘ ********** VBA Error Codes **************************
‘
‘3 Return without GoSub
‘5 Invalid procedure call
‘6 Overflow
‘7 Out of memory
‘9 Subscript out of range
’10 This array is fixed or temporarily locked
’11 Division by zero
’13 Type mismatch
’14 Out of string space
’16 Expression too complex
’17 Can ‘t perform requested operation
’18 User interrupt occurred
’20 Resume without error
’28 Out of stack space
’35 Sub, Function, or Property not defined
’47 Too many code resource or DLL application clients
’48 Error in loading code resource or DLL
’49 Bad code resource or DLL calling convention
’51 Internal Error
’52 Bad file name or number
’53 File Not found
’54 Bad file mode
’55 File already open
’57 Device index/O error
’58 File already exists
’59 Bad record length
’61 Disk full
’62 Input past end of file
’63 Bad record number
’67 Too many files
’68 Device unavailable
’70 Permission denied
’71 Disk Not Ready
’74 Can ‘t rename with different drive
’75 Path/File access error
’76 Path Not found
’91 Object variable or With block variable not set
’92 For loop not initialized
’93 Invalid pattern string
’94 Invalid use of Null
’97 Can ‘t call Friend procedure on an object that is not an instance of the defining class
’98 A property or method call cannot include a reference to a private object, either as an argument or as a return value
‘298 System resource or DLL could not be loaded
‘320 Can ‘t use character device names in specified file names
‘321 Invalid file format
‘322 Can’t create necessary temporary file
‘325 Invalid format in resource file
‘327 Data value named not found
‘328 Illegal parameter; can’t write arrays
‘335 Could not access system registry
‘336 Component not correctly registered
‘337 component Not found
‘338 Component did not run correctly
‘360 Object already loaded
‘361 Can ‘t load or unload this object
‘363 Control Not Specified
‘364 Object was unloaded
‘365 Unable to unload within this context
‘368 The specified file is out of date. This program requires a later version
‘371 The specified object can’t be used as an owner form for Show
‘380 Invalid property value
‘381 Invalid property-array index
‘382 Property Set can’t be executed at run time
‘383 Property Set can’t be used with a read-only property
‘385 Need property-array index
‘387 Property Set not permitted
‘393 Property Get can’t be executed at run time
‘394 Property Get can’t be executed on write-only property
‘400 Form already displayed; can’t show modally
‘402 Code must close topmost modal form first
‘419 Permission to use object denied
‘422 Property not found
‘423 Property or method not found
‘424 Object required
‘425 Invalid object use
‘429 component Can ‘t create object or return reference to this object
‘430 Class doesn ‘t support Automation
‘432 File name or class name not found during Automation operation
‘438 Object doesn ‘t support this property or method
‘440 AutomatiOn Error
‘442 Connection to type library or object library for remote process has been lost
‘443 Automation object doesn’t have a default value
‘445 Object doesn ‘t support this action
‘446 Object doesn ‘t support named arguments
‘447 Object doesn ‘t support current locale setting
‘448 Named Not Argument
‘449 Argument not optional or invalid property assignment
‘450 Wrong number of arguments or invalid property assignment
‘451 Object not a collection
‘452 Invalid ordinal
‘453 Specified code resource not found
‘454 Code Not resource
‘455 Code resource lock error
‘457 This key is already associated with an element of this collection
‘458 Variable uses a type not supported in Visual Basic
‘459 This component doesn’t support the set of events
‘460 Invalid Clipboard format
‘461 Method or data member not found
‘462 The remote server machine does not exist or is unavailable
‘463 Class not registered on local machine
‘480 Can ‘t create AutoRedraw image
‘481 Invalid Picture
‘482 printer Error
‘483 Printer driver does not support specified property
‘484 Problem getting printer information from the system. Make sure the printer is set up correctly
‘485 Invalid picture type
‘486 Can ‘t print form image to this type of printer
‘520 Can ‘t empty Clipboard
‘521 Can ‘t open Clipboard
‘735 Can ‘t save file to TEMP directory
‘744 Search Not text
‘746 Replacements too long
28 Oct, 2015
By: Andrew G. Roe
Errors are bound to happen, but it’s simple to incorporate error handling in your VB.NET and VBA code.
Regardless of your programming skill level, errors can occur whenever someone runs your program. The key is handling those errors correctly and efficiently. In most of my previous articles on AutoCAD programming, error handling has been omitted for brevity and clarity in demonstrating other programming concepts. In this article, we’ll look more closely at error handling in two different environments: Visual Basic for Applications (VBA) and Visual Basic.NET (VB.NET).
VBA
While VBA has declined in popularity among AutoCAD programmers in the past decade, Autodesk still unofficially supports it with a downloadable VBA enabler, so AutoCAD users can continue using legacy VBA routines (see “VBA Lives On with AutoCAD 2016”). VBA’s simplicity provides a good starting point for understanding basic error-handling concepts.
Consider the case where your program needs to perform some basic calculations, such as dividing one number into another to determine a percentage. Errors could occur if the user enters something other than a number (such as a letter), or if the user tries to divide a number by zero. VBA provides several tools to handle these errors, including the On Error statement. To see how this works, try the following steps.
1. If you haven’t already done so, download and install the 32-bit or 64-bit VBA enabler (whichever is applicable to your operating system). The enabler works in AutoCAD and its vertical products.
2. Start AutoCAD.
3. Select the Manage tab on the AutoCAD ribbon, and click Visual Basic Editor. This opens the VBA Interactive Development Environment (IDE), as shown below.
4. From the Insert menu in the VBA IDE, click Module to insert a blank Module.
5. Add the following code into the VBA code window:
Private Sub ErrorHandlingExample()
On Error GoTo ErrorHandler
Dim Var1 As Double
Dim Var2 As Double
Dim Pct As Double
Var1 = InputBox("Enter a numerator:")
Var2 = InputBox("Enter a denominator:")
Pct = Var1 / Var2
MsgBox ("Percentage = " & Pct)
Exit Sub
ErrorHandler:
Select Case Err.Number
Case 11
MsgBox "You tried to divide by zero."
Case 13
MsgBox "You did not enter a number."
Case Else
MsgBox Err.Description
End Select
End Sub
6. Click the Play button to run the routine you just created.
7. Enter a number when prompted for the numerator, and enter 0 when prompted for the denominator. You should see an error message in a message box.
8. Click OK to close the information window and return to the VBA IDE.
9. Click the Play button to run the routine again.
10. Enter a letter when prompted for the numerator. You should see a different error message.
If you enter two numbers when prompted, the program runs as intended and provides an answer.
1 2
You installed AutoCAD VBA extensions and when launching a VBA code or typing in VBA commands (like VBAIDE, VBARUN, VBAMAN, etc), AutoCAD pops up and tells you AutoCAD VBA is not installed.
This can be caused by a few factors, but if you’ve followed the guidance in the Autodesk KB and still cannot get it to run, then the issue may not be the installer, but some core files that are missing/corrupt.
Here’s what I normally do to correct it:
1. Uninstall the AutoCAD VBA Extension
2. Do a full rebuild of the C++ libraries:
https://resources.imaginit.com/support-blog/how-to-uninstall-and-reinstall-c-libraries
3. After the rebuild, please reinstall the AutoCAD VBA extension and see if the issue is now resolved.
About the Author
Sr. Technical Support Specialist<br><br>An AutoCAD Certified Professional, Ryan is responsible for taking client cases and assisting with issues with the software — everything from regular glitches to software deployments and whatever else goes wrong. He’s proficient in AutoCAD (including customization), VBA, LISP, and Civil 3D.
Follow on Linkedin
More Content by Ryan Wunderlich
Previous Article
Next Article
If your application doesn’t react the way you intended, or if it produces unexpected results or simply stops working for no apparent reason, then your program probably has what’s known as a bug. The process of hunting down and correcting bugs is called debugging. This topic describes various types of errors you may accidentally introduce into your code. It also discusses the extremely useful features that are available from the VBA IDE to help you identify and fix your problems when things go wrong.
You may encounter the following types of errors in the VBA code you work with:
• Logic errors are made during the development phase as you write the code.
• Compiler errors are sometimes discovered by the VBA interpreter immediately after you enter a statement. Sometimes they are discovered by the compiler program when it tries to translate the code into an executable form.
• Run-time errors occur during execution time.
The VBA IDE doesn’t attempt to fix any of these errors for you, but it does provide useful features to help you when things go wrong. You’ll be able to do as much as possible to ensure that the code you enter is syntactically correct so that the interpreter program can understand it. Other features assist in debugging your code when it doesn’t quite work in the way it’s supposed to.
The next three sections describe these three classifications of errors in more detail.
Logic Errors
Logic errors, introduced as you develop the VBA code, only become obvious when your application doesn’t perform as expected. For example, suppose your application requires the user to enter a telephone number into a text box and, as each key is pressed, validates the corresponding character to ensure that it’s a number. If not, the application rejects it and sounds a beep.
The text box control in your application has a KeyPress event procedure that is passed the numeric ASCII code of the last key pressed as its KeyAscii parameter. The KeyPress event procedure for the telephone number entry in Listing 10.1, for example, is syntactically correct, runs like a dream without giving any error messages, doesn’t fall over—and yet, when you enter a letter into the text box instead of a number, your letter is accepted and appended to the Text property string. Which was not the original idea and isn’t supposed to happen.
The error here is in the condition of the If statement. As written, the condition will always be False because there is no key you can press that produces a character that is both less that the ASCII code for zero and greater than the ASCII code for 9. For this condition to be True, the character input would have to be represented by two different ASCII codes.
To rectify this event procedure, the And from the If statement on Line 2 must be changed to an Or. That way, only numbers will get displayed in the text box and the others will be discarded.
If you want to run this event procedure and examine it as you work through this topic, you’ll need to set up a GUI with a UserForm containing a label and a command button control as shown in Figure 10. Change the Caption properties to those shown in the figure, and update the Name property of your tex box to txtTelephone.
Figure 10.1 Input Validation GUI for prompting the user to enter a telephone number
Listing 10.1: KeyPress Event Procedure
Analysis
• Line 1 starts the KeyPress event procedure ofthe txtTelephone text box.This has a ByVal parameter, KeyAscii, that’s assigned the ASCII code value of the character associated with the key just entered.The KeyAscii parameter is passed a reference to the Microsoft Form’s ReturnInteger object, which allows you to reject any invalid characters.
• Line 2 uses the If statement with a condition that attempts to verify that the KeyAscii character is not in the range 0 through 9. It mistakenly uses the And operator, however, instead of the Or operator. The result is that any character entered gets accepted and appended to the text in the text box.
• Line 3 cancels the keypress and is only executed if the condition in the If statement evaluates to True.
• Line 4 sounds a beep to alert the user that the last character input has been rejected.
• Line 4 ends the If statement block.
• Line 5 ends the KeyPress event procedure.
Compiler Errors
Compiler errors occur because you have entered code incorrectly. Some compiler errors are picked up right away when you enter a statement that doesn’t meet the syntax requirements of the Visual Basic language. Other compiler errors are detected during compile time, while your source code is being translated into executable code ready for running by the Compile ACADProject command under the Debug menu.
Getting Feedback as You’re Entering Code
The VBA IDE can be set up to provide immediate feedback as soon as you enter a statement containing a syntax error. For example, if you enter the following statement and press Enter:
If A = B
you’ll see the following message box containing the error message about an expected Then:
If you try this and no message appears, you’ll need to make sure that you have enabled the Auto Syntax Check option in the IDE Options dialog box (Figure 10.2):
1. Choose Tools ^ Options and select the Editor tab.
2. If the Auto Syntax Check option isn’t on, select the check box to enable it.
3. Click OK to return to the VBA IDE.
Figure 10.2 The Editor tab from Tools – Options contains the Auto Syntax Check option.
ByVal Parameters vs. ByRef Parameters
A ByVal parameter is passed a copy of a variable, so if the procedure changes the value of the parameter, only the copy is changed. This means the variable still keeps its original value.
A ByRef parameter is passed a reference to a variable that enables access to the contents in its memory address allocation. Updating a ByRef parameter updates the memory address contents,so the variable will still be set to the new value after the procedure has finished executing.
A ByVal parameter can also be passed a reference to a ReturnBoolean, ReturnEffect, ReturnInteger, or ReturnString object. As such, ByVal acts more like a ByRef parameter, in that you can update the named parameter,and the Value property of the object will retain the new value even after the procedure has finished.
Errors during the Compilation Stage
Following are a couple of examples of errors that often occur as you compile the entire application into executable code. (This is the last step you’ll do prior to running the code.)
• Variables that are not defined even although the Option Explicit statement is included at the start of the module. When the compiler comes across such variables, it displays the message “Compiler error: Variable not defined.”
• Missing arguments from calls to a method or function. When a method or function call does not include all the required arguments, the message “Compiler error: Argument not optional” appears.
Run-Time Errors
A run-time error occurs while the code is being executed and usually means that a statement has attempted to perform some invalid operation.
One common run-time error is when your code tries to divide a number by a variable that’s set to zero.
When you’re working with variables that are supposed to be set up as references to objects, another common run-time error you might make is to forget to include the Set in the assignment statement. For example, the following statement
produces a message box containing the error message Run-time error 91 : Object variable or With block variable not set.” This statement should have been written as follows:
Err Object
The properties of the Err object are assigned the details of a run-time error. They uniquely identify the error, give its source, and provide a description including (if possible) how to handle the error. The following table lists and describes the Err object’s properties. The Err object’s properties are initially set to zero or to empty strings. When an error occurs, they are reset to values and strings that provide useful information about the error.
Number Numerical value in the range 0 to 65,535 that, in combination with the Name property, uniquely identifies the error. This property is used as the argument passed to the Error statement.
Source Returns the name of the object or the application that caused the error. Description Contains an error message from the application or an object. HelpFile Pathname for the Visual Basic Help file.
HelpContext The Help file’s context ID for the error associated with the Number property.
LastDLLError Contains the system error code for the last call to a Dynamic Link Library (DLL).









