Vba excel стандартные функции

String/Text Functions ASC Returns ASCII value of a character CHR Returns the character based on the ASCII value CONCATENATE with & Used to join 2 or more strings together using the & operator FORMAT STRINGS Takes a string expression and returns it as a formatted string INSTR Returns the position of the first occurrence of a substring in a string INSTRREV Returns the position of the first occurrence of a string in another string, starting from the end of the string LCASE Converts a string to lowercase LEFT Extract a substring from a string, starting from the left-most character LEN Returns the length of the specified string LTRIM Removes leading spaces from a string MID Extracts a substring from a string (starting at any position) REPLACE Replaces a sequence of characters in a string with another set of characters RIGHT Extracts a substring from a string starting from the right-most character RTRIM Removes trailing spaces from a string SPACE Returns a string with a specified number of spaces SPLIT Used to split a string into substrings based on a delimiter STR Returns a string representation of a number STRCOMP Returns an integer value representing the result of a string comparison STRCONV Returns a string converted to uppercase, lowercase, proper case or Unicode STRREVERSE Returns a string whose characters are in reverse order TRIM Returns a text value with the leading and trailing spaces removed UCASE Converts a string to all uppercase VAL Returns the numbers found in a string Format Applies a format to an expression and returns the result as a string. String Creates a string consisting of a number of repeated characters. Date/Time Functions DATE Returns the current system date DATEADD Returns a date after which a certain time/date interval has been added DATEDIFF Returns the difference between two date values, based on the interval specified DATEPART Returns a specified part of a given date DATESERIAL Returns a date given a year, month, and day value DATEVALUE Returns the serial number of a date DAY Returns the day of the month (a number from 1 to 31) given a date value FORMAT DATES Takes a date expression and returns it as a formatted string HOUR Returns the hours (a number from 0 to 23) from a time value MINUTE Returns the minutes (a number from 0 to 59) from a time value MONTH Returns the month (a number from 1 to 12) given a date value MONTHNAME Returns a string representing the month given a number from 1 to 12 NOW Returns the current system date and time TIMESERIAL Returns a time given an hour, minute, and second value TIMEVALUE Returns the serial number of a time WEEKDAY Returns a number representing the day of the week, given a date value WEEKDAYNAME Returns a string representing the day of the week given a number from 1 to 7 YEAR Returns a four-digit year (a number from 1900 to 9999) given a date value Second Returns the second component of a supplied time. Time Returns the current time. Timer Returns the number of seconds that have elapsed since midnight. Math/Trig Functions ABS Returns the absolute value of a number ATN Returns the arctangent of a number COS Returns the cosine of an angle EXP Returns e raised to the nth power FIX Returns the integer portion of a number FORMAT NUMBERS Takes a numeric expression and returns it as a formatted string INT Returns the integer portion of a number LOG Returns the natural logarithm of a number RANDOMIZE Used to change the seed value used by the random number generator for the RND function RND Used to generate a random number (integer value) ROUND Returns a number rounded to a specified number of digits SGN Returns the sign of a number SIN Returns the sine of an angle SQR Returns the square root of a number TAN Returns the tangent of an angle MOD Returns the remainder after division operator (Integer). XOR The bitwise exclusion operator. Logical Functions AND Returns TRUE if all conditions are TRUE CASE Has the functionality of an IF-THEN-ELSE statement FOR…NEXT Used to create a FOR LOOP IF-THEN-ELSE Returns a value if a specified condition evaluates to TRUE or another value if it evaluates to FALSE OR Returns TRUE if any of the conditions are TRUE SWITCH Evaluates a list of expressions and returns the corresponding value for the first expression in the list that is TRUE WHILE…WEND Used to create a WHILE LOOP IS Compares two object reference variables. LIKE The pattern matching operator. Information Functions ENVIRON Returns the value of an operating system environment variable ISDATE Returns TRUE if the expression is a valid date ISEMPTY Used to check for blank cells or uninitialized variables ISERROR Used to check for error values ISNULL Used to check for a NULL value ISNUMERIC Used to check for a numeric value IsArray Tests if a supplied variable is an array. IsMissing Tests if an optional argument to a procedure is missing. IsObject Tests if a supplied variable represents an object variable. Financial Functions DDB Returns the depreciation of an asset based on the double-declining balance method FV Returns the future value of an investment IPMT Returns the interest payment for an investment IRR Returns the internal rate of return for a series of cash flows MIRR Returns the modified internal rate of return for a series of cash flows NPER Returns the number of periods for an investment NPV Returns the net present value of an investment PMT Returns the payment amount for a loan PPMT Returns the payment on the principal for a particular payment PV Returns the present value of an investment RATE Returns the interest rate for an annuity SLN Returns the depreciation of an asset based on the straight-line depreciation method SYD Returns the depreciation of an asset based on the sum-of-years’ digits depreciation method File/Directory Functions CHDIR Used to change the current directory or folder CHDRIVE Used to change the current drive CURDIR Returns the current path DIR Returns the first filename that matches the pathname and attributes specified FILEDATETIME Returns the date and time of when a file was created or last modified FILELEN Returns the size of a file in bytes GETATTR Returns an integer that represents the attributes of a file, folder, or directory MKDIR Used to create a new folder or directory SETATTR Used to set the attributes of a file FileAttr Returns the mode of a file that has been opened using the Open statement. FILECOPY Copies a file from one directory to another. FREEFILE Returns the next valid free file number (Integer). GET Reads data from a text file into a record. INPUT Returns the open stream of an Input or Binary file (String). EOF Returns the value indicating if the end of a file has been reached (Boolean). WRITE Writes data to a sequential file. PRINT Writes display-formatted data to a sequential file. PUT Writes data from a record into a text file. KILL Deletes an existing file. SEEK — Function Returns the current read/write position within a file opened using the Open statement (Long). SEEK — Statement Repositions where the next operation in a file will occur. OPEN Opens a text file or CSV file. LINE INPUT Reads a single line from an Open sequential file and assigns it to a string. CLOSE Closes a text file. LOADPICTURE Loads a picture from a file into a Picture or Image control (IPictureDisp). LOC Returns the current read/write position within an open file (Long). LOCK Locks access to parts of a file for other processes. LOF Returns the length or size of an open file, in bytes (Long). NAME Renames an existing file or directory. SAVEPICTURE Saves a graphic image from an objects Picture or Image property to a file. Data Type Conv. Functions CBOOL Converts a value to a boolean CBYTE Converts a value to a byte (ie: number between 0 and 255) CCUR Converts a value to currency CDATE Converts a value to a date CDBL Converts a value to a double CDEC Converts a value to a decimal number CINT Converts a value to an integer CLNG Converts a value to a long integer CSNG Converts a value to a single-precision number CSTR Converts a value to a string CVAR Converts a value to a variant CLNGLNG Returns the expression converted to a longlong (64 bit platform) data type. CLNGPTR Returns the expression converted to a longptr data type. CVDATE Returns the expression converted to a date variant-subtype (Variant). FormatCurrency Applies a currency format to an expression and returns the result as a string. FormatDateTime Applies a date/time format to an expression and returns the result as a string. FormatNumber Applies a number format to an expression and returns the result as a string. FormatPercent Applies a percentage format to an expression and returns the result as a string. Hex Converts a numeric value to hexadecimal notation and returns the result as a string. Oct Converts a numeric value to octal notation and returns the result as a string. MACID Converts a four character constant to a value that can be used by Dir, Kill, Shell and AppActivate. VBA Array Functions Array Creates an array, containing a supplied set of values. Filter Returns a subset of a supplied string array, based on supplied criteria. Join Joins a number of substrings into a single string. LBound Returns the lowest subscript for a dimension of an array. UBound Returns the highest subscript for a dimension of an array. REDIM Initialises and resizes a dynamic array. VBA Message Functions InputBox Displays a dialog box prompting the user for input. MsgBox Displays a modal message box. VBA Error Handling Functions CVErr Produces an Error data type for a supplied error code. Error Returns the error message corresponding to a supplied error code. Lookup/Ref Functions CHOOSE Returns a value from a list of values based on a given position VBA Program Flow Functions IIf Evaluates an expression and returns one of two values, depending on whether the expression evaluates to True or False. Others Vlookup in VBA Use the Excel spreadsheet Vlookup function from within VBA APPACTIVATE Activates an application or window currently running on Windows. BEEP Produces a single beep noise. CALL Transfers control to a subroutine or function. CALLBYNAME Returns, sets or executes a method or property of an object (Variant). COMMAND Returns the argument portion of the command line used to launch the application (Variant). CREATEOBJECT Returns a reference after creating a new ActiveX or OLE object (Variant). DELETESETTING Removes (or deletes) a key or section from the registry. DOEVENTS Pauses execution to let the system process other events. EQV The bitwise comparison operator. ERASE Reinitialises the elements of an array. GETALLSETTINGS Returns the list of key settings and their values from the registry (Variant). GETOBJECT Returns the reference to an object provided by an ActiveX component. GETSETTING Reads from the registry and returns the value or key from the registry (String). GOTO Transfers control to the subroutine indicated by the line label. IMESTATUS Returns the current Input Method Editor mode of Microsoft Windows (Integer). IMP The logical implication from two values (Variant). IMPLEMENTS Specifies an interface or class that can be implemented in a class module. LET Computes a value and assigns it to a new variable. LOAD Loads an object but doesn’t display it. LSET Left aligns a string within a string variable. NOT The logical ‘NOT’ operator (Boolean). OBJPTR Returns a LongPtr on a 64 bit version and a Long on a 32 bit version. PARTITION Returns a string indicating which particular range it falls into (String). QBCOLOR Returns the RGB colour corresponding to the specified colour number (Long). RAISEEVENT Fires an event declared at module level within a class, form or document. REM Specifies a single line of comments. RESET Closes all files open with the Open statement. RGB Returns the number representing an RGB colour value (Long). RMDIR Removes an existing directory. RSET Right aligns a string within a string variable. SAVESETTING Writes to the registry and saves a section or key in the registry. SENDKEYS Sends keystrokes to an application. SET Assigns an object reference to an object variable. SHELL Returns the program’s task id from running an executable programs (Double). SPC Inserts a specified number (n) of spaces when writing or displaying text. STOP Suspends execution. STRPTR Returns a LongPtr on a 64 bit version and a Long on a 32 bit version. TAB Used with the Print # statement or the Print method to position output. TYPENAME Returns the data type of the variable as a string (String). TYPEOF Returns the object data type. UNLOAD Removes an object from memory. UNLOCK Controls access to a file. VARPTR Returns a LongPtr on a 64 bit version and a Long on a 32 bit version. VARTYPE Returns the number indicating the data type of a variable (Integer). WIDTH Assigns an output line width (characters) for the open file.

