How do I write VBScript code for M-Files purposes?

Note: When you develop new extensions or edit existing ones, we recommend that you replace VBScript content with Vault Application Framework (VAF) compatible code for future compatibility. For more information on the benefits of VAF development over VBScript, refer to The Vault Application Framework in M-Files Developer Portal.

See the links above for instructions on adding VBScript code in each instance.

You can access and manage objects contained in the document vault by means of M-Files API and VBScript in the above-mentioned circumstances.

VBScript basics

Below are some elementary basics of VBScript to get you started. Note that we are just scratching the surface here. See Useful resources for further instructions. If you are new to scripting and unfamiliar with concepts such as variables and functions, it might be helpful to first read a beginner's guide to scripting, such as Learn Beginning Scripting.

Statements

In VBScript, a line break ends a statement and thus there is no separate termination character for ending statements. The example below contains two statements:
Dim szPropertyName
szPropertyName = PropertyDef.Name
If you want to divide a statement into separate lines, you may use the underscore character (_) to indicate that a statement is continued on the next line:
Err.Raise MFScriptCancel, _
    "The document vault already contains an object with the same title. Please choose another title."

Commenting

Always comment what you are doing in your code so that others reading your code understand what is going on. You can add a comment in your code using the ' character:
' Get the title of the object.
Dim szCurrentTitle
szCurrentTitle = oCurrentTitleProp.GetValueAsUnlocalizedText
It is a good approach to add a comment above any line of code that you may think is not immediately obvious to the reader.

Variables

Variables are declared using the Dim keyword:
Dim szCurrentTitleProp
Values are assigned to variables using the equals (=) sign. You should always declare you variables before assigning them new values:
Dim szCurrentTitleProp
szCurrentTitleProp = PropertyValues.SearchForProperty( iTitleProperty ).GetValueAsUnlocalizedText
You may use the Option Explicit statement to force explicit declaration of all variables. If you attempt to use an undeclared variable when Option Explicit is enabled in your script, your script will not work. For instance, the following script would not work since the variable szValue has not been declared before it is assigned a value:
Option Explicit
szValue = PropertyValue.GetValueAsUnlocalizedText
When you are scripting in M-Files, you have a number of predefined variables at your disposal. The variable PropertyValue, for example, can be used for fetching the value of a property. See Available VBScript Variables for the complete list of predefined variables.
Note: We recommend you to use the so-called Hungarian notation when naming variables. This way you, or whoever reading your code, has a clear understanding of the data type of the value stored in the the variable. You can use, for instance, the following notation:
  • "sz" for strings
  • "o" for objects
  • "i" for integers
  • "b" for Booleans
  • "f" for floating-point numbers
  • "d" for dates

Constants

You can use constants for storing values that must remain constant throughout the script:
Const iMaxNumberOfItems = 50
Note that you must assign a literal value to a constant. You cannot use a variable, another constant or a function to initialize a constant.

Objects

Objects are assigned to variables using the Set statement. You may create a new instance of an M-Files API object and assign it to a variable in the following fashion:
Dim oTitleSearch
Set oTitleSearch = CreateObject( "MFilesAPI.SearchCondition" )
Objects are components that have their own properties and methods. Methods are functions that belong to a specific object and that can be used in the context of the object. Properties, on the other hand, are used to view or set values of an object. You access the properties and methods of an object using dot notation:
oTitleSearch.Set oTitleExpression, MFConditionTypeEqual, oTitleTypedValue
Method arguments, such as oTitleExpression, MFConditionTypeEqual, and oTitleTypedValue in the above example, are listed after the method and separated by a comma. Parameters are passed either by value or by reference. If a method takes a parameter by value, the method copies the value passed as the argument and thus the original value is unchanged. If, on the other hand, a method takes a parameter by reference, any changes the method may cause to the argument also impact the original reference. The value Nothing should be used if the default value of the parameter is to be used.

When scripting in M-Files, you will take advantage of the objects available in VBScript, and more importantly, the objects available in M-Files API. Refer to the M-Files API documentation for complete details.

Concatenating strings

You may concatenate two or more strings into one using the & operator:
' Get proposal number.
Dim szNumber
szNumber = PropertyValues.SearchForProperty( 1156 ).TypedValue.DisplayValue

' Get customer.
Dim szCustomer
szCustomer = PropertyValues.SearchForProperty( 1288 ).TypedValue.DisplayValue

