Excel 2010 Developer Reference > Visual Basic for Applications Language Reference > Visual Basic Language Reference
Error Messages
Topics
#Else clause must be preceded by a matching #If
#Else If, #Else, or #End If must be preceded by a matching #If
#ElseIf must be preceded by a matching #If or #ElseIf and followed by an #ElseIf, #Else, or #End If
<Item> is not a valid control type (Error 720)
A compatible ActiveX component must be a Visual Basic executable or a DLL
A form can’t be moved or sized while minimized or maximized
A module is not a valid type
A procedure of that name already exists
A procedure with a ParamArray argument cannot be called with named arguments
A property or method call cannot include a reference to a private object, either as an argument or as a return value (Error 98)
ActiveX component can’t create object or return reference to this object (Error 429)
ActiveX Component did not run correctly (Error 338)
ActiveX component not correctly registered (Error 336)
ActiveX control ‘item’ not found (Error 363)
Add-in can’t reference project
Ambiguous name detected
AppleScript error
Application-defined or object-defined error
Argument not optional (Error 449)
Argument required for Property Let or Property Set
Array already dimensioned
Array argument must be ByRef
Assignment to constant not permitted
Automation error (Error 440)
Automation object doesn’t have a default value (Error 443)
Bad DLL calling convention (Error 49)
Bad file mode (Error 54)
Bad file name or number (Error 52)
Bad interface for Implements: interface contains data fields
Bad interface for Implements: interface is derived from another pure interface with non-restricted methods
Bad interface for Implements: interface is not derived from Iunknown
Bad interface for Implements: method does not return HRESULT
Bad interface for Implements: method has out-only or LCID parameter
Bad interface for Implements: method has parameter with too many levels of indirection
Bad interface for Implements: method has underscore in name
Bad interface for Implements: methods uses type that is not supported by Visual Basic
Bad record length (Error 59)
Bad record number (Error 63)
Beginning of search scope has been reached; do you want to continue from the end?
Block If without End If
Breakpoint not allowed on this line
ByRef argument type mismatch
Calling convention not supported by Visual Basic
Cannot define a KWID_tkPUBLIC user-defined type within a private object module
Cannot display specified name because it is hidden
Cannot handle events for the object specified
Cannot jump to specified type because it is in the specified library, which is not currently referenced
Can’t add a reference to the specified file
Can’t assign or coerce array of fixed-length string or user-defined type to Variant
Can’t assign to an array
Can’t call Friend procedure on an object that isn’t an instance of the defining class (Error 97)
Can’t change data types of array elements
Can’t create AutoRedraw image (Error 480)
Can’t create necessary temporary file (Error 322)
Can’t display hidden procedure
Can’t display system information
Can’t edit module
Can’t empty Clipboard (Error 520)
Can’t enter break mode at this time
Can’t execute code in break mode
Can’t execute immediate statements in design mode
Can’t exit design mode because control can’t be created
Can’t find DLL entry point in specified DLL
Can’t find project or library
Can’t find Windows Help .exe file
Can’t Get or Put user-defined type containing object reference
Can’t have paramarrays with optional arguments
Can’t load module; invalid format
Can’t load or unload this object (Error 361)
Can’t make an assignment to a read-only property
Can’t open Clipboard (Error 521)
Can’t perform operation because the project is protected
Can’t perform requested operation (Error 17)
Can’t perform requested operation since the module is hidden
Can’t place conditional breakpoint on an array
Can’t print form image to this type of printer (Error 486)
Can’t print minimized form image
Can’t quit at this time
Can’t record into running module
Can’t ReDim, Erase, or assign to Variant that contains array whose element is With object
Can’t remove control or reference; in use
Can’t remove default reference
Can’t rename with different drive (Error 74)
Can’t save file to TEMP directory (Error 735)
Can’t set the project name at this time
Can’t show non-modal form when modal form is displayed
Can’t sink this object’s events because it’s already firing events to the maximum number of supported event recipients (Error 96)
Can’t start new recording until current session is ended
Can’t use character device names in file names: ‘item’ (Error 320)
Case Else outside Select Case
Case without Select Case
Circular dependencies between modules
Class doesn’t support Automation (Error 430)
Class is not set (Error 31018)
Class not registered on local machine (Error 463)
Class not registered. ‘item 1’
Code execution has been interrupted
Code resource lock error (Error 455)
Code resource not found (Error 454)
Compile error in hidden module: <module name>
Component not correctly registered
Conflicting attributes were found in ‘item’. The defaults will be used
Conflicting names were found in ‘item1’. The name ‘item2’ will be used
Connection to type library or object library for remote process has been lost (Error 442)
Constant expression required
Constants, fixed-length strings, arrays, user-defined types, and Declare statements not allowed as Public members of an object module
Could not access system registry (Error 335)
Could not create reference: ‘item’
Could not execute specified program
Could not start Internet Explorer
Current module does not support Print method
Cyclic reference of projects not allowed
Data value named not found (Error 327)
Definitions of property procedures for the same property are inconsistent
Deftype statements must precede declarations
Destination label too far away; loop, Select Case, or block If too large
Device I/O error (Error 57)
Device unavailable (Error 68)
Disk full (Error 61)
Disk not ready (Error 71)
Display more load errors?
Division by zero (Error 11)
Do without Loop
Do you want to export specified object before removing it?
Duplicate declaration in current scope
Duplicate definition
Duplicate Deftype statement
Duplicate Option statement
Duplicate procedure name
Duplicate resources with same type and name
Edit can’t be undone—proceed anyway?
Else without If
Empty Enum type not allowed
Empty watch expression
End If without block If
End of search scope has been reached; do you want to continue from the beginning?
End Select without Select Case
End With without With
Enum types defined in standard modules or private classes cannot be used in public object modules as parameters or return types for public procedures, as public data members, or as fields of public user defined types
Error accessing the system registry
Error in loading DLL (Error 48)
Error loading from file (Error 31037)
Error loading ‘item’. A control could not be loaded due to load error. Continue?
Error loading ‘item’. An error was encountered loading a property. Continue?
Error saving to file (Error 31036)
Errors during load. Refer to ‘item’ for details
Errors occurred during load
Event handler is invalid
Event not found
Exit Do not within Do…Loop
Exit For not within For…Next
Exit Function not allowed in Sub or Property
Exit Property not allowed in Function or Sub
Exit Sub not allowed in Function or Property
Expected array
Expected End Function
Expected End Property
Expected End Sub
Expected End With
Expected Function or variable
Expected procedure, not module
Expected procedure, not project or library
Expected procedure, not user-defined type
Expected procedure, not variable
Expected Sub, Function, or Property
Expected user-defined type, not project
Expected variable or procedure, not Enum type
Expected variable or procedure, not module
Expected variable or procedure, not project
Expected: <various>
Expression too complex (Error 16)
External name not defined
Failed to activate control ‘item 1’. This control may be incompatible with your application. Make sure you are using the version of the control that was provided with your application.
Failed to load control ‘item1’ from ‘item2’. Your version of ‘item2’ may be outdated. Make sure you are using the version of the control that was provided with your application.
File already exists (Error 58)
File already open (Error 55)
File format no longer supported
File is read-only
File not found (Error 53)
File specified was not found
Filename or class name not found during Automation operation (Error 432)
Fixed or static data can’t be larger than 64K
Fixed-length strings and use of the ‘new’ qualifier are not allowed for fields in a public user defined type defined in an object module
Fixed-length strings not allowed as the type of a public member of an object module; private object modules not allowed as the type of a public member of a public object module
For control variable already in use
For Each can only iterate over a collection object or an array
For Each control variable must be Variant or Object
For Each control variable on arrays must be Variant
For Each may not be used on array of user-defined type or fixed-length strings
For loop not initialized (Error 92)
For without Next
Form already displayed; can’t show modally (Error 400)
Form not found (Error 424)
Forward reference to user-defined type
Function call on left-hand side of assignment must return Variant or Object
Function marked as restricted or uses a type not supported in Visual Basic
Identifier too long
Identifier under cursor isn’t a procedure name
Illegal parameter. Can’t write arrays (Error 328)
Illegal parameter. Can’t write object because it does not support persistence.
Illegal parameter. Can’t write user-defined type.
Incorrect DLL version
Incorrect OLE version
Input past end of file (Error 62)
Insufficient Immediate window memory to create variable
Insufficient memory to save Undo information
Insufficient project information to load project on platform or with version now being used
Interface not valid for Implements
Internal error (Error 51)
Invalid Access mode
Invalid attribute in Sub, Function, or Property
Invalid character
Invalid Clipboard format (Error 460)
Invalid Clipboard format (Error 460)
Invalid data format
Invalid data type for constant
Invalid event name
Invalid file format (Error 321)
Invalid file format (Error 321)
Invalid format in resource file (Error 325)
Invalid in Immediate window
Invalid inside Enum
Invalid inside procedure
Invalid length for fixed-length string
Invalid Next control variable reference
Invalid object use (Error 425)
Invalid optional parameter type
Invalid or unqualified reference
Invalid ordinal (Error 452)
Invalid outside Enum
Invalid outside procedure
Invalid ParamArray use
Invalid pattern string (Error 93)
Invalid picture (Error 481)
Invalid picture (Error 481)
Invalid picture type (Error 485)
Invalid procedure call or argument (Error 5)
Invalid procedure name
Invalid property name
Invalid property value (Error 380)
Invalid property value (Error 380)
Invalid property-array index (Error 381)
Invalid qualifier
Invalid ReDim
Invalid syntax for conditional compiler constant declarations
Invalid Template
Invalid type-declaration character
Invalid use of AddressOf operator
Invalid use of base class name
Invalid use of Me keyword
Invalid use of New keyword
Invalid use of Null (Error 94)
Invalid use of object
Invalid watch expression
Item’ already exists in project
‘item’ cannot be added because it is referenced but not in use by any items in the project. To correct this, uncheck ‘Remove information about unused ActiveX Controls’ in Project Options.
Item’ could not be loaded
‘Item’ could not be loaded. Remove it from the list of available add-ins?
Item’ could not be registered
‘item’ designers can only be used in DLL projects
‘item’ designers cannot be private
‘item’ designers cannot be public in ActiveX EXE projects
‘item’ designers must be public and cannot be used in Standard EXE projects
‘Item’ has an old file format. When saved, it will be saved in a newer format.
‘item’ has caused an access violation. Remove it from the list of available Add-Ins?
‘Item’ is a binary form and can’t be loaded into Visual Basic
‘Item’ is a read-only file
‘item’ is a single-threaded component and cannot be used in multi-threaded projects. Change the threading model for ‘item’ or contact the component vendor for an updated version.
‘Item’ property can’t be read at run time (Error 393)
‘Item’ property can’t be set at run time (Error 382)
‘Item’ property is read-only (Error 383)
‘Item’ property is write-only (Error 394)
‘Item’ will not be loaded. Name is already in use
‘item1’ is an invalid key. The file ‘item2’ can’t be loaded
‘item1’ is referenced by ‘item2’ project and cannot be updated.
Label not defined
Language/country setting has changed
License information for this component not found. You don’t have an appropriate license to use this functionality in the design environment (Error 429)
Line isn’t an executable statement
Line ‘item1’: All controls must precede menus; can’t load control ‘item2’.
Line ‘item1’: Can’t create embedded object in ‘item2’
Line ‘item1’: Can’t create embedded object in ‘item2’; license not found
Line ‘item1’: Can’t load control ‘item2’; containing control not a valid container.
Line ‘item1’: Can’t load control ‘item2’; license not found
Line ‘item1’: Can’t load control ‘item2’; name already in use.
Line ‘item1’: Can’t set checked property in menu ‘item2’. Parent menu can’t be checked.
Line ‘item1’: Can’t set Shortcut property in menu ‘item2’. Parent menu cannot have a shortcut key.
Line ‘item1’: Class ‘item2’ of control ‘item3’ was not a loaded control class.
Line ‘item1’: Class name too long; truncated to ‘item2’.
Line ‘item1’: Control name too long; truncated to ‘item2’.
Line ‘item1’: Could not create reference: ‘item2’
Line ‘item1’: Did not find an index property, and control ‘item2’ already exists.
Line ‘item1’: ‘item2’ has a quoted string where the property name should be.
Line ‘item1’: Maximum nesting level for controls exceeded with ‘item2’.
Line ‘item1’: Missing or invalid control class in file ‘item2 ‘.
Line ‘item1’: Missing or invalid control name in file ‘item2’.
Line ‘item1’: Parent menu ‘item2’ can’t be loaded as a separator.
Line ‘item1’: Property ‘item2’ in control ‘item3’ had an invalid property index.
Line ‘item1’: Property ‘item2’ in ‘item3’ could not be loaded.
Line ‘item1’: Property ‘item2’ in ‘item3’ could not be set.
Line ‘item1’: Property ‘item2’ in ‘item3’ had an invalid file reference.
Line ‘item1’: Property ‘item2’ in ‘item3’ had an invalid value.
Line ‘item1’: Property ‘item2’ in ‘item3’ must be a quoted string.
Line ‘item1’: Syntax error: property ‘item2’ in ‘item3’ was missing an equal sign (=).
Line ‘item1’: The CLSID ‘item2’ for ‘item3’ is invalid.
Line ‘item1’: The control name ‘item2’ is invalid.
Line ‘item1’: The file ‘item2’ could not be loaded.
Line ‘item1’: The Form or MDIForm name ‘item2’ is already in use; can’t load this form.
Line ‘item1’: The Form or MDIForm name ‘item2’ is not valid; can’t load this form.
Line ‘item1’: The property name ‘item2’ in ‘item3’ is invalid.
Line too long
Loop without Do
LSet allowed only on strings and user-defined types
LSet not allowed
Maximum number of watch expressions added
MDI forms are not allowed in multithreaded projects. Any MDI form will be removed from this project. To keep the MDI form in the project select Cancel and change threading model to Thread Pool with only 1 thread.
Member identifier already exists in object module from which this object module derives
Method not valid without suitable object
Method or data member not found (Error 461)
Missing end bracket
Module not found
Module too large
Must be first statement on the line
Must close or hide topmost modal form first (Error 402)
Must specify which item(s) to print
Name conflicts with existing module, project, or object library
Name ‘item’ conflicts with existing module, project, or object library
Named argument already specified
Named argument not found (Error 448)
Named arguments not allowed
Need property-array index (Error 385)
Next without For
No creatable public component detected. Press F1 for more information.
No Help available
No object (Error 31004)
No text selected
No watch expression selected
Not a legal object name: ‘item
Not enough memory to completely save project
Not enough memory to load file
Not enough memory to run; quitting
Object already loaded (Error 360)
Object does not have a Property Let procedure
Object does not source Automation events
Object doesn’t support current locale setting (Error 447)
Object doesn’t support named arguments (Error 446)
Object doesn’t support this action (Error 445)
Object doesn’t support this property or method (Error 438)
Object library feature not supported
Object library for Visual Basic for Applications not found
Object library invalid or contains references to object definitions that could not be found
Object library not registered
Object library’s language setting incompatible with current project
Object module must implement all procedures in interface
Object required (Error 424)
Object server not found (Error 337)
Object variable not set (Error 91)
Object was unloaded (Error 364)
One or more files in the project have changed. Do you want to save the changes now?
One or more instances of this object are running. Can’t remove it at this time.
One or more of the properties in ‘item’ was bad. Some or all of the properties might not be set correctly.
Only comments may appear after End Sub, End Function, or End Property
Only public user defined types defined in public object modules can be used as parameters or return types for public procedures of class modules or as fields of public user defined types
Only valid in object module
Operation not allowed in DLL
Option Private Module not permitted in object module
Optional argument must be Variant
Other applications are currently accessing an object in your program. Ending the program now could cause errors in those programs. End program at this time?
Out of memory (Error 31001)
Out of memory (Error 7)
Out of memory; some watches might have been deleted
Out of resources
Out of stack space (Error 28)
Out of string space (Error 14)
Overflow (Error 6)
ParamArray must be declared as an array of Variant
Path not found (Error 76)
Path/File access error (Error 75)
Permission denied (Error 70)
Permission to use object denied (Error 419)
Please see the Readme file for more information on this error
Printer driver does not support specified property (Error 483)
Printer error (Error 482)
Printer error (Error 482)
Private Enum and user-defined types cannot be used as parameters or return types for public procedures, public data members, or fields of public user-defined types
Private object modules cannot be used in public object modules as parameters or return types for public procedures, as public data members, or as fields of public user defined types
Problem getting printer information from the system; make sure the printer is set up correctly. (Error 484)
Procedure declaration does not match description of event or procedure having same name
Procedure too large
Procedure type mismatch
Project contains too many procedure, variable, and constant names
Project file is read-only
Project is unviewable.
Project not found
Property Get can’t be executed at run time (Error 393)
Property Get can’t be executed on write-only property (Error 394)
Property let procedure not defined and property get procedure did not return an object (Error 451)
Property not found (Error 422)
Property or method not found (Error 423)
Property Set can’t be executed at run time (Error 382)
Property Set can’t be used with a read-only property (Error 383)
Property Set not permitted (Error 387)
Qualified name disallowed in module scope
Qualifier must be collection
Range has no values
Replacements too long (Error 746)
Requested type library or wizard is not a VBA project
Resume without error (Error 20)
Return without GoSub (Error 3)
RSet allowed only on strings
Run-time error <number>:
Search string must be specified
Search string must be specified
Search string too long or complex
Search text isn’t found
Search text not found (Error 744)
Seek failed: can’t read/write from the disk
Select Case without End Select
Selected watch expression invalid
Set Next Statement can only apply to executable lines within current procedure.
SHARE.EXE required
Specified ActiveX component not correctly registered or not found
Specified DLL function not found (Error 453)
Specified format doesn’t match format of data (Error 461)
Specified library or project already referenced
Statement invalid inside Type block
Statement invalid outside Type block
Statement too complex
Statements or labels invalid between Select Case and first Case
String value too long to process; form load aborted
Sub, Function, or Property not defined (Error 35)
Subscript out of range (Error 9)
Syntax error
System DLL ‘dll’ could not be loaded (Error 298)
System error ‘item’
The .VBP file for this project contains an invalid or corrupt library references ID
The ActiveX Designer’s Type Information does not match what was saved. Unable to Load.
The application description can’t be more than 2000 characters long
The code in this project must be updated for use on 64-bit systems
The current project does not support files of this type
The edit may make the object module incompatible with the previously specified compatible ActiveX component
The file ‘item’ is marked as a version not supported by the current version of Visual Basic and won’t be loaded
The file ‘item’ is out of date. This program requires a later version (Error 368)
The form class contained in the specified file is not supported in Visual Basic for Applications; the file can’t be loaded.
The library containing this symbol is not referenced by the current project, so the symbol is undefined. Would you like to add a reference to the containing library now?
The project file ‘item’ is corrupt and can’t be loaded
The project file ‘item1’ contains invalid ‘item2’ key value
The project file ‘item1’ contains invalid ‘item2’ key value. Valid range is 0 to ‘item3’
The project file ‘item1’ contains invalid key ‘item2’. The project can’t be loaded
The project name is too long. Name has been truncated
The remote server machine does not exist or is unavailable (Error 462)
The selected Add-In has not been confirmed to be ‘Command Line Safe,’ and may require some user intervention (possible UI)
The specified file could not be loaded.
The specified object can’t be used as an owner form for Show() (Error 371)
The specified region has been searched
The specified region has been searched and 1 replacement was made
The specified region has been searched and the replacements were made
This action will reset your project, proceed anyway?
This array is fixed or temporarily locked (Error 10)
This command will stop the debugger.
This component doesn’t raise any events
This component doesn’t support this set of events (Error 459)
This control can only be used with ‘item’ designers
This control cannot be used with ‘item’ designers
This designer cannot be used because it uses features that are not supported in this version of Visual Basic
This document was opened with Macros Disabled
This edit requires a Reset
This feature requires Internet Explorer ‘item’ or greater. You can obtain the latest version from http://www.microsoft.com
This interaction between compiled and design environment components is not supported
This key is already associated with an element of this collection (Error 457)
This project is currently referenced by another project and cannot be closed
This VBA project was created while running VBA in a different application. You may only open it from inside the same application in which it was created.
Too many arguments
Too many dimensions
Too many DLL application clients
Too many files (Error 67)
Too many line continuations
Too many local, nonstatic variables
Too many module-level variables
Translation failed. Please check the trnslate.log file for more information.
Trappable Errors
Type mismatch (Error 13)
Type mismatch: array or user-defined type expected
Type not supported in Visual Basic
Type-declaration character does not match declared data type
Type-declaration character not allowed
Type-declaration character required
Unable to activate object (Error 31027)
Unable to create embedded object (Error 31032)
Unable to read from the disk
Unable to unload within this context (Error 365)
Unable to write Designer cache file ‘item’; will just use regular files on Load
Unable to write to the disk
Unexpected compile error
Unexpected error
Unexpected error; please contact Microsoft Technical Support
Unexpected error; quitting
Unmatched brackets in search string
Unrecognized project language
User interrupt occurred (Error 18)
User-defined type may not be passed ByVal
User-defined type not defined
User-defined type without members not allowed
Valid values are whole numbers from 1 to 32
Valid values are whole numbers from 2 to 60
Variable not defined
Variable not yet created in this context
Variable required. Can’t assign to this expression
Variable uses a type not supported in Visual Basic (Error 458)
Version number missing or invalid; Visual Basic 5.0 assumed
Visual Basic can’t load ‘item’ because it is not in the system registry. Please ensure that all add-ins have been installed correctly.
Warning: custom language settings not portable
Wend without While
While without Wend
Windowless controls can’t have menus.
With object must be user-defined type, Object, or Variant
Wizards can’t reference projects
Wrong number of arguments (Error 450)
Wrong number of dimensions
Wrong version of operating system; requires Windows NT 3.51 (build ‘item1’ or later) or Windows 95 (build ‘item2’ or later)
You must save a project before you can reference it.
You must terminate the #If block with an #End If
Component could not successfully create requested object
Component ‘item’ or one of its dependencies not correctly registered: a file is missing or invalid
Component not found in registered location
Invalid Base Address
Programmatic ID string too long ‘item’. The Programmatic ID must be 39 characters or less.
Project <name> has been modified. Do you wish to save the changes now?
The file ‘item’ was not registerable as an ActiveX Component.
The load behavior for ‘item’ could not be updated because of current registry permissions.
The project file ‘item1’ contains invalid key ‘item2’.
Unable to display Help
Unexpected error occurred in code generator or linker
Version numbers must be in the range 0 to 9999
The binary compatibility DLL or EXE contains a parameter type or return type whose definition cannot be found
The binary compatibility DLL or EXE contains an Implements type whose definition cannot be found
При написании кода пишет ошибку: expected line number or label or statement or end of statement
В этой программе полный ноль, не могу понять что не так.
Option Explicit
Sub PRIM4_1()
‘Объявление переменных I,J,K целого типа
Dim I As Integer, J As Integer, K As Integer
‘Объявление переменных MIN, MAX и массива A(1 To 10) вещественного типа
Dim A(1 To 10) As Single, MIN As Single, MAX As Single
‘Объявление переменной S строкового типа
Dim S As String
‘Задание начального значения
S = «»
‘Начало цикла, где I-параметр цикла
For I = 1 To 10
‘Заполнение элементов массива — A(I) случайными величинами
A(I) = (Rnd * 10 + I)
‘Суммирование элементов массива в строку для вывода в окно
S = S + «» + Str(Format(A(I), «FIXED»))
‘Продолжение цикла
Next I
‘Вывод значений элементов массива в диалоговое окно
MsgBox «Вывод элементов массива», vbInformation, «S=» & S
‘Задание начальных значений переменных MIN и MAX
MAX = A(1): K = 1
MIN = A(1): J = 1
‘Начало цикла
For I = 2 To 10
‘Поиск MIN путём сравнения MIN с последующими элементами
If A(I) < MIN Then MIN = A(I): J = I
‘Поиск Max путём сравнения Max с последующими элементами
If A(I) > MAX Then MAX = A(I): K = I
‘Продолжения цикла
Next I
‘Вывод результата вычислений
MsgBox «Индексы мин. и макс. элементов» & (Chr(10) & Chr(13)),_
&»j=»&J&»»&»k=»&K, vbInformation,_
«MIN=»&Str(Format(MIN,»fixed»))&»»&»MAX=»&Str(Format(MAX,»fixed»))
‘Конец кода программы
End Sub
|
Berserker_ua 0 / 0 / 0 Регистрация: 22.05.2013 Сообщений: 17 |
||||
|
1 |
||||
Синтаксическая ошибка26.05.2013, 21:17. Показов 8680. Ответов 17 Метки нет (Все метки)
Вформе есть 2 списка (Список8 и Список12). в Списке8 в соответствии с запросом выводит данные поля таблицы (STAT, KODDIAN, KODDIAZ). При двойном клике по Спискок8 в Списке12 должно открытся данные с табллицы MSXK но в строках & «WHERE STAT = » & Forms!Form5!STAT _
__________________
0 |
|
Programming Эксперт 94731 / 64177 / 26122 Регистрация: 12.04.2006 Сообщений: 116,782 |
26.05.2013, 21:17 |
|
17 |
|
81 / 24 / 2 Регистрация: 18.01.2013 Сообщений: 74 |
|
|
26.05.2013, 21:42 |
2 |
|
в строках 31, 32 нужны пробелы, иначе запрос сливается в одну строку & «WHERE STAT = » & Forms!Form5!STAT _
0 |
|
0 / 0 / 0 Регистрация: 22.05.2013 Сообщений: 17 |
|
|
26.05.2013, 21:54 [ТС] |
3 |
|
mcherry, Можно подрбднее? Если вы имеете в виду после » то всё равно не работает.
0 |
|
81 / 24 / 2 Регистрация: 18.01.2013 Сообщений: 74 |
|
|
26.05.2013, 21:56 |
4 |
|
в этой же строке ошибка? когда у меня подобное возникает я в любую свободную ячейку на листе екселя вывожу получившийся запрос (перед его выполнением) и смотрю что там не так, попробуйте и Вы вывести, может где-то еще что-то пропущено….
0 |
|
0 / 0 / 0 Регистрация: 22.05.2013 Сообщений: 17 |
|
|
26.05.2013, 22:12 [ТС] |
5 |
|
я в Access’е пишу, пробовал удалить одну или пару строк всё равно одна и так ошибка Добавлено через 3 минуты
0 |
|
81 / 24 / 2 Регистрация: 18.01.2013 Сообщений: 74 |
|
|
26.05.2013, 22:18 |
6 |
|
тоже синтаксическую ошибку выдает? попробуйте текст запроса выдать в меседж-боксе…
0 |
|
0 / 0 / 0 Регистрация: 22.05.2013 Сообщений: 17 |
|
|
26.05.2013, 22:33 [ТС] |
7 |
|
Не сильно понимаю как это можно осуществить.
0 |
|
81 / 24 / 2 Регистрация: 18.01.2013 Сообщений: 74 |
|
|
26.05.2013, 22:39 |
8 |
|
MsgBox strSQL и будет видно где ошибка в синтаксисе запроса
0 |
|
0 / 0 / 0 Регистрация: 22.05.2013 Сообщений: 17 |
|
|
26.05.2013, 22:55 [ТС] |
9 |
|
Вы имеете в виду записать:
0 |
|
mcherry 81 / 24 / 2 Регистрация: 18.01.2013 Сообщений: 74 |
||||
|
26.05.2013, 23:00 |
10 |
|||
|
нет,
+ не забываем пробелы после » на новой строке с частью запроса
0 |
|
Berserker_ua 0 / 0 / 0 Регистрация: 22.05.2013 Сообщений: 17 |
||||
|
26.05.2013, 23:29 [ТС] |
11 |
|||
|
Измененная строка
и всё равно таже ошибка Добавлено через 2 минуты
0 |
|
81 / 24 / 2 Регистрация: 18.01.2013 Сообщений: 74 |
|
|
26.05.2013, 23:45 |
12 |
|
Проверьте возвращают ли нужные значения Forms!Form5!STAT и Список8.Column(2), пустое сообщение не должно выводиться, т.к. «MsgBox strSQL» выводит содержимое переменной — в данном случае текст запроса
1 |
|
0 / 0 / 0 Регистрация: 22.05.2013 Сообщений: 17 |
|
|
27.05.2013, 00:02 [ТС] |
13 |
|
Благодарю Вас за помощь, надеюсь исправлю как-то это. Если у Вас будет желание не могли б просмотреть этот процесс(Form5)
0 |
|
mcherry 81 / 24 / 2 Регистрация: 18.01.2013 Сообщений: 74 |
||||
|
27.05.2013, 00:18 |
14 |
|||
|
так работает:
в строке был лишний пробел после AND KODDIAZ = ‘ и получалось что запрос выбирает не KODDIAZ=’F051′, а KODDIAZ=’ F051′ и перед формированием строки запроса MsgBox не нужен…
1 |
|
81 / 24 / 2 Регистрация: 18.01.2013 Сообщений: 74 |
|
|
27.05.2013, 00:26 |
15 |
|
вот, поправила:
0 |
|
0 / 0 / 0 Регистрация: 22.05.2013 Сообщений: 17 |
|
|
27.05.2013, 00:36 [ТС] |
16 |
|
Спасибо огромное, но теперь как изменить чтобы в одном из столбцов вторго списка выводилось текст с переменной MSXK.NDIA, просто задача была такая чтобы с первого списка выбрать код диагноза и после двойного нажати во втором выводилась информация про диагноз? Добавлено через 9 минут
0 |
|
81 / 24 / 2 Регистрация: 18.01.2013 Сообщений: 74 |
|
|
27.05.2013, 00:36 |
17 |
|
открыть форму в режиме конструктора, открыть свойства списка 12 (через контекстное меню) и поменять свойство «число столбцов» с 2 на 3.
1 |
|
0 / 0 / 0 Регистрация: 22.05.2013 Сообщений: 17 |
|
|
27.05.2013, 00:45 [ТС] |
18 |
|
да, уведел уже, просто забыл про это) Добавлено через 8 минут
0 |
|
IT_Exp Эксперт 87844 / 49110 / 22898 Регистрация: 17.06.2006 Сообщений: 92,604 |
27.05.2013, 00:45 |
|
Помогаю со студенческими работами здесь Ошибка TNS-01150: Указан неверный адрес имени прослушивателя NL-00303: синтаксическая ошибка в NV-строке
$connection = mysqli_connect(‘127.0.0.1′,’mysql’,’mysql’,’test_db’); if ( $connection… Ошибка анализа: синтаксическая ошибка, неожиданная «ModelBlogArticle» (T_STRING) в /home/u1607/uggitut.ru/www/admin/mode вот выдает ошибку: Parse error: syntax error,…
Искать еще темы с ответами Или воспользуйтесь поиском по форуму: 18 |
I have my code below, the strange thing is that the Errorhandler procedure is still executing even though there are no errors in the code… What can be the issue?
Running the code without any errorhandlers generates no errors, but still the msgbox under Errorhandler shows up when I include an error handling statement!
Code
Public Sub ExportGraphs(Optional PivotExport As Boolean)
' Exports only graphs on the "Mainwindow" sheet to a new worksheet
Dim wsh As Worksheet: Set wsh = Sheets.Add
Dim source_sht As Worksheet: Set source_sht = Sheets("Mainwindow")
ActiveWindow.Zoom = 70
On Error GoTo Errorhandler
With wsh
If source_sht.OLEObjects("Btn_CurrentTime").Object.Value = True Then
.Name = source_sht.OLEObjects("CombBox_Instruments").Object.Value & " " & source_sht.OLEObjects("DTPicker_FROM").Object.Value _
& "-" & source_sht.OLEObjects("DTPicker_TO").Object.Value
Else
.Name = source_sht.OLEObjects("CombBox_Instruments").Object.Value & " " & "Max_Possible_To" _
& "-" & source_sht.OLEObjects("DTPicker_TO").Object.Value
End If
End With
Dim source_chart As ChartObject
Dim target_rng As Range: Set target_rng = wsh.Range("A1")
For Each source_chart In source_sht.ChartObjects
source_chart.CopyPicture xlScreen, xlBitmap
target_rng.PasteSpecial
Set target_rng = target_rng.Offset(20, 0)
Next
If PivotExport = True Then
Debug.Print "se"
End If
Errorhandler:
MsgBox "An export sheet for this ticker and timeline already exists"
End Sub
Chrismas007
6,0554 gold badges23 silver badges47 bronze badges
asked Dec 30, 2014 at 15:35
![]()
1
@dee provided the correct answer.
The Errorhandler: is just a place holder. It does NOT operate like you think. You are using it like an If... Then... statement:
If Error Then
Show MsgBox
Else
Skip MsgBox
End If
As the Errorhandler is just a placeholder and NOT an If... Then..., the code after the placeholder will run regardless of error or no error. To rectify this issue, add an Exit Sub above the Errorhandler: line:
Exit Sub
Errorhandler:
MsgBox "An export sheet for this ticker and timeline already exists"
End Sub
answered Dec 30, 2014 at 16:14
Chrismas007Chrismas007
6,0554 gold badges23 silver badges47 bronze badges
In this piece of code, ErrorHandler: is what is known as a line label.
Errorhandler:
MsgBox "An export sheet for this ticker and timeline already exists"
End Sub
Line labels are not executable code, but rather just a marker that can tell other code where to jump to via any GoTo Statement. Armed with this knowledge, they are obviously not exclusive to error handlers.
The solution here is to use the Exit Statement to return from the Sub «early».
Exit Sub
Errorhandler:
MsgBox "An export sheet for this ticker and timeline already exists"
End Sub
Others may disagree with me, but I like to build my error handling so that the code always stops execution on Exit Sub. If the code ends its execution on End Sub, something has gone wrong.
answered Dec 30, 2014 at 16:35
![]()
RubberDuckRubberDuck
11.4k4 gold badges47 silver badges95 bronze badges
Оператор является синтаксически завершенным, однако дополнительный программный элемент элементом, выполненной инструкции. The statement is syntactically complete, but an additional programming element follows the element that completes the statement. Признак конца строки является обязательным в конце каждой инструкции. A line terminator is required at the end of every statement.
Признак конца строки делит символов файла исходного кода в Visual Basic на строки. A line terminator divides the characters of a Visual Basic source file into lines. Признаки конца строки относятся Юникода каретки возвращаемого символа (& HD), Юникод перевода строки символ (& высокой ДОСТУПНОСТИ), и символ, за которым следует символ перевода строки Юникода возврата каретки Юникода. Examples of line terminators are the Unicode carriage return character (&HD), the Unicode linefeed character (&HA), and the Unicode carriage return character followed by the Unicode linefeed character. Дополнительные сведения о признаки конца строки, см. в разделе спецификация языка Visual Basic. For more information about line terminators, see the Visual Basic Language Specification.
Идентификатор ошибки: BC30205 Error ID: BC30205
Исправление ошибки To correct this error
Установите этот флажок, чтобы увидеть, если два отдельных оператора случайно помещенных в той же строке. Check to see if two different statements have inadvertently been put on the same line.
Вставьте знак завершения строки после элемента, выполняемой инструкции. Insert a line terminator after the element that completes the statement.
Sub Макрос1()
‘
‘ Макрос1 Макрос
‘
‘
‘
Dim a1, a2, n, a, b, c, d
a1 = InputBox(«A1=», «Initial value», -10)
a2 = InputBox(«A2=», «Second value», -9)
n = InputBox(«n=», «Number of points», 20)
a = InputBox(«a=», «The value of a», 0.3)
b = InputBox(«b=», «The value of b», -0.5)
c = InputBox(«c=», «The value of c», 3)
d = InputBox(«d=», «The value of d», 11.5)
Рис. 3.14. Запуск пользовательской формы перед добавлением программного кода
Пора перейти к наиболее пугающему и вместе с тем самому увлекательному этапу программирования в VBA — созданию программного кода. Напомню, что для нашей с вами программы требуется создать две процедуры и что они связаны с событиями, возникающими в процессе выполнения программы. Первая процедура должна при появлении на экране формы отобразить нужное сообщение, а вторая — завершить выполнение программы, когда кто-нибудь щелкнет на кнопке ОК.
Чтобы напечатать связанный с формой или одним из ее элементов управления программный код, вам нужно вместо окна формы открыть окно программного кода этой формы. Для этого выделите форму или элемент управления в ней. Для кнопки ОК это сделать легче всего, так почему бы не начать именно с нее? Щелкните на кнопке ОК, чтобы вокруг нее появились маркеры изменения размеров. Теперь для вызова окна программного кода воспользуйтесь любым из следующих способов.
* Выбрать View=Code из меню.
* Щелкнуть на форме правой кнопкой мыши и в появившемся контекстном меню выбрать View Code.
В появившемся при этом окне программного кода должна уже быть заготовка процедуры (рис. 3.15). VBA автоматически создает процедуру для часто используемого в случае кнопки события — простого щелчка на кнопке. Ваша программа использует эту процедуру, когда кто-нибудь щелкнет на кнопке ОК.
Рис. 3.15. VBA создаст такую заготовку процедуры, как только вы откроете окно программного кода для кнопки ОК
По сути, эти две строки программного кода не делают ничего — они просто определяют рамки, показывающие VBA, где начинается и заканчивается процедура. Первой строкой созданного для вас программного кода будет
Private Sub OKButton_Click()
В любой VBA-процедуре первая строка программного кода определяет тип процедуры (в данном случае это процедура .типа Sub, т.е. подпрограмма) и имя процедуры. Private и Sub относятся к ключевым словам VBA, т.е. к словам и символам, которые являются частью языка VBA. Ключевые слова имеют фиксированные специальные значения в VBA, и вы не можете их использовать в качестве имен таких объектов, как процедуры. Кстати, различные виды процедур в VBA обсуждаются в главе 6. В данном случае VBA предлагает для процедуры имя OKButton_Click, которое представляет собой комбинацию имени кнопки и типа события.
Последней строкой автоматически генерируемого программного кода будет:
Такой строкой должны заканчиваться все процедуры типа Sub. Эта строка сообщает VBA о том. что выполнение процедуры пора завершить.
Добавление своего программного кода
Текстовый курсор будет мигать между этими двумя созданными VBA строками. Напечатав лишь одну дополнительную строку программного кода, мы дадим возможность программе завершить работу. Вот этот программный код:
Оператор Unload убирает указанный объект из памяти. Здесь это объект с именем Me, имеющим в VBA специальный смысл. В данном случае оно означает форму и весь ее программный код.
Исправление ошибок при вводе программного кода
Фигурально выражаясь, всегда, когда вы печатаете программный код, за вашей спиной стоит компилятор VBA. Если компилятор обнаруживает очевидную ошибку, вы немедленно получаете соответствующее сообщение с информацией об ошибке, по крайней мере в общих словах. Предположим, например, что после оператора Unload Me вы напечатали какой-нибудь лишний символ. Компилятор VBA знает, что Unload Me вполне завершенный оператор и за ним в строке больше ничего не должно следовать.
Как только вы переместите точку ввода в следующую строку, компилятор перепишет весь неправильный оператор красным цветом и выделит посторонний символ. Вы получите также сообщение Compile error. Expected: end of statement (Ошибка компиляции. Ожидался конец оператора).
Компилятор может обнаружить далеко не все ошибки, допущенные вами при печатании программного кола. Когда вы запустите программу, компилятор обнаружит и другие ошибки, но о них мы поговорим немного позже.
Вторая процедура, которая должна отображать на экране сообщение, чуть сложнее первой. Эта процедура должна вызываться при появлении формы на экране. В окне программного кода, которое должно у вас остаться активным, выполните следующие шаги.
1. В текстовом поле слева вверху окна программного кода, в котором до сих пор было написано OKButton, щелкните на стрелке в правом конце поля.
После этого откроется список объектов, имеющих отношение к форме (рис. 3.16).
Рис. 3.16. В открывающемся списке объектов перечислены объекты, имеющие отношение к форме, которой принадлежит это окно программного кода
2. Из раскрывающегося списка выберите UserForm.
VBA создаст новую процедуру для события Click (щелчок). Эта процедура будет вызвана, если пользователь вашей программы щелкнет кнопкой мыши в любом месте фермы, где нет элементов управления. Нашей с вами программе такая процедура не нужна, поэтому пока оставьте ее.
3. Теперь щелкните на стрелке в конце текстового поля, находящегося справа, чтобы открыть список процедур, в котором будут перечислены все события, которые VBA распознает для объекта UserForm.
Этот список достаточно велик, что дает вам возможность сделать свою программу чуткой практически настолько, насколько захотите (рис. 3.17).
Рис. 3.17. В списке процедур представлены события, которые будут для активного в данный момент объекта
4. Выберите Activate — самый первый пункт в списке. Чтобы увидеть этот пункт, вам придется пролистать список.
VBA добросовестно создаст заготовку процедуры UserForm_Activate, которая вызывается при загрузке формы в память.
5. Если вас раздражает пустая процедура UserForm_Click, удалите ее, выделив весь ее текст и нажав клавишу Del.
Этот шаг не обязателен — соответствующий программный код не принесет никакого вреда. Но из-за того, что этот программный код не делает ничего полезного, а только отвлекает, можете смело прервать его одинокую жизнь.
Поскольку заготовка процедуры и в этом случае, как всегда, создается автоматически, вы сразу можете сосредоточиться на ее наполнении. Между строками, которые любезно предложены вам VBA, напечатайте еще три строки кода. Результат должен выглядеть следующим образом:
Dim Quote As String Quote = Не повторяется такое никогда:
lblNow.Caption = Quote Format(Now, dddddd, hh ч. mm мин.)
Первая из напечатанных вами строк
Dim Quote As String
создает переменную с именем Quote и определяет ее как строковую, что означает последовательность текстовых символов.
Quote = Не повторяется такое никогда:
сохраняет текст Не повторяется такое никогда: в только что созданной переменной Quote. Точно так же, как на уроках алгебры в школе, вы здесь используете знак равенства, чтобы приписать определенное значение переменной. Обратите внимание на то, что VBA перед закрывающими кавычками добавлен пробел, чтобы отделить текст сообщения от следующего за ним текста.
lblNow.Caption = Quote Format(Now, dddddd, hh ч. mm мин.)
содержит программный код, который непосредственно отображает нужное сообщение в форме. Эта строка начинается с идентификации элемента управления с именем lblNow как объекта, с которым идет работа. После имени стоит точка, означающая, что далее идет свойство объекта lblNow — в данном случае это свойство Caption. Вообще любое свойство подобно переменной, и его можно изменить во время выполнения программы. Поэтому, чтобы изменить установки свойства, в программном коде используется знак равенства. Оставшаяся часть строки определяет сообщение, которое должно появиться на экране в виде надписи.
Первой частью сообщения является переменная Quote. Следующий затем знак плюс дает указание VBA добавить то, что следует дальше, к тексту, хранящемуся в переменной Quote. В скобках функция Now говорит VBA, что нужно сбегать и узнать текущие показания часов компьютера, которые постоянно отсчитывают дату и время. Затем функция Format берет эту сырую информацию и представляет ее в виде, который сможете прочитать вы. Странный набор букв в кавычках как раз и определяет вил даты и времени на экране, но здесь я не собираюсь вдаваться в детальные объяснения по этому поводу — подробную информацию вы найдете в главе 11.
Избегание условий ошибки
Когда возникает ошибка времени выполнения, хороший код должен ее обрабатывать. Лучшей стратегией обработки ошибок является запись кода, который проверяет условия ошибки и просто избегает выполнения кода, который приводит к ошибке выполнения.
Одним из ключевых элементов сокращения ошибок во время выполнения является запись небольших процедур, которые делают одно . Чем меньше процедур процедур приходится терпеть неудачу, тем проще код в целом — отлаживать.
Избежать ошибки времени выполнения 91 — Объект или С заблокированной переменной блока:
Эта ошибка будет повышена, если объект используется до назначения ссылки. Возможно, у вас есть процедура, которая получает параметр объекта:
Private Sub DoSomething(ByVal target As Worksheet)
Debug.Print target.Name
End Sub
Если target не назначена ссылка, приведенный выше код вызовет ошибку, которую легко избежать, проверяя, содержит ли объект фактическую ссылку на объект:
Private Sub DoSomething(ByVal target As Worksheet)
If target Is Nothing Then Exit Sub
Debug.Print target.Name
End Sub
Если target назначению не присвоена ссылка, то непризнанная ссылка никогда не используется, и ошибка не возникает.
Этот способ раннего выхода из процедуры, когда один или несколько параметров недопустимы, называется предложением охраны .
Избегайте ошибки времени выполнения 9 — Подкласс вне диапазона:
Эта ошибка возникает при доступе к массиву за пределами его границ.
Private Sub DoSomething(ByVal index As Integer)
Debug.Print ActiveWorkbook.Worksheets(index)
End Sub
Учитывая, что индекс больше, чем количество листов в ActiveWorkbook , приведенный выше код вызовет ошибку времени выполнения. Простое предложение охраны может избежать этого:
Private Sub DoSomething(ByVal index As Integer)
If index > ActiveWorkbook.Worksheets.Count Or index <= 0 Then Exit Sub
Debug.Print ActiveWorkbook.Worksheets(index)
End Sub
Большинство ошибок времени выполнения можно избежать, тщательно проверив значения, которые мы используем, прежде чем мы их используем, и разветвляемся на другом пути выполнения, соответственно, используя простой оператор If — в сторожевых предложениях, который не делает предположений и не проверяет параметры процедуры, или даже в тело более крупных процедур.
Оператор Error
Даже с защитными пунктами, один не может реально всегда учитывать все возможные ошибки , которые могут быть подняты в теле процедуры. Оператор On Error GoTo инструктирует VBA перейти к метке линии и ввести «режим обработки ошибок» всякий раз, когда во время выполнения происходит непредвиденная ошибка. После обработки ошибки, код может возобновить обратно в «нормальное» исполнение с помощью Resume ключевое слово.
Линейные метки обозначают подпрограммы : потому что подпрограммы исходят из устаревшего кода BASIC и используют GoSub GoTo и GoSub и Return чтобы вернуться к «основной» процедуре, довольно легко написать жесткий код спагетти, если все не строго структурировано , По этой причине лучше всего:
- процедура имеет одну и только одну подпрограмму обработки ошибок
- подпрограмма обработки ошибок работает только в состоянии ошибки
Это означает, что процедура, которая обрабатывает его ошибки, должна быть структурирована следующим образом:
Private Sub DoSomething()
On Error GoTo CleanFail
'procedure code here
CleanExit:
'cleanup code here
Exit Sub
CleanFail:
'error-handling code here
Resume CleanExit
End Sub
Стратегии обработки ошибок
Иногда вы хотите обрабатывать разные ошибки с помощью разных действий. В этом случае вы будете проверять глобальный объект Err , который будет содержать информацию об ошибке, которая была поднята, и действовать соответственно:
CleanExit:
Exit Sub
CleanFail:
Select Case Err.Number
Case 9
MsgBox "Specified number doesn't exist. Please try again.", vbExclamation
Resume
Case 91
'woah there, this shouldn't be happening.
Stop 'execution will break here
Resume 'hit F8 to jump to the line that raised the error
Case Else
MsgBox "An unexpected error has occurred:" & vbNewLine & Err.Description, vbCritical
Resume CleanExit
End Select
End Sub
В качестве общего руководства рассмотрите возможность включения обработки ошибок для всей подпрограммы или функции и обработайте все ошибки, которые могут возникнуть в пределах ее области действия. Если вам нужно обрабатывать ошибки только в секции небольшого сечения кода — включить и выключить обработку ошибок на одном уровне:
Private Sub DoSomething(CheckValue as Long)
If CheckValue = 0 Then
On Error GoTo ErrorHandler ' turn error handling on
' code that may result in error
On Error GoTo 0 ' turn error handling off - same level
End If
CleanExit:
Exit Sub
ErrorHandler:
' error handling code here
' do not turn off error handling here
Resume
End Sub
Номера строк
VBA поддерживает номера строк в стиле legacy (например, QBASIC). Скрытое свойство Erl можно использовать для идентификации номера строки, которая вызвала последнюю ошибку. Если вы не используете номера строк, Erl только вернет 0.
Sub DoSomething()
10 On Error GoTo 50
20 Debug.Print 42 / 0
30 Exit Sub
40
50 Debug.Print "Error raised on line " & Erl ' returns 20
End Sub
Если вы используете номера строк, но не последовательно, а затем Erl возвращает номер последней строки перед командой, вызвавшей ошибку.
Sub DoSomething()
10 On Error GoTo 50
Debug.Print 42 / 0
30 Exit Sub
50 Debug.Print "Error raised on line " & Erl 'returns 10
End Sub
Имейте в виду, что Erl также имеет только Integer точность и будет бесшумно переполняться. Это означает, что номера строк за пределами целочисленного диапазона дадут неверные результаты:
Sub DoSomething()
99997 On Error GoTo 99999
99998 Debug.Print 42 / 0
99999
Debug.Print Erl 'Prints 34462
End Sub
Номер строки не так актуален, как утверждение, вызвавшее ошибку, и строки нумерации быстро становятся утомительными и не совсем удобны в обслуживании.
Резюме ключевого слова
Подпрограмма обработки ошибок будет либо:
- выполняются до конца процедуры, и в этом случае выполнение возобновляется в процедуре вызова.
- или используйте ключевое слово
Resumeдля возобновления выполнения внутри той же процедуры.
Ключевое слово Resume должно использоваться только в подпрограмме обработки ошибок, потому что если VBA встречает Resume не находясь в состоянии ошибки, возникает ошибка времени выполнения 20 «Возобновить без ошибок».
Существует несколько способов, по которым подпрограмма обработки ошибок может использовать ключевое слово Resume :
-
Resumeиспользуется отдельно, выполнение продолжается в инструкции, вызвавшей ошибку . Если ошибка на самом деле не обрабатывается , прежде чем делать это, то та же ошибка будет поднят снова, и выполнение может войти в бесконечный цикл. -
Resume Nextпродолжает выполнение инструкции сразу после инструкции, вызвавшей ошибку. Если ошибка на самом деле не обрабатывается , прежде чем делать это, то выполнение разрешается продолжать с потенциально недействительными данными, которые могут привести к логическим ошибкам и неожиданному поведению. -
Resume [line label]продолжает выполнение на указанной метке строки (или номер строки, если вы используете номера строк в стиле устаревшего стиля). Обычно это позволяет выполнить некоторый код очистки до того, как будет чисто выйти из процедуры, например, чтобы закрыть соединение с базой данных, прежде чем вернуться к вызывающему.
Вкл.
Сам оператор On Error может использовать ключевое слово Resume чтобы проинструктировать среду выполнения VBA для эффективного игнорирования всех ошибок .
Если ошибка не выполняется до этого, то выполнение разрешено продолжать с потенциально недействительными данными, что может привести к логическим ошибкам и неожиданному поведению .
Вышеупомянутый акцент не может быть особо подчеркнут. On Error Resume Next эффективно игнорирует все ошибки и выталкивает их под ковер . Программа, которая взрывается с ошибкой во время выполнения с учетом недопустимого ввода, — это более эффективная программа, чем программа, которая работает с неизвестными / непреднамеренными данными — будь то только потому, что ошибка намного легче идентифицируется. On Error Resume Next можно легко скрыть ошибки .
Оператор On Error является областью действия процедур — поэтому в данной процедуре обычно должен быть только один , такой оператор On Error .
Однако иногда не удается избежать ошибки, и переключение на подпрограмму обработки ошибок только на Resume Next просто не кажется правильным. В этом конкретном случае утверждение с известным до невозможности может быть обернуто между двумя On Error :
On Error Resume Next
[possibly-failing statement]
Err.Clear 'resets current error
On Error GoTo 0
Команда On Error GoTo 0 сбрасывает обработку ошибок в текущей процедуре, так что любая дополнительная инструкция, вызывающая ошибку времени выполнения , будет необработанной внутри этой процедуры и вместо этого будет переходить в стек вызовов до тех пор, пока она не будет захвачена активным обработчиком ошибок. Если в стеке вызовов нет активного обработчика ошибок, он будет рассматриваться как необработанное исключение.
Public Sub Caller()
On Error GoTo Handler
Callee
Exit Sub
Handler:
Debug.Print "Error " & Err.Number & " in Caller."
End Sub
Public Sub Callee()
On Error GoTo Handler
Err.Raise 1 'This will be handled by the Callee handler.
On Error GoTo 0 'After this statement, errors are passed up the stack.
Err.Raise 2 'This will be handled by the Caller handler.
Exit Sub
Handler:
Debug.Print "Error " & Err.Number & " in Callee."
Resume Next
End Sub
Пользовательские ошибки
Часто при написании специализированного класса вы хотите, чтобы он поднимал свои собственные конкретные ошибки, и вам понадобится чистый способ для кода пользователя / вызова для обработки этих пользовательских ошибок. Оптимальным способом достижения этого является определение специального типа Enum :
Option Explicit
Public Enum FoobarError
Err_FooWasNotBarred = vbObjectError + 1024
Err_BarNotInitialized
Err_SomethingElseHappened
End Enum
Используя встроенную константу vbObjectError пользовательские коды ошибок не перекрываются с зарезервированными / существующими кодами ошибок. Необходимо явно указать только первое значение перечисления, поскольку базовое значение каждого члена Enum 1 больше, чем предыдущий элемент, поэтому базовое значение Err_BarNotInitialized неявно является vbObjectError + 1025 .
Повышение собственных ошибок времени выполнения
Ошибка выполнения может быть повышена с Err.Raise оператора Err.Raise , поэтому пользовательская ошибка Err_FooWasNotBarred может быть повышена следующим образом:
Err.Raise Err_FooWasNotBarred
Метод Err.Raise также может принимать пользовательские параметры Description и Source — по этой причине рекомендуется также определять константы для хранения каждого пользовательского описания ошибки:
Private Const Msg_FooWasNotBarred As String = "The foo was not barred."
Private Const Msg_BarNotInitialized As String = "The bar was not initialized."
А затем создайте выделенный частный метод для повышения каждой ошибки:
Private Sub OnFooWasNotBarredError(ByVal source As String)
Err.Raise Err_FooWasNotBarred, source, Msg_FooWasNotBarred
End Sub
Private Sub OnBarNotInitializedError(ByVal source As String)
Err.Raise Err_BarNotInitialized, source, Msg_BarNotInitialized
End Sub
После этого реализация класса может просто вызвать эти специализированные процедуры для повышения ошибки:
Public Sub DoSomething()
'raises the custom 'BarNotInitialized' error with "DoSomething" as the source:
If Me.Bar Is Nothing Then OnBarNotInitializedError "DoSomething"
'...
End Sub
Клиентский код может обрабатывать Err_BarNotInitialized как и любую другую ошибку, внутри своей собственной подпрограммы обработки ошибок.
Примечание: наследие Error ключевое слово также может быть использован вместо Err.Raise , но это устаревшее / осуждается.
Ошибка разбора: синтаксическая ошибка, неожиданный ‘а’ (T_WHILE) в C:OSPaneldomainsTest.ruindex.php на линии 15