Must be first statement on the line vba ошибка

Permalink

Cannot retrieve contributors at this time

title keywords f1_keywords ms.prod ms.assetid ms.date ms.localizationpriority

Must be first statement on the line

vblr6.chm1040049

vblr6.chm1040049

office

5aa6b5a6-27ed-7825-f204-20b9697f25f3

06/08/2017

medium

Not all keywords can appear at the beginning of a line of code. This error has the following causes and solutions:

  • You preceded a Sub, Function, or Property statement with another statement on the same line. A Sub, Function, or Property statement must always be the first statement on any line in which it appears (unless preceded by the keyword Public, Private, or Static).

  • You preceded an End If, Else, or ElseIf statement with another statement on the same line. An End If, Else, or ElseIf (only when used in a block If structure) statement must always be the first statement on any line in which it appears.

For additional information, select the item in question and press F1 (in Windows) or HELP (on the Macintosh).

[!includeSupport and feedback]

Пользовательское соглашение

Политика конфиденциальности

© Николай Павлов, Planetaexcel, 2006-2023
info@planetaexcel.ru


Использование любых материалов сайта допускается строго с указанием прямой ссылки на источник, упоминанием названия сайта, имени автора и неизменности исходного текста и иллюстраций.

Техническая поддержка сайта

ООО «Планета Эксел»

ИНН 7735603520


ОГРН 1147746834949
        ИП Павлов Николай Владимирович
        ИНН 633015842586
        ОГРНИП 310633031600071 



    • #1
    Function UpdatedSymbol(Symbol As String) As String
        If Len(Symbol) = 4 Then
            UpdatedSymbol = Symbol
        Else If Len(Symbol) = 0 Then 'this is the line which produces the error
            UpatedSymbol = Symbol
        Else
            UpdatedSymbol = Left(Symbol, 3) & Right(Symbol, 1)
        End If
        
    End Function

    What is wrong with this code? I am getting a Compile Error: Must be first statement on the line.

    I have checked and rechecked and it seems right but it does not work. I have tried different values, swapped the 4 and the 0 but nothing works.

    Any thoughts?

    • #2

    Re: If…Else If…Compile Error

    Should be no space in between ElseIf

    Function UpdatedSymbol(Symbol As String) As String
        If Len(Symbol) = 4 Then
            UpdatedSymbol = Symbol
        ElseIf Len(Symbol) = 0 Then 'this is the line which produces the error
            UpatedSymbol = Symbol
        Else
            UpdatedSymbol = Left(Symbol, 3) & Right(Symbol, 1)
        End If
        
    End Function
    • #3

    Re: If…Else If…Compile Error

    SMH thank you! I knew it was something like that.

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


Here you’ll find all the error codes associated with VBScript along with the Err object.

Runtime Errors

Runtime errors occur wherever your script attempts to perform an invalid action. The vast majority of these errors should be caught during the debugging and testing stage. VBScript contains 43 runtime errors, which are listed in the following table with their decimal and hexadecimal representations.

Decimal Hexadecimal Description

5

800A0005

Invalid procedure call or argument

6

800A0006

Overflow

7

800A0007

Out of memory

9

800A0009

Subscript out of range

10

800A000A

This array is fixed or temporarily locked

11

800A000B

Division by zero

13

800A000D

Type mismatch

14

800A000E

Out of string space

17

800A0011

Can’t perform requested operation

28

800A001C

Out of stack space

35

800A0023

Sub or Function not defined

48

800A0030

Err in loading DLL

51

800A0033

Internal error

91

800A005B

Object variable not set

92

800A005C

For loop not initialized

94

800A005E

Invalid use of Null

424

800A01A8

Object required

429

800A01AD

ActiveX component can’t create object

430

800A01AE

Class doesn’t support Automation

432

800A01B0

File name or class name not found during Automation operation

438

800A01B6

Object doesn’t support this property or method

445

800A01BD

Object doesn’t support this action

447

800A01BF

Object doesn’t support current locale setting