' Create proposal title.
Dim szName
szName = "Proposal #" & szNumber & " / " & szCustomer
In the above example, the proposal title, stored in the variable szName, is the result of the concatenation of the following strings:
  • string literal Proposal #
  • the proposal number, stored in the szNumber variable
  • another string literal /
  • the customer name, stored in the szCustomer variable
The resulting proposal title could thus be, for example, Proposal #5577 / ESTT.
You can add a line break to your string by concatenating the VbCrLF constant with your strings:
Err.Raise MFScriptCancel, _
    "The document vault already contains an object with the same title." & VbCrLF & "Please choose another title."

Raising errors

If you need to, say, validate a property value with VBScript, it is necessary to display an error message to the user if the value the user entered is invalid. You can raise an error in VBScript using the Raise method of the Err object:
Err.Raise MFScriptCancel, "The property """ & szPropertyName & """ must have a value of at least 10 characters."
The method takes the error number and description as parameters. For M-Files scripting purposes, the MFScriptCancel variable is used as it stores the M-Files error number.

If statements

If statements are used for executing a group of statements if the condition specified in the If statement evaluates to true:
If Len( szValue ) < 10 Then

    Err.Raise MFScriptCancel, "The property """ & szPropertyName & """ must have a value of at least 10 characters."

End If
The if block must end with an End If statement. All the statements between If and End If are executed if the condition specified between If and Then evaluates to true. You can use the And operator to specify multiple conditions that must all be true for the if block to be executed, or the Or operator to specify multiple operators, one of which must be true for the if block to be executed. You can use the following comparison operators for specifying the condition:
  • == checks if the value of two operands are equal or not, if yes, then the condition is true.
  • <> checks if the value of two operands are equal or not, if not, then the condition is true.
  • > checks if the value of the left operand is greater than the value of the right operand, if yes, then the condition is true.
  • < checks if the value of the left operand is less than the value of the right operand, if yes, then the condition is true.
  • >= checks if the value of the left operand is greater than or equal to the value of the right operand, if yes, then the condition is true
  • <= checks if the value of the left operand is less than or equal to the value of the right operand, if yes, then the condition is true
You can also nest an If statement inside another If or, say, an Else statement or use the ElseIf statement to create a deeper branching logic in your script.

Functions and subroutines

You can use a subroutine to define a section of code to be used multiple times by reference in your code:
Sub CloseFile()
    oMyFile.Close
    Set oMyFile = Nothing
End Sub
Or, you can define a function to use multiple times a section of code that returns a value of some kind:
Function IsOdd( iValue )
    If iValue MOD 2 = 0 Then ' Even value.
        IsOdd = False
    Else ' Odd value.
        IsOdd = True
    End If
End Function
To call a subroutine or function in your script, just refer to it by name:
Closefile()
IsOdd( 5 )

Useful resources

Your most valuable sources of information on scripting within M-Files are the following:

The M-Files API documentation is an exhaustive reference to the M-Files API objects, methods, interfaces, properties, and enumerations that you can take advantage of within VBScript code. The latter resource, on the other hand, lists and explains all the variables with preassigned values that you can readily utilize in your VBScript code.

In addition to the two aforementioned resources, you may find the following external websites useful:

Example

The example below is a script that can be used for validating a property when the user attempts to save metadata changes on the metadata card. The script ensures that the entered property value must be at least 10 characters in length. Let us take a closer look at the script:
Option Explicit

Dim szPropertyName, szValue

szPropertyName = PropertyDef.Name

szValue = PropertyValue.GetValueAsUnlocalizedText

If Len( szValue ) < 10 Then

    Err.Raise MFScriptCancel, "The property """ & szPropertyName & """ must have a value of at least 10 characters."

End If
First, the variables szPropertyName and szValue are declared, after which the name of the property and its value we are validating are stored in the variables we have just declared. We use the GetValueAsUnlocalizedText method (refer to the M-Files API documentation for more information) to obtain the property value as unlocalized text.

Our condition for validating the property value is that the value must have at least 10 characters. We evaluate that condition in an If statement. We have defined in the condition of the If statement that the length of the property must be less than 10 characters for the statement inside the If statement to be executed. If the property value is 10 characters or more, the If code block is not executed and the script execution is finished.

In the if block, we send an error message to the user where we state that the property value that the user entered must have at least 10 characters, thus instructing the user to add a longer value. After the error message is displayed, the metadata card is displayed again, allowing the user to modify the invalid property value.

For complete instructions on validating property values with VBScript, see Automatically Validating Property Values.