totn Excel Functions


Learn how to use all Excel VBA functions used in Macros. VBA functions are built-in functions that are used in Excel’s programming environment called Visual Basic for Applications (VBA).

Below is a list of Excel VBA functions sorted alphabetically. If you would like a list of these functions sorted by category, click on the following button:

Sort Alphabetically


(Enter a value in the field above to quickly find functions in the list below)

Lookup/Ref Functions

CHOOSE (VBA) Returns a value from a list of values based on a given position

String/Text Functions

ASC (VBA) Returns ASCII value of a character
CHR (VBA) Returns the character based on the ASCII value
CONCATENATE with & (VBA) Used to join 2 or more strings together using the & operator
FORMAT STRINGS (VBA) Takes a string expression and returns it as a formatted string
INSTR (VBA) Returns the position of the first occurrence of a substring in a string
INSTRREV (VBA) Returns the position of the first occurrence of a string in another string, starting from the end of the string
LCASE (VBA) Converts a string to lowercase
LEFT (VBA) Extract a substring from a string, starting from the left-most character
LEN (VBA) Returns the length of the specified string
LTRIM (VBA) Removes leading spaces from a string
MID (VBA) Extracts a substring from a string (starting at any position)
REPLACE (VBA) Replaces a sequence of characters in a string with another set of characters
RIGHT (VBA) Extracts a substring from a string starting from the right-most character
RTRIM (VBA) Removes trailing spaces from a string
SPACE (VBA) Returns a string with a specified number of spaces
SPLIT (VBA) Used to split a string into substrings based on a delimiter
STR (VBA) Returns a string representation of a number
STRCOMP (VBA) Returns an integer value representing the result of a string comparison
STRCONV (VBA) Returns a string converted to uppercase, lowercase, proper case or Unicode
STRREVERSE (VBA) Returns a string whose characters are in reverse order
TRIM (VBA) Returns a text value with the leading and trailing spaces removed
UCASE (VBA) Converts a string to all uppercase
VAL (VBA) Returns the numbers found in a string

Date/Time Functions

DATE (VBA) Returns the current system date
DATEADD (VBA) Returns a date after which a certain time/date interval has been added
DATEDIFF (VBA) Returns the difference between two date values, based on the interval specified
DATEPART (VBA) Returns a specified part of a given date
DATESERIAL (VBA) Returns a date given a year, month, and day value
DATEVALUE (VBA) Returns the serial number of a date
DAY (VBA) Returns the day of the month (a number from 1 to 31) given a date value
FORMAT DATES (VBA) Takes a date expression and returns it as a formatted string
HOUR (VBA) Returns the hours (a number from 0 to 23) from a time value
MINUTE (VBA) Returns the minutes (a number from 0 to 59) from a time value
MONTH (VBA) Returns the month (a number from 1 to 12) given a date value
MONTHNAME (VBA) Returns a string representing the month given a number from 1 to 12
NOW (VBA) Returns the current system date and time
TIMESERIAL (VBA) Returns a time given an hour, minute, and second value
TIMEVALUE (VBA) Returns the serial number of a time
WEEKDAY (VBA) Returns a number representing the day of the week, given a date value
WEEKDAYNAME (VBA) Returns a string representing the day of the week given a number from 1 to 7
YEAR (VBA) Returns a four-digit year (a number from 1900 to 9999) given a date value

Math/Trig Functions

ABS (VBA) Returns the absolute value of a number
ATN (VBA) Returns the arctangent of a number
COS (VBA) Returns the cosine of an angle
EXP (VBA) Returns e raised to the nth power
FIX (VBA) Returns the integer portion of a number
FORMAT NUMBERS (VBA) Takes a numeric expression and returns it as a formatted string
INT (VBA) Returns the integer portion of a number
LOG (VBA) Returns the natural logarithm of a number
MOD (VBA) Returns the remainder after a number is divided by a divisor
RANDOMIZE (VBA) Used to change the seed value used by the random number generator for the RND function
RND (VBA) Used to generate a random number (integer value)
ROUND (VBA) Returns a number rounded to a specified number of digits
SGN (VBA) Returns the sign of a number
SIN (VBA) Returns the sine of an angle
SQR (VBA) Returns the square root of a number
TAN (VBA) Returns the tangent of an angle

Logical Functions

AND (VBA) Returns TRUE if all conditions are TRUE
CASE (VBA) Has the functionality of an IF-THEN-ELSE statement
FOR…NEXT (VBA) Used to create a FOR LOOP
IF-THEN-ELSE (VBA) Returns a value if a specified condition evaluates to TRUE or another value if it evaluates to FALSE
OR (VBA) Returns TRUE if any of the conditions are TRUE
SWITCH (VBA) Evaluates a list of expressions and returns the corresponding value for the first expression in the list that is TRUE
WHILE…WEND (VBA) Used to create a WHILE LOOP

Information Functions

ENVIRON (VBA) Returns the value of an operating system environment variable
ISDATE (VBA) Returns TRUE if the expression is a valid date
ISEMPTY (VBA) Used to check for blank cells or uninitialized variables
ISERROR (VBA) Used to check for error values
ISNULL (VBA) Used to check for a NULL value
ISNUMERIC (VBA) Used to check for a numeric value

Financial Functions

DDB (VBA) Returns the depreciation of an asset based on the double-declining balance method
FV (VBA) Returns the future value of an investment
IPMT (VBA) Returns the interest payment for an investment
IRR (VBA) Returns the internal rate of return for a series of cash flows
MIRR (VBA) Returns the modified internal rate of return for a series of cash flows
NPER (VBA) Returns the number of periods for an investment
NPV (VBA) Returns the net present value of an investment
PMT (VBA) Returns the payment amount for a loan
PPMT (VBA) Returns the payment on the principal for a particular payment
PV (VBA) Returns the present value of an investment
RATE (VBA) Returns the interest rate for an annuity
SLN (VBA) Returns the depreciation of an asset based on the straight-line depreciation method
SYD (VBA) Returns the depreciation of an asset based on the sum-of-years’ digits depreciation method

File/Directory Functions

CHDIR (VBA) Used to change the current directory or folder
CHDRIVE (VBA) Used to change the current drive
CURDIR (VBA) Returns the current path
DIR (VBA) Returns the first filename that matches the pathname and attributes specified
FILEDATETIME (VBA) Returns the date and time of when a file was created or last modified
FILELEN (VBA) Returns the size of a file in bytes
GETATTR (VBA) Returns an integer that represents the attributes of a file, folder, or directory
MKDIR (VBA) Used to create a new folder or directory
SETATTR (VBA) Used to set the attributes of a file

Data Type Conv. Functions

CBOOL (VBA) Converts a value to a boolean
CBYTE (VBA) Converts a value to a byte (ie: number between 0 and 255)
CCUR (VBA) Converts a value to currency
CDATE (VBA) Converts a value to a date
CDBL (VBA) Converts a value to a double
CDEC (VBA) Converts a value to a decimal number
CINT (VBA) Converts a value to an integer
CLNG (VBA) Converts a value to a long integer
CSNG (VBA) Converts a value to a single-precision number
CSTR (VBA) Converts a value to a string
CVAR (VBA) Converts a value to a variant

Аннотация: Лекция посвящена описанию основных конструкций и принципов VBA. Подробно обсуждаются стандартные встроенные функции VBA и пользовательские процедуры и функции.

6.1. Встроенные математические функции

06-01-Математика.docm — пример к п. 6.1.

Вы хотите вычислить квадратный корень, округлить число или сделать с ним еще что-нибудь подобное? Для этого VBA имеет специализированные функции, вы можете найти их в табл. 6.1.

Таблица
6.1.
Встроенные математические функции

Функция Описание
Abs Абсолютное значение
Atn Арктангенс
Cos Косинус числа
Exp Возвращает число e (2.718282), возведенное в степень аргумента функции.
Fix Отбрасывает дробную часть числа и возвращает целую. В результате для положительных чисел получается число меньшее, чем входное (Fix(2.5) возвратит 2), для отрицательных — большее (Fix(-2.5) возвратит -2)
Int Отбрасывает дробную часть числа и возвращает целую. Для положительных получается число меньшее введенного (Int(2.5) возвратит 2), для отрицательных — так же меньшее (Int(-2.5) возвратит -3).
Log Возвращает натуральный логарифм числа
Rnd Возвращает случайное число типа Single, причем, это число находится между 0 и 1.
Для инициализации генератора случайных чисел используйте директиву Randomize — ее надо вызвать до вызова Rnd.
Sgn Функция предназначена для определения знака числа. Если число положительное — она возвращает 1. Для нуля функция возвратит 0, для отрицательного числа -1.
Sin Синус
Sqr Квадратный корень
Tan Тангенс

Давайте рассмотрим пример. Добавим в документ Microsoft Word кнопку, назовем ее cmd_Calc, надпишем ее как Вычисления и добавим следующий код (листинг 6.1.), иллюстрирующий работу рассмотренных функций.

Dim dblNumber As Double
    'Переменная, используемая в вычислениях
    Dim varResult
    'Переменная типа Variant
    dblNumber = Val(InputBox("Введите число"))
    'Вычисляем абсолютное значение введенного числа
    'Сначала присвоим результат переменной varResult
    'Далее - выведем подписанный результат в окне
    'сообщения, воспользуемся знаком "+" для
    'конкатенации строк, в других случаях
    'будем вызывать функции непосредственно
    'в MsgBox'e
    'Обратите внимание на то, что мы конвертируем
    'числовые значения в строки с помощью функции Str
    varResult = Abs(dblNumber)
    MsgBox ("Абсолютное значение " + _
    Str(dblNumber) + " равняется " + Str(varResult))
    'Арктангенс
    MsgBox ("Арктангенс " + _
    Str(dblNumber) + " равняется " + _
    Str(Atn(dblNumber)))
    'Косинус
    MsgBox ("Косинус " + _
    Str(dblNumber) + " равняется " + _
    Str(Cos(dblNumber)))
    'e в степени введенного числа
    MsgBox ("Число e в степени " + _
    Str(dblNumber) + " равняется " + _
    Str(Exp(dblNumber)))
    'Функция Fix
    MsgBox ("Результат работы функции Fiх для " + _
    Str(dblNumber) + " равняется " + _
    Str(Fix(dblNumber)))
    'Функция Int
    MsgBox ("Результат работы функции Int для " + _
    Str(dblNumber) + " равняется " + _
    Str(Int(dblNumber)))
    'Натуральный логарифм
    MsgBox ("Натуральный логарифм " + _
    Str(dblNumber) + " равняется " + _
    Str(Log(dblNumber)))
    'Получим несколько случайных чисел
    'первое число - от 0 до 1
    'второе - от 0 до 10.
    'Третье - от 25 до 100
    'Четвертое - целое от 0 до 34
    Randomize
    MsgBox ("Группа случайных чисел: " + _
    Str(Rnd()) + ", " + _
    Str(Rnd() * 10) + ", " + _
    Str(Rnd() * 75 + 25) + ", " + _
    Str(Int(Rnd() * 34)))
    'Функция Sgn
    MsgBox ("Результат работы Sgn для " + _
    Str(dblNumber) + " равняется " + _
    Str(Sgn(dblNumber)))
    'Cинус
    MsgBox ("Синус " + _
    Str(dblNumber) + " равняется " + _
    Str(Sin(dblNumber)))
    'Квадратный корень
    MsgBox ("Квадратный корень " + _
    Str(dblNumber) + " равняется " + _
    Str(Sqr(dblNumber)))
    'Тангенс
    MsgBox ("Тангенс " + _
    Str(dblNumber) + " равняется " + _
    Str(Tan(dblNumber)))


Листинг
6.1.
Обработчик события Click кнопки cmd_Calc

Обратите внимание на алгоритм получения случайного числа, находящегося в определенном диапазоне, с помощью функции Rnd. Предположим, нам нужно получить случайное число от 15 до 40. Получим, для начала, число от 0 до 40. Очевидно, что для этого нам понадобится такой вызов: Rnd()*40.

Чтобы «поднять» уровень наименьшего случайного числа, возвращаемого выражением, до 15, сделаем следующее.

Во-первых, вычислим разность 40 и 15 — у нас получится 25. Значит, чтобы получить случайное число от 0 до 25, можно использовать вызов Rnd()*25.

Во-вторых, прибавим к полученному случайному числу 15. Теперь выражение для получения случайного числа от 15 до 40 выглядит так: Rnd()*25+15.

Проверим это высказывание на правильность. Функция Rnd, как известно, возвращает случайные числа от 0 до 1. Если функция возвратит 0 — результат вычисления выражения будет равен 15 (0*25+15). Если функция возвратит 1 — результат будет равен 40 (25*1+15). Промежуточные значения Rnd дадут искомые случайные числа между 15 и 40.

На рис. 6.1. вы можете видеть окно сообщения, содержащее результаты вызовов функции Rnd.

Окно сообщения, выводящее случайные числа

Рис.
6.1.
Окно сообщения, выводящее случайные числа

Выше мы работали, в основном, с числами, теперь поговорим о строковых переменных.

6.2. Строковые функции

06-02-Строковые функции.docm — пример к п. 6.2.

В табл. 6.2. вы можете найти информацию об основных строковых функциях VBA.

Таблица
6.2.
Строковые функции

Функция Описание
Len(string) Возвращает длину строки. Например, длина строки «Добрый день» составляет 11 символов — учитывая пробел. Выходное значение имеет тип Long
LCase(string) Возвращает строку, все символы которой записаны в нижнем регистре. Например, строка «Привет» превратится в «привет»
UCase(string) Возвращает строку, все символы которой записаны в верхнем регистре. Например, для «Привет» мы получим «ПРИВЕТ»
String(number, character) Возвращает строку, состоящую из number символов character
Left(string, length) Возвращает length символов, начиная с первого левого символа строки string
Right(string, length) Возвращает length символов, начиная с самого правого символа строки string
LTrim(string) Возвращает строку, в которой вырезаны все пробелы слева
RTrim(string) Вырезает из строки все пробелы справа
Trim(string) Вырезает из строки все пробелы слева и справа
Mid(string, start[, length]) Вырезает из строки string с позиции start length символов
Asc(string) Возвращает ASCII-код первого символа строки
Chr(charcode) Возвращает символ, соответствующий коду символа

Работа со строками традиционно считается сложным разделом программирования для начинающих, поэтому проиллюстрируем вышеописанные функции примерами.

Создадим документ Microsoft Word и добавим на него следующие кнопки табл. 6.3.

Обработчик нажатия кнопки cmd_Len (листинг 6.2.) будет содержать решение следующей задачи: сообщить пользователю длину введенного текста. Очевидно, для решения этой задачи нам понадобится функция Len.

'Переменная для хранения входной строки
    Dim str_InpStr As String
    'Переменная для хранения найденной длины строки
    Dim lng_StrLen As Long
    str_InpStr = InputBox("Введите строку")
    'Вычисляем длину строки
    lng_StrLen = Len(str_InpStr)
    MsgBox ("Длина введенной строки: _" + _
    str_InpStr + "_ равняется " + Str(lng_StrLen) + _
    " символам")


Листинг
6.2.
Пример использования функции Len

На рис. 6.2. вы можете видеть результат вычисления длины строки.

Результат вычисления длины строки

Рис.
6.2.
Результат вычисления длины строки

Теперь займемся конверсией символов — функциями LCase и UCase (листинг 6. 3.).

'Переменная для хранения входной строки
    Dim str_InpStr As String
    'Переменная для хранения измененной строки
    Dim str_NewStr As String
    str_InpStr = InputBox("Введите текст")
    'В str_NewStr окажется введеная строка
    'в которой все прописные буквы заменены строчными
    str_NewStr = LCase(str_InpStr)
    MsgBox ("Измененная строка: " + str_NewStr)
    'Теперь в str_NewStr будет та же строка
    'в которой все буквы стали прописными
    str_NewStr = UCase(str_InpStr)
    MsgBox ("Измененная строка: " + str_NewStr)


Листинг
6.3.
Пример использования функций LCase и UCase

На очереди — вырезание символов — функции Mid, LTrim, Rtrim, Left, Right (листинг 6.4.) Среди этих функций наиболее мощной является Mid — используя ее, можно делать со строками очень много всего.

'Переменная для хранения входной строки
    Dim str_InpStr As String
    'Переменная для хранения вырезанных символов
    Dim str_NewStr As String
    'Зададим строку, с которой удобно будет работать
    str_InpStr = "  Здравствуйте, Александр  "
    'Функции удаления пробелов
    'При выводе строки ставим перед ее началом
    'и концом символ "_" для того чтобы
    'лучше было видно наличие
    'или отсутствие пробелов
    MsgBox ("Мы работаем с такой строкой: " + _
    "_" + str_InpStr + "_")
    'LTrim - присваиваем результаты работы
    'переменной и выводим информацию в MsgBox
    str_NewStr = LTrim(str_InpStr)
    MsgBox ("Результат работы LTrim: " + _
    "_" + str_NewStr + "_")
    'RTrim
    MsgBox ("Результат работы RTrim: " + _
    "_" + RTrim(str_InpStr) + "_")
    'Trim
    MsgBox ("Результат работы Trim: " + _
    "_" + Trim(str_InpStr) + "_")
    'Left - вырезаем из строки str_InpStr 12
    'символов предварительно очистив ее
    'от начальных пробелов
    str_NewStr = Left(LTrim(str_InpStr), 12)
    MsgBox ("Первые 12 символов слева: " + _
    str_NewStr)
    'Right - аналогично Вырезаем 9 символов справа
    str_NewStr = Right(RTrim(str_InpStr), 9)
    MsgBox ("Первые 9 символов справа: " + _
    str_NewStr)
    'Функция Mid - для начала выведем по одному символу
    'со второй и пятнадцатой позиции строки
    'преварительно очищенной от лишних пробелов
    'в начале и в конце
    str_NewStr = Mid(Trim(str_InpStr), 2, 1)
    MsgBox ("Второй символ введенной строки: " + _
    str_NewStr)
    str_NewStr = Mid(Trim(str_InpStr), 15, 1)
    MsgBox ("Пятнадцатый символ введенной строки: " + _
    str_NewStr)
    'Выведем 5 символов, начиная с 15 символа
    str_NewStr = Mid(Trim(str_InpStr), 15, 5)
    MsgBox ("Пять символов строки с 15-й позиции: " + _
    str_NewStr)


Листинг
6.4.
Пример использования функций для вырезания символов

Теперь рассмотрим примеры работы функций Asc, Chr и функции String. Чтобы работать с функциями Asc и Chr нам нужно познакомиться с понятием таблицы символов ASCII.

ASCII расшифровывается как American Standard Code For Information Intercharge — американский стандартный код для обмена информацией. Каждый символ в ASCII закодирован восьмибитным кодом. В результате получается таблица, в которой каждому управляющему символу, цифре, букве латинского или национального алфавитов сопоставлен свой код. Коды записывают в различных представлениях — в основном — в шестнадцатеричном и десятичном. Мы будем пользоваться десятичной записью.

Мы не будем приводить здесь таблицу ASCII полностью, приведем лишь некоторые полезные коды и диапазоны кодов.

Коды в диапазоне 0-31 имеют управляющие символы. Символ возврата каретки (тот самый, который вставляется в документ при нажатии клавиши Enter ) имеет код 13.

Коды в диапазоне 32-127 имеют латинские символы, цифры, знаки препинания — эта часть таблицы остается постоянной для различных кодовых таблиц. Например, пробел имеет код 32, точка — 46. Диапазон 48-57 занимают цифры от 0 до 9, диапазон 65-90 занимают заглавные латинские буквы от A до Z, диапазон 97-122 — строчными буквы a-z.

В диапазоне 128-225 расположены символы национальной кодировки. В русифицированных версиях MS Windows обычно применяется кодовая страница MS Windows 1251. В ней коды 192-223 имеют заглавные буквы от А до Я, 224-255 — строчные буквы от а до я.

Используя коды символов можно вводить в документы (или записывать в файлы, создаваемые программно) символы, которые нельзя ввести с клавиатуры.

В коде обработчика Click для cmd_Asc создадим программу (листинг 6.5.), которая сначала запрашивает у пользователя ввод символа, после чего выводит его ASCII код, потом — ввод кода, после чего выводит соответствующий ему символ. Так же здесь мы посмотрим на то, как работает функция String:

'Переменная для хранения кода символа
    Dim num_AscNumber
    'Переменная для хранения символа
    Dim str_Char
    'Начало блока перевода кода в символ
    num_AscNumber = Val(InputBox("Введите код символа"))
    'В переменной str_Char теперь хранится символ
    'с кодом num_AscNumber
    str_Char = Chr(num_AscNumber)
    MsgBox (str_Char + " - символ с кодом " + _
    Str(num_AscNumber))
    'Начало блока перевода символа в код
    str_Char = InputBox("Введите символ")
    'Теперь в переменной num_AscNumber хранится
    'Код символа, введенного в str_Char
    num_AscNumber = Asc(str_Char)
    MsgBox ("Символу " + str_Char + " соответствует код" + _
    Str(num_AscNumber))
    'А теперь - пример функции String.
    'выведем в окне сообщения 15 символов *
    MsgBox ("15 символов *: " + String(15, "*"))


Листинг
6.5.
Пример использования функций Chr, Asc, String

На чтение 6 мин Опубликовано 15.12.2015

Содержание

  1. Операторы Excel VBA
  2. Математические операторы
  3. Строковые операторы
  4. Операторы сравнения
  5. Логические операторы
  6. Встроенные функции

Операторы Excel VBA

При написании кода VBA в Excel набор встроенных операторов используют на каждом шагу. Эти операторы делятся на математические, строковые, операторы сравнения и логические. Далее мы подробно рассмотрим каждую группу операторов.

Математические операторы

Основные математические операторы VBA перечислены в таблице ниже.

В правом столбце таблицы указан приоритет операторов, принятый по умолчанию при отсутствии скобок. Добавляя в выражение скобки, можно изменять порядок выполнения операторов VBA по своему желанию.

Оператор Действие Приоритет
(1 — высший; 5 — низший)
^ Оператор возведения в степень 1
* Оператор умножения 2
/ Оператор деления 2
Оператор деления без остатка – возвращает результат деления двух чисел без остатка. Например, 74 возвратит результат 1 3
Mod Оператор модуля (остатка) – возвращает остаток от деления двух чисел. Например, 8 Mod 3 возвратит результат 2. 4
+ Оператор сложения 5
Оператор вычитания 5

Строковые операторы

Основной строковый оператор в Excel VBA – это оператор конкатенации & (слияние):

Оператор Действие
& Оператор конкатенации. К примеру, выражение «A» & «B» возвратит результат AB.

Операторы сравнения

Операторы сравнения используются для сравнения двух чисел или строк и возвращают логическое значение типа Boolean (True или False). Основные операторы сравнения Excel VBA перечислены в этой таблице:

Оператор Действие
= Равно
<> Не равно
< Меньше
> Больше
<= Меньше либо равно
>= Больше либо равно

Логические операторы

Логические операторы, как и операторы сравнения, возвращают логическое значение типа Boolean (True или False). Основные логические операторы Excel VBA перечислены в таблице ниже:

Оператор Действие
And Операция конъюнкции, логический оператор И. Например, выражение A And B возвратит True, если A и B оба равны True, в противном случае возвратит False.
Or Операция дизъюнкции, логический оператор ИЛИ. Например, выражение A Or B возвратит True, если A или B равны True, и возвратит False, если A и B оба равны False.
Not Операция отрицания, логический оператор НЕ. Например, выражение Not A возвратит True, если A равно False, или возвратит False, если A равно True.

В приведённой выше таблице перечислены не все логические операторы, доступные в VBA. Полный список логических операторов можно найти на сайте Visual Basic Developer Center.

Встроенные функции

В VBA доступно множество встроенных функций, которые могут быть использованы при написании кода. Ниже перечислены некоторые из наиболее часто используемых:

Функция Действие
Abs Возвращает абсолютную величину заданного числа.

Пример:

  • Abs(-20) возвращает значение 20;
  • Abs(20) возвращает значение 20.
Chr Возвращает символ ANSI, соответствующий числовому значению параметра.

Пример:

  • Chr(10) возвращает перенос строки;
  • Chr(97) возвращает символ a.
Date Возвращает текущую системную дату.
DateAdd Добавляет определённый временной интервал к заданной дате. Синтаксис функции:

DateAdd(интервал, число, дата)

Где аргумент интервал определяет тип временного интервала, добавляемого к заданной дате в количестве, указанном в аргументе число.

Аргумент интервал может принимать одно из следующих значений:

Интервал Значение
yyyy год
q квартал
m месяц
y день года
d день
w день недели
ww неделя
h час
n минута
s секунда

Пример:

  • DateAdd(«d», 32, «01/01/2015») добавляет 32 дня к дате 01/01/2015 и, таким образом, возвращает дату 02/02/2015.
  • DateAdd(«ww», 36, «01/01/2015») добавляет 36 недель к дате 01/01/2015 и возвращает дату 09/09/2015.
DateDiff Вычисляет количество определённых временных интервалов между двумя заданными датами.

Пример:

  • DateDiff(«d», «01/01/2015», «02/02/2015») вычисляет количество дней между датами 01/01/2015 и 02/02/2015, возвращает результат 32.
  • DateDiff(«ww», «01/01/2015», «03/03/2016») вычисляет количество недель между датами 01/01/2015 и 03/03/2016, возвращает результат 61.
Day Возвращает целое число, соответствующее дню месяца в заданной дате.

Пример: Day(«29/01/2015») возвращает число 29.

Hour Возвращает целое число, соответствующее количеству часов в заданном времени.

Пример: Hour(«22:45:00») возвращает число 22.

InStr Принимает в качестве аргументов целое число и две строки. Возвращает позицию вхождения второй строки внутри первой, начиная поиск с позиции, заданной целым числом.

Пример:

  • InStr(1, «Вот искомое слово», «слово») возвращает число 13.
  • InStr(14, «Вот искомое слово, а вот еще искомое слово», «слово») возвращает число 38.

Примечание: Аргумент-число может быть не задан, в таком случае поиск начинается с первого символа строки, заданной во втором аргументе функции.

Int Возвращает целую часть заданного числа.

Пример: Int(5.79) возвращает результат 5.

Isdate Возвращает True, если заданное значение является датой, или False – если датой не является.

Пример:

  • IsDate(«01/01/2015») возвращает True;
  • IsDate(100) возвращает False.
IsError Возвращает True, если заданное значение является ошибкой, или False – если ошибкой не является.
IsMissing В качестве аргумента функции передаётся имя необязательного аргумента процедуры. IsMissing возвращает True, если для рассматриваемого аргумента процедуры не передано значение.
IsNumeric Возвращает True, если заданное значение может быть рассмотрено как число, в противном случае возвращает False.
Left Возвращает заданное количество символов от начала переданной строки. Синтаксис функции вот такой:

Left(строка, длина)

где строка – это исходная строка, а длина – количество возвращаемых символов, считая от начала строки.

Пример:

  • Left(«абвгдежзиклмн», 4) возвращает строку «абвг»;
  • Left(«абвгдежзиклмн», 1) возвращает строку «а».
Len Возвращает количество символов в строке.

Пример: Len(«абвгдеж») возвращает число 7.

Month Возвращает целое число, соответствующее месяцу в заданной дате.

Пример: Month(«29/01/2015») возвращает значение 1.

Mid Возвращает заданное количество символов из середины переданной строки. Синтаксис функции:

Mid(строка, начало, длина)

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

Пример:

  • Mid(«абвгдежзиклмн», 4, 5) возвращает строку «гдежз»;
  • Mid(«абвгдежзиклмн», 10, 2) возвращает строку «кл».
Minute Возвращает целое число, соответствующее количеству минут в заданном времени.Пример: Minute(«22:45:15») возвращает значение 45.
Now Возвращает текущую системную дату и время.
Right Возвращает заданное количество символов от конца переданной строки. Синтаксис функции:

Right(строка, длина)

Где строка – это исходная строка, а длина – это количество символов, которые надо извлечь, считая от конца заданной строки.

Пример:

  • Right(«абвгдежзиклмн», 4) возвращает строку «клмн»;
  • Right(«абвгдежзиклмн», 1) возвращает строку «н».
Second Возвращает целое число, соответствующее количеству секунд в заданном времени.

Пример: Second(«22:45:15») возвращает значение 15.

Sqr Возвращает квадратный корень числовой величины, переданной в аргументе.

Пример:

  • Sqr(4) возвращает значение 2;
  • Sqr(16) возвращает значение 4.
Time Возвращает текущее системное время.
Ubound Возвращает верхний индекс измерения заданного массива.

Примечание: Для многомерных массивов в качестве необязательного аргумента может быть указано, индекс какого именно измерения нужо возвратить. Если не указано, то по умолчанию равно 1.

Year Возвращает целое число, соответствующее году в заданной дате.Пример: Year(«29/01/2015») возвращает значение 2015.

Данный список включает в себя только избранные наиболее часто употребляемые встроенные функции Excel Visual Basic. Исчерпывающий список функций VBA, доступных для использования в макросах Excel, можно найти на сайте Visual Basic Developer Center.

Оцените качество статьи. Нам важно ваше мнение:

Понравилась статья? Поделить с друзьями:
  • Vba excel ссылки на файл
  • Vba excel ссылка на ячейку в другой книге
  • Vba excel ссылка на эту книгу
  • Vba excel ссылка на форму
  • Vba excel ссылка на текущий лист