448

800A01C0

Named argument not found

449

800A01C1

Argument not optional

450

800A01C2

Wrong number of arguments or invalid property assignment

451

800A01C3

Object not a collection

458

800A01CA

Variable uses an Automation type not supported in VBScript

462

800A01CE

The remote server machine does not exist or is unavailable

481

800A01E1

Invalid picture

500

800A01F4

Variable is undefined

502

800A01F6

Object not safe for scripting

503

800A01F7

Object not safe for initializing

504

800A01F8

Object not safe for creating

505

800A01F9

Invalid or unqualified reference

506

800A01FA

Class not defined

507

800A01FB

An exception occurred

5008

800A1390

Illegal assignment

5017

800A1399

Syntax error in regular expression

5018

800A139A

Unexpected quantifier

5019

800A139B

Expected ² ] ² in regular expression

5020

800A139C

Expected ² ] ² in regular expression

5021

800A139D

Invalid range in character set

Syntax Errors

Syntax errors occur wherever your script contains statements that do not follow the pre-defined rules for that language. This type of error should be caught during development. VBScript contains 49 syntax errors, listed in the following table with their decimal and hexadecimal representations.

Decimal Hexadecimal Description

1001

800A03E9

Out of memory

1002

800A03EA

Syntax error

1005

800A03ED

Expected ²( ²

1006

800A03EE

Expected ²) ²

1010

800A03F2

Expected identifier

1011

800A03F3

Expected ²= ²

1012

800A03F4

Expected ²If ²

1013

800A03F5

Expected ²To ²

1014

800A03F6

Expected ²End ²

1015

800A03F7

Expected ²Function ²

1016

800A03F8

Expected ²Sub ²

1017

800A03F9

Expected ²Then ²

1018

800A03FA

Expected ²Wend ²

1019

800A03FB

Expected ²Loop ²

1020

800A03FC

Expected ²Next ²

1021

800A03FD

Expected ²Case ²

1022

800A03FE

Expected ²Select ²

1023

800A03FF

Expected expression

1024

800A0400

Expected statement

1025

800A0401

Expected end of statement

1026

800A0402

Expected integer constant

1027

800A0403

Expected ²While ² or ²Until ²

1028

800A0404

Expected ²While ², ²Until ², or end of statement

1029

800A0405

Expected ²With ²

1030

800A0406

Identifier too long

1013

800A0407

Invalid number

1014

800A0408

Invalid character

1015

800A0409

Unterminated string constant

1034

800A040A

Unterminated comment

1037

800A040D

Invalid use of ²Me ² keyword

1038

800A040E

²loop ² without ²do ²

1039

800A040F

Invalid ²exit ² statement

1040

800A0410

Invalid ²for ² loop control variable

1041

800A0411

Name redefined

1042

800A0412

Must be first statement on the line

1044

800A0414

Cannot use parentheses when calling a Sub

1045

800A0415

Expected literal constant

1046

800A0416

Expected ²In ²

1047

800A0417

Expected ²Class ²

1048

800A0418

Must be defined inside a Class

1049

800A0419

Expected Let or Set or Get in property declaration

1050

800A041A

Expected ²Property ²

1051

800A041B

Number of arguments must be consistent across properties specification

1052

800A041C

Cannot have multiple default property/method in a Class

1053

800A041D

Class initialize or terminate do not have arguments

1054

800A041E

Property Set or Let must have at least one argument

1055

800A041F

Unexpected ²Next ²

1057

800A0421

²Default ² specification must also specify ²Public ²)

1058

800A0422

²Default ² specification can only be on Property Get

The Err Object

Errors usually make their way into code and as such it’s important to be able to spot them and remove them. At the core of this is error handling using the Err object.

Let’s take a quick tour of the Err object and the On Err statement and look at ways to make use of them in VBScript code.

Err Object

The Err object is the heart and soul of error handling in VBScript, and exposes information about runtime errors through its properties. Unlike other objects in VBScript, it is an intrinsic object with global scope; hence, there is no need to declare and initialize the Err object.

Initially the Err properties are either zero-length strings or , and when a runtime error occurs the properties of the Err object get populated by the generator of the error (e.g. VBScript, an Automation object, or by the programmer). Err.Number contains an integer, and Number is the default property of the Err object. It is easy to test whether the error actually occurred with an If ErrThen statement because of automatic conversion between integer and Boolean subtypes : the integer (no error) converts to Boolean False , and all other numbers evaluate to True .

The following example illustrates a partial IE VBScript (although it could just as easily be from a .wsc , or .hta file) in which the programmer raises one of the predefined VBScript errors. Note that the Err object is not declared and it cannot be created as a separate object.

 

Err Object Properties

Let’s take a look at the Err object properties.

Description

The Description property returns or sets a descriptive string associated with an error. By default this is a zero-length string until the property is set by the programmer or by the generator of an error. The description is useful when displaying or logging errors and when raising custom errors. If the programmer raises one of the default runtime errors, the Description property contains the string associated with the error.

Syntax


Err.Description [= stringexpression]


Name Subtype Description

Err

Err Object

This is always the Err Object

Stringexpression

String

A string expression containing a description of the error

Example Usage

 

This sample script will produce Variable in undefined inside a message box.

HelpContext

The HelpContext property is used to automatically display the Help topic specified in the HelpFile property. This property either sets or retrieves the value of the help context. If both HelpFile and HelpContext are empty, the value of Number is checked. If

Number corresponds to a VBScript runtime error value, then the VBScript help context ID for the error is used.

This property is rarely used, and requires coordination between the person authoring the Help system and the scripter.

Finally, use of the HelpFile and HelpContext only make sense in a non-IE setting with the older .hlp system. Newer HTML help simply uses HTML documents, which may be displayed under most circumstances using techniques discussed in HTML Help manuals.

The following sample illustrates the use of the traditional .hlp files with the Windows Script Host.

Syntax


Err.HelpContext [= contextID]


Name Subtype Description

Err

Err Object

This always is the Err Object

ContextID

Integer

Optional. A valid identifier for a Help topic within the Help file

Example Usage


On Error Resume Next




Dim Msg




Err.Clear




Err.Raise 6 Generate Overflow error.




Err.Helpfile = c:  windows help yourHelp.hlp




Err.HelpContext = 21




If Err.Number <> 0 Then




Msg = Press Help to see & Err.Helpfile & topic for & _




the following HelpContext: & Err.HelpContext




MsgBox Msg, , error: & Err.Description, Err.Helpfile, Err.HelpContext




End If


HelpFile

The HelpFile property is used to set and retrieve a fully qualified path to a programmer- authored Help File. Often it is used in conjunction with the HelpContext property-see the notes and the earlier example. The most common way of setting the value is through the Err.Raise method.

Syntax


Err.HelpFile [= filepath]


Name Subtype Description

Err

Err Object

This always is the Err Object

Filepath

String

Optional. Fully qualified path to the Help File

Number

This is the default property of the Err object, and returns or sets a numeric value specifying an error. Custom error handling functions utilize the Number property to diagnose the runtime error.

When setting or retrieving a custom error, the vbObjectErr constant is used to ensure that custom errors do not conflict with VBScript and common Automation Errs .

Syntax


Err.Number [= errornumber]


Name Subtype Description

Err

Err Object

This is always the Err Object

Errornumber

Integer

An integer representing a VBScript error number or an SCODE error value. SCODE is a long integer value that is used to pass detailed information to the caller of an interface member or API function

Example Usage


On Error Resume Next




Err.Raise vbObjectError + 16, ,CustomObject Error Raise Custom Error #16.




If Err.Number <> 0 Then (If Err Then) can be used too




MsgBox (Error # & CStr(Err.Number) & & Err.Description)




End If


The preceding sample code sets a custom error number in Err.Number through the Err.Raise method, and then displays the return value through a Message Box ( MsgBox ).

Source

The Source property sets or returns the name of the object or application that reported the error. Most commonly the source is the class name or ProgID of the object generating the error.

Most of the time the Source property will show ³Microsoft VBScript ³, but in cases where the error occurs while accessing a property or method of an Automation object, the source property will show the component’s class name. This is not only useful because it allows for a greater degree of granularity (or visibility) in error handling, but it also allows for better error display and logging possibilities. This property can be set through the Err.Raise method in both VBScript and in custom COM components .

Syntax


Err.Source [= stringexpression]


Name Subtype Description

Err

Err Object

This always is the Err Object

Stringexpression

Integer

A string expression representing the application that generated the error

Example Usage


On Error Resume Next




Err.Raise vbObjectError + 1, cTestClass, CustomObject Error




If Err.Number <> 0 Then (If Err Then) can be used too




MsgBox (Error # & CStr(Err.Number) & & Err.Description & Source: & Err.Source)




End If


Err Object Methods

Let ²s take a look at the Err object methods.

Clear

The Clear method resets all of the properties of the Err object to either or a zero-length string. The Err object should ideally be reset after an error has been handled because of the deferred nature of error handling in VBScript, to avoid the potential mistake of handling the same error twice.

The Err object is additionally cleared by any of the following statements:

  • On Error Resume Next
  • On Error Goto
  • Exit Sub
  • Exit Function

Therefore, error-handling functions must be called before any of the preceding statements are executed.

Syntax


Err.Clear


Name Subtype Description

Err

Err Object

This always is the Err Object

Example Usage


On Error Resume Next The Err Object is Reset




Err.Raise 5




Err.Clear




If Err.Number = 0 Then (If Err Then) can be used too




MsgBox (Error has been reset: Err.Number - & CStr(Err.Number))




End If


Raise

The Raise method generates a runtime error. All of the parameters of the Raise method, except for its number, are optional. When optional parameters are not specified, and the Err object has not been cleared, old values may appear.

The best practice is to use Err.Clear after error handling, and to inspect the Err object before using Err.Raise (in case an error has occurred in the meantime). When raising custom error numbers, the vbObjectErr constant should be added.

The HelpFile and HelpContext parameters are used with the traditional .hlp help, and not with the HTML help systems.

Raising errors is a popular technique to stop the execution of a procedure, and handle it via some error handling function. You may raise errors when data is invalid, and when you want to pass an error up the call stack. This is a popular technique when you want to change one error into another, so that it can be handled properly.

Syntax


Err.Raise (number, source, description, helpfile, helpcontext)


Name Subtype Description

Err

Err Object

This is always the Err Object

Number

Long

This identifies the nature of the error. All VBScript (predefined and user -defined) error numbers are in the range 0-65535

Source

String

This identifies the name of the object or application that generates the error. When setting this property for Windows Script Components, use the ProgID form.

If nothing is specified, the current ID of the project is used; often, it just defaults to ²Microsoft VBScript ²

Description

String

This is the description of the error. If unspecified, the value in number is examined. If it can be mapped to a VBScript runtime error code, a string provided by VBScript is used as the description. If there is no VBScript error corresponding to number, a generic error message is used

Helpfile

String

This is the fully qualified path to a customized help file in which help on this error can be found. If unspecified, VBScript uses the fully qualified drive, path, and file name of the VBScript help file

Helpcontext

Integer

This is the context ID identifying a topic within helpfile that provides help for the error. If omitted, the VBScript help file context ID for the error corresponding to the number property is used, if it exists

Example Usage


Dim strMsg




On Error Resume Next




Err.Raise vbObjectError + 1, prjProject.clsClass, Custom Error,




c: windowsYourHelpfile.hlp, 1




If Err.Number <> 0 Then




strMsg = Error Number: & CStr(Err.Number) & vbCrLf




strMsg = strMsg & Description: & Err.Description & vbCrLf




strMsg = strMsg & Source: & Err.Source




If Err.HelpFile <> Then




strMsg = strMsg & vbCrLf & Press Help to see the help file




MsgBox strMsg, , Error: & Err.Description, Err.Helpfile, Err




.HelpContext




End If




MsgBox strMsg No Help file available here




Err.Clear




End If


This example shows a common way of raising an error in Windows Script Host, where the help file is readily available.

vbObjectError Constant

This is a built-in constant that can be used in conjunction with programmer-defined errors and Err.Raise . It does not have to be declared or initialized ; its decimal value is -2147221504 (or -0 (8004000 in hexadecimal). Whereas previous examples have shown how to use the vbObjectError constant with the Err.Raise method, the following example shows a skeleton of a centralized error handler that combines Select Case with custom errors.

Example Usage


If Err.Number <> 0 Then this should call separate subs




Select Case Err.Number




Case vbObjectError + 1




call sub handling error 1




Case vbObjectError + 3




call sub handling error 3




Case Else




call reporting sub to display errors




End Select




End If


On Error Resume Next

This statement enables error handling within the scope of a script or a procedure. Without the On Error Resume Next statement, the default runtime error handler displays the error and stops the execution of the script.

On Error Resume Next continues the execution of the script on the next line following the error. The error handling routine has to exist within the same scope as this statement. The statement becomes inactive with a call to another procedure or when an On Error Goto statement is used.

Syntax


On Error Resume Next


Tip  

When Internet Explorer’s advanced option Disable Script Debugging is not selected and the Script Debugger is installed on the same system, On Error Resume Next does not go into effect; instead, the browser automatically goes into the ³debug ³ mode. So, when testing the effectiveness of your error handler through Internet Explorer, make sure that this option is selected.

On Error Goto 0

The On Error Goto statement disables the error handling that was enabled by On Error Resume Next . This statement is especially useful in the testing stage, when there is a need to identify certain errors and yet handle others. On Error Goto can be placed immediately after the error handling procedure is called.

Like On Error Resume Next , this statement is also scope dependent.

Syntax


On Error Goto 0


Scope of On Error Statement and Differences Between VBScript’s and VBs (or VBAs) Error Handling

It is important to understand the scope of the On Error statement; otherwise your error handling procedures may never execute. VBScript-unlike its parent language-does not support labels, and it does not support the VB On Error Goto label. Thus, VBScript provides support only for in-line error handlers that can cause understandable grief . Basically, in order to mimic a block of code in VB that would respond to an On Error Goto label statement you might be inclined to use several If Err Then statements in order to check for an error with each single line of execution. However, with a little bit of programming, this can easily be achieved by enabling an error handler around a given procedure. Should one of the lines in the procedure fail, the error can be thrown up the calling stack. Of course, there is no Resume statement, which complicates some of the scripting. This can only be circumvented by trying to correct the problem that generated the error and attempting to call the procedure again.

Before we look at some error handling techniques, let’s examine the scope of error handling. The following script illustrates an important concept behind the scope of the error-enabling and error-disabling statements, as well as showing the differences in scope and the importance in clearing of errors.


Sub TestError()




On Error Resume Next




Err.Raise 6 Execution will continue




MsgBox (TestError: Error # & CStr(Err.Number) & & Err.Description)




Err.Clear




End Sub




Sub TestError2()




Err.Clear Execution stops, moves up in scope




MsgBox (TestError2: This will never Show Up)




End Sub




Main body of the script




TestError() has local Error Handler no need for global Handler




On Error Resume Next




Call TestError()




If Err.Number <> 0 Then




MsgBox (Global: Error # & CStr(Err.Number) & & Err.Description)




Err Clear




Else




MsgBox (Global: No Error, It was handled locally and cleared)




End If




TestError2 has no local error handler




Call TestError2()




If Err.Number <> 0 Then




MsgBox (Global: Error # & CStr(Err.Number) & & Err.Description)




Err.Clear




End If




Global script Error handling is turned off, cause crash




On Error goto 0




Call TestError2()


Upon execution, the error is first handled locally, and after it is cleared, it is ignored. Next, the calls to the Test Error2() subroutine are first handled by the global error handler and, after it is disabled on the second-last line, a runtime error appears.

Now, to consider the importance of clearing errors and the scope of On Error Resume Next , we make two adjustments, commenting out certain code.


Sub TestError()




On Error Resume Next




Err.Raise 6 Execution will continue




MsgBox (TestError: Error # & CStr(Err.Number) & & Err.Description)




REM Err.Clear




End Sub




Sub TestError2()




Err.Clear Execution stops, moves up in scope




MsgBox (TestError2: This will never Show Up)




End Sub




Main body of the script




TestError() has local Error Handler no need for global Handler




REM On Error Resume Next


With these changes, an error message is still displayed after the call to TestError() , but the first call to the TestError2() subprocedure results in an invocation of the default error handler, and stoppage of the script immediately after the call, that is, the On Error Resume Next statement was local in scope to the TestError() subprocedure.

The following code illustrates the possibility of mimicking the On Error Goto label statement by encompassing a block of code in a procedure, rather than trapping errors inline, as in VB. Here the scripter can invoke an error handler at a higher level rather than at the level where the error occurred (in this case, a procedure without a local error handler).


Option Explicit




Dim intZero, intNonZero, intResult




intZero = 0




intNonZero = 1




Sub TestError()




Statements that will execute




MsgBox (This will always execute)




now cause an error




intResult = intNonZero / intZero causes error 11




Statements that will not execute if error occurs




MsgBox (Finally executed, Result = & CStr(intResult))




End Sub




simulate On Error Goto Label by having a block of code in a sub




On Error Resume Next




Call TestError()




If Err.Number = 11 Then




MsgBox Division By Zero - may still continue & vbCrLf & Err.Description




Err.Clear




intZero = 1




TestError()




End If




On Error Goto 0 kill other error handling


Error Handling in Internet Explorer

Besides VBScript itself, some Web authors might also turn to DHTML events. Internet Explorer’s DHTML object model supports a variety of events, including events occurring as a result of an error. Essentially, this allows for a different degree of control when authoring scripts for IE. Thanks to the GetRef() function, which returns a pointer to a function, it is now possible to bind VBScript procedures to an event.

For instance, the following line will execute the RunMySub procedure in response to the Window .Onload event in IE.


Set Window.Onload = GetRef(RunMySub)


Similarly, you can write procedures that will execute when the OnError event is fired , either for an element or for the window object.

There are two additional techniques for error handling in IE:

  • Centralized, through the use of the window.onerror event
  • Decentralized, through the use of the element.onerror event

The following code example illustrates the old and the new syntax for handling DHTML errors.

Old Syntax


Function element_onerror (message, url, line)


element is the name of the element or window.

 

New Syntax


Set element.onerror = GetRef(functionName)


The new syntax allows us to bind functions to events, just like in JScript. Again, element is the name of the element or window, and functionName is an actual function or a sub.

 

There are a few important differences between the VBScript’s error handling and the use of the onerror event in IE. Following is the list of a summary of the onerror IE handlers:

  • Execution does not resume on the next line. The script may resume with the next user action or handled event-for example, the user ³clicks ³ on another element. If you want greater error-handling control in individual procedures executed in the browser, the On Error Resume Next statement should be used.
  • All errors pertaining to the element (or window) are handled by the event unless handled via VBScript’s On Error Resume Next technique.
  • Errors can be passed to a higher-level element via event bubbling.
  • Custom errors cannot be created; there is no Err.Raise counterpart in the DHTML object model.

Возможно, вам также будет интересно:

  • Msxml6 dll ошибка скачивания указанного ресурса
  • Msxml6 dll ошибка загрузки указанного ресурса
  • Msxml3 dll системная ошибка 2146697208
  • Msxml3 dll ошибка скачивания указанного ресурса
  • Msxml3 dll ошибка при вызове метода контекста

  • Понравилась статья? Поделить с друзьями:
    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии