Excel vba заменить текст в строке

Замена части строкового выражения в VBA Excel по указанному шаблону поиска и замены и возврат преобразованной строки с помощью функции Replace.

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

Если замену подстроки необходимо осуществить в диапазоне ячеек, функцию Replace следует применить к значению каждой ячейки заданного диапазона. Проще замену в диапазоне ячеек произвести с помощью метода Range.Replace.

Синтаксис и параметры

Replace(expression, find, replace, [start], [count], [compare])

  • expression – исходное строковое выражение, содержащее подстроку, которую необходимо заменить;
  • find – искомая подстрока, подлежащая замене;
  • replace – подстрока, заменяющая искомую подстроку;
  • start – порядковый номер символа исходной строки, с которого необходимо начать поиск, часть строки до этого номера обрезается, по умолчанию равен 1 (необязательный параметр);
  • count – количество замен подстроки, по умолчанию выполняется замена всех обнаруженных вхождений (необязательный параметр);
  • compare – числовое значение, указывающее вид сравнения (необязательный параметр).

Сокращенный синтаксис функции Replace с необязательными параметрами по умолчанию:

Replace(expression, find, replace)

Параметр compare

Константа Значение Описание
vbUseCompareOption -1 используется параметр, заданный оператором Option Compare
vbBinaryCompare 0 выполняется двоичное сравнение
vbTextCompare 1 применяется текстовое сравнение

По умолчанию используется двоичное (бинарное) сравнение. При таком сравнении буквенные символы в нижнем и верхнем регистрах различаются. Если необходимо провести замену подстроки независимо от регистра букв, используйте значение параметра compare – vbTextCompare (1).

Примеры кода VBA Excel

Пример 1

Замена единственного вхождения искомой подстроки в строковое выражение:

Sub Primer1()

Dim a

a = «Сливочное масло»

a = Replace(a, «Сливочное», «Рыжиковое»)

MsgBox a

‘Результат: «Рыжиковое масло»

End Sub

Пример 2

Замена нескольких вхождений искомой подстроки в строковое выражение:

Sub Primer2()

Dim a

a = «Идёт медведь, идёт лиса, идёт грач»

‘с параметром compare по умолчанию

a = Replace(a, «идёт», «бежит»)

MsgBox a

‘Результат:

‘Идёт медведь, бежит лиса, бежит грач

a = «Идёт медведь, идёт лиса, идёт грач»

‘с параметром compare=1(vbTextCompare)

a = Replace(a, «идёт», «бежит», , , 1)

MsgBox a

‘Результат:

‘бежит медведь, бежит лиса, бежит грач

End Sub

Пример 3

Замена одного вхождения искомой подстроки в строковое выражение из нескольких с обрезанием исходной строки до 15 символа:

Sub Primer3()

Dim a

a = «Идёт медведь, идёт лиса, идёт грач»

a = Replace(a, «идёт», «бежит», 15, 1)

MsgBox a

‘Результат:

‘бежит лиса, идёт грач

End Sub

In this Article

  • Replace Function
    • Starting Position
    • Replace a Few Occurrences Only
    • Case Sensitivity
    • Double Quotes
    • Replace Break Line in Cell

This tutorial will demonstrate how to use the VBA Replace Function to replace strings of text.

Replace Function

The VBA Replace function replaces a substring of text with another substring.

Sub ReplaceExample_1()
MsgBox Replace("ABCABCABC", "A", "!")       
'Result is: "!BC!BC!BC"
MsgBox Replace("I like pink, red and black", "pink", "purple")
'Result is: "I like purple, red and black"
MsgBox Replace("A, B, C, A, B, C, A, B, C", ", ", ",")
'Result is: "ABCABCABC"

MsgBox Replace("ABCABCABC", "ABC", "!")
'Result is: "!!!"
MsgBox Replace("ABCABCABC", "ABc", "!")
'Result is: "ABCABCABC"
MsgBox Replace("ABCABCABC", "ZBC", "!")
'Result is: "ABCABCABC"

End Sub

Starting Position

By assigning a start position, you can indicate what character position to start with (default = 1).

Sub ReplaceExample_2()
MsgBox Replace("ABCABCABC", "A", "123")        'Result is: "123BC123BC123BC"
MsgBox Replace("ABCABCABC", "A", "123", 2)     'Result is: "BC123BC123BC"
MsgBox Replace("ABCABCABC", "A", "123", 7)     'Result is: "123BC"
MsgBox Replace("ABCABCABC", "A", "123", 8)     'Result is: "BC"

MsgBox Replace("ABCABCABC", "ABC", "!@")        'Result is: "!@!@!@"
MsgBox Replace("ABCABCABC", "ABC", "!@", 2)     'Result is: "BC!@!@"
MsgBox Replace("ABCABCABC", "ABC", "!@", 6)     'Result is: "C!@"
MsgBox Replace("ABCABCABC", "ABC", "!@", 7)     'Result is: "!@"
MsgBox Replace("ABCABCABC", "ABC", "!@", 8)     'Result is: "BC"

End Sub

Replace a Few Occurrences Only

You can also indicate how many instances of the substring to replace (default All)

Sub ReplaceExample_3()
MsgBox Replace("ABCABCABC", "A", "12")      'Result is: "12BC12BC12BC"
MsgBox Replace("ABCABCABC", "A", "12", , 1)     'Result is: "12BCABCABC"
MsgBox Replace("ABCABCABC", "A", "12", , 2)    'Result is: "12BC12BCABC"
MsgBox Replace("ABCABCABC", "A", "12", , 3)    'Result is: "12BC12BC12BC"
MsgBox Replace("ABCABCABC", "A", "12", , 5)    'Result is: "12BC12BC12BC"

MsgBox Replace("ABCABCABC", "A", "12", 3, 1)
'Result is: "C12BCABC"
'We replaced A with 12, 1 time starting from position 3 of the original string.

End Sub

Case Sensitivity

The Replace Function is case sensitive by default. You can switch to case insensitive by adding the optional parameter (vbTextCompare). Here, you must also define the starting position of the search.

Sub ReplaceExample_4()
MsgBox Replace("ABcABCABc", "ABc", "12")
'Result is: "12ABC12"
MsgBox Replace("ABcABCABc", "ABc", "12", , , vbTextCompare)
'Result is: "121212"
'When we use vbTextCompare we need to add the 2 other optional arguments:
'start and count

MsgBox Replace("ABcABCABcABc", "ABc", "12", 3, 1)
'Result is: "cABC12ABc"
'Started from position3 and replaced ABC only 1 time.

End Sub

You can also perform a case-insensitive Replace, by adding Option Compare Text to the top of your module:

Option Compare Text

Double Quotes

The Replace Function can replace the double quotes character used to delimit the start and end of a string.

VBA Chr function can return a character from its number in the character set.

MsgBox Chr(34) 'Result is: "

Or

MsgBox Chr(64) 'Result is: @

Double quotes can be used inside the Replace Function using “””” or VBA Function Chr(34).

Sub ReplaceExample_5()
Dim StrEx As String

StrEx = "AB""AB"""
MsgBox StrEx 'Result is: AB"AB"

MsgBox Replace(StrEx, Chr(34), "12")
'Result is: AB12AB12

MsgBox Replace(StrEx, """", "DQ")
'Result is: "ABDQABDQ"

End Sub

Replace Break Line in Cell

The Replace Function can find the break line special character in a cell and remove it or replace it with a space character. The break line special character can be entered in a cell using the keyboard shortcut Alt+Enter and can be used in VBA code with its Character set number using VBA function Chr(10).

replace line break

Sub ReplaceExample_6()
Dim StrEx As String 'Define a string variable

'Read the value of cell A2 in worksheet Sheet1
StrEx = ThisWorkbook.Worksheets("Sheet1").Range("A2").Value

'The break line character entered with Alt+Enter is Chr(10) and is invisible.
'This code line replaces that character with space
StrEx = Replace(StrEx, Chr(10), " ")

'Write the replaced value in cell B2 in worksheet Sheet1
ThisWorkbook.Worksheets("Sheet1").Range("B2").Value = StrEx

End Sub

VBA Replace String

Excel VBA Replace String

Excel VBA Replace looks for a substring within a list and replaces the substring with a second substring. When we use Excel VBA Replace Strings in Data there are some situations when we need to replace some character or a string from a sentence. If we have a large set of data that we want to replace it can be a tedious task to do it manually but with this function, it is very easy to provide the arguments and replace the string.

Syntax:

The syntax for Replace String function:

Replace ( Expression as String, Old String, New String, Start, Count, Compare)
Now the expression is the main string from where we want to remove the old string and new string which will replace the old string. The other arguments are optional. If we compare this function to excel worksheet substitute function we will find that Replace in VBA is the replacement of the substitute function in excel.

How to Replace Text in String Using VBA?

We will learn how to Replace Text in String using the VBA Code in Excel.

You can download this VBA Replace String Excel Template here – VBA Replace String Excel Template

Example #1

Let us start with a basic example of using the replace function where we will replace a simple word name from the sentence “My name is Anand”. Here we will replace Anand to Aran. For this, follow the below steps:

Step 1: Insert a new module inside Visual Basic Editor (VBE). Click on Insert tab > select Module.

Insert Module

Step 2: Insert a new subprocedure for example 1.

Code:

Sub Example1()

End Sub

VBA Replace String Example 1-1

Step 3: Declare a variable as a string.

Code:

Sub Example1()

Dim Str As String

End Sub

Variable Example 1-2

Step 4: Now let us use replace function while providing a string as the expression to the variable.

Code:

Sub Example1()

Dim Str As String
Str = Replace("My name is Anand", "Anand", "Aran")

End Sub

VBA Replace String Example 1-3

Step 5: Let us use the Msgbox function to display the value we have in this variable.

Code:

Sub Example1()

Dim Str As String
Str = Replace("My name is Anand", "Anand", "Aran")
MsgBox Str

End Sub

VBA Replace String Example 1-4

Step 6: When we execute the code.

VBA Replace String Example 1-5

Example #2

Let us begin with the second example where we can use the arguments used in the replace function as the variables. We will use a different statement for this example. For this, follow the below steps:

Step 1: In the same module let us start another subprocedure.

Code:

Sub Example2()

End Sub

VBA Replace String Example 2-1

Step 2: Now let us declare three different variables as a string.

Code:

Sub Example2()

Dim Str, Str1, Str2 As String

End Sub

Declare Three Different Variables Example 2-2

Step 3: In the first variable we can provide any string statement.

Code:

Sub Example2()

Dim Str, Str1, Str2 As String
Str = " I am a Good Boy"

End Sub

String statement Example 2-3

Step 4: Now in the second variable we can use the Input Box function to get input from the user.

Code:

Sub Example2()

Dim Str, Str1, Str2 As String
Str = " I am a Good Boy"
Str1 = InputBox("Enter a String")

End Sub

Input Box function Example 2-4

Step 5: Now in the third variable we can use the replace function to replace the second string to the desired string.

Code:

Sub Example2()

Dim Str, Str1, Str2 As String
Str = " I am a Good Boy"
Str1 = InputBox("Enter a String")
Str2 = Replace(Str, "Boy", Str1)

End Sub

VBA Replace String Example 2-5

Step 6: We will use the Msgbox function to display the result in the third string.

Code:

Sub Example2()

Dim Str, Str1, Str2 As String
Str = " I am a Good Boy"
Str1 = InputBox("Enter a String")
Str2 = Replace(Str, "Boy", Str1)
MsgBox Str2

End Sub

Msgbox function Example 2-6

Step 7: When we execute the code above and give input as “girl”.

VBA Replace String Example 2-8

Example #3

Now we will discuss one of the optional arguments in the function which is the start option where we can define from which position we want. For this, follow the below steps:

Step 1: In the same module let us start another subprocedure.

Code:

Sub Example3()

End Sub

VBA Replace String Example 3-1

Step 2: Now let us declare three different variables as a string.

Code:

Sub Example3()

Dim Str, Str1, Str2 As String

End Sub

VBA Replace String Example 3-2

Step 3: In the first variable we can provide any string statement.

Code:

Sub Example3()

Dim Str, Str1, Str2 As String
Str = " I am a Good Boy"

End Sub

VBA Replace String Example 3-3

Step 4: Now in the second variable we can use the Input Box function to get input from the user.

Code:

Sub Example3()

Dim Str, Str1, Str2 As String
Str = " I am a Good Boy"
Str1 = InputBox("Enter a String")

End Sub

Input Box function Example 3-4

Step 5: Now in the third variable we can use the replace function to replace the second string to the desired string and give start position as 7.

Code:

Sub Example3()

Dim Str, Str1, Str2 As String
Str = " I am a Good Boy"
Str1 = InputBox("Enter a String")
Str2 = Replace(Str, "Boy", Str1, Start:=7)

End Sub

VBA Replace String Example 3-5

Step 6: We can use the Msgbox function to show the result and when we execute the code which will ask us for a string.

Code:

Sub Example3()

Dim Str, Str1, Str2 As String
Str = " I am a Good Boy"
Str1 = InputBox("Enter a String")
Str2 = Replace(Str, "Boy", Str1, Start:=7)
MsgBox Str2

End Sub

Msgbox function Example 3-6

Step 7: When we press Ok we will see the final result.

VBA Replace String Example 3-7

Example #4

Now there is another optional argument which is the number of times we want to replace a string. For this, follow the below steps:

Step 1: In the same module let us start another subprocedure.

Code:

Sub Example4()

End Sub

VBA Replace String Example 4-1

Step 2: Now let us declare three different variables as a string.

Code:

Sub Example4()

Dim Str, Str1, Str2 As String

End Sub

VBA Replace String Example 4-2

Step 3: In the first variable we can provide any string statement.

Code:

Sub Example4()

Dim Str, Str1, Str2 As String
Str = " I am a Good Boy, but you are a bad boy"

End Sub

VBA Replace String Example 4-3

Step 4: Now in the second variable we can use the Input Box function to get an Input from the user.

Code:

Sub Example4()

Dim Str, Str1, Str2 As String
Str = " I am a Good Boy, but you are a bad boy"
Str1 = InputBox("Enter a String")

End Sub

Input Box function Example 4-4

Step 5: Now in the third variable we can use the replace function to replace the second string to the desired string as shown in the below screenshot and use the number of instances we want to replace the string as follows and then use msgbox function to display the result.

Code:

Sub Example4()

Dim Str, Str1, Str2 As String
Str = " I am a Good Boy, but you are a bad boy"
Str1 = InputBox("Enter a String")
Str2 = Replace(Str, "Boy", Str1, Count:=1)

End Sub

VBA Replace String Example 4-5

Step 6: Use the number of instances we want to replace the string as follows and then use the Msgbox function to display the result.

Code:

Sub Example4()

Dim Str, Str1, Str2 As String
Str = " I am a Good Boy, but you are a bad boy"
Str1 = InputBox("Enter a String")
Str2 = Replace(Str, "Boy", Str1, Count:=1)
MsgBox Str2

End Sub

VBA Replace String Example 4-6

Step 7: Once we execute the code and provide a second string as “girl” we will see the following result.

VBA Replace String Example 4-7

Explanation of VBA Replace String:

We have seen from the above examples that the Replace function is the replacement of the substitute function of excel. It has three mandatory arguments and other arguments are optional. We can use the optional arguments together or one at a time. Start refers to the position of the string whereas count refers to the number of times we want to replace the old string with the new string.

How to Use VBA Replace String?

The method to use this function is very simple and similar to excel worksheet function. This function needs three mandatory arguments:

  1. First is the expression or the main string.
  2. Then we have to provide a target string which needs to replaced.
  3. And the final argument is the string which is the new string that needs to be replaced.

Things to Remember

There are few things which we need to remember about Replace string in VBA such as follows:

  1. There are three arguments in the Replace function of excel and there are two optional arguments.
  2. The two optional arguments are either for the number of times we want to replace or the position where we want to replace.
  3. This function is similar to a substitute function in excel.

Recommended Articles

This is a guide to the VBA Replace String. Here we discuss How to Replace Text in String in Excel VBA along with practical examples and downloadable excel template. You can also go through our other suggested articles –

  1. VBA RGB
  2. VBA CDEC
  3. VBA XML
  4. VBA IsError

VBA Replace function in Excel is categorized as a Text/String function in VBA. It is a built-in function in MS Office Excel. It replaces a sub-string with another string in a given string. It has three required parameters and three optional parameters. If expression is Null, then the function returns an error. Expression contains length, then it returns an empty string.

This function use as a VBA function and a Excel Worksheet function(It has different syntax in Excel). The Replace function can be used in either procedure or function in a VBA editor window in Excel. We can use this VBA Replace function any number of times in any number of procedures or functions. In the following section we learn what is the syntax and parameters of the Replace function, where we can use this Replace function and real-time examples in VBA.

Table of Contents:

  • Overview
  • Syntax of VBA Replace Function
  • Parameters or Arguments
  • Where we can apply or use the VBA Replace Function?
  • Ex 1: Replace all occurrences of substring “F1” with “Help”
  • Ex 2: Replace all occurrences of substring “Help” with “F1”
  • Ex 3: Replace all occurrences of substring “F1” with “Help” starting from position 13
  • Ex 4: Replace all occurrences of substring “F1” with “Help” starting from position 13 and keep whole string
  • Ex 5: Replace last occurrence of substring “F1” with “Help”
  • Ex 6: Remove all occurrences of substring ‘F1’
  • Instructions to Run VBA Macro Code
  • Other Useful Resources

The syntax of the VBA Replace function is

Replace(Expression, Find, Replace, [Start], [Count], [Compare])

Note: This Replace function returns a string.

Parameters or Arguments:

This function has three mandatory parameters and three optional parameters for the Replace Function.
Where

Expression: An Expression is a mandatory argument. It represents a string expression you want to replace sub-string in.
Find: Find is a mandatory argument. It represents a sub-string which we want to find or search within an expression.
Replace: Replace is a mandatory argument. It represents a sub-string which we want to replace within an expression.
Start: Start is an optional parameter. Default value is ‘1’. It represents the position in expression to start search.
Count: Count is an optional parameter. It represents the number of occurrences to replace sub-string within an expression. Default value is ‘-1’. If we ignore, it will replace all occurrences of sub-string with another specified sub-string.
Compare: Compare is an optional parameter. It represents a numeric value. It specifies the type of comparison to evaluate the sub-strings. This argument can have anyone of the following value. Default comparison is ‘vbBinaryCompare’.

VBA Constant Value Description
vbUseCompareOption -1 Performs a comparison using the Option Compare statement.
vbBinaryCompare 0 performs a binary comparison
vbTextCompare 1 performs a text comparison
vbDatabaseCompare 2 performs a database comparison. It applies only in MS Access.

Where we can apply or use the VBA Replace Function?

We can use this VBA Replace function in MS Office 365, MS Excel 2016, MS Excel 2013, 2011, Excel 2010, Excel 2007, Excel 2003, Excel 2016 for Mac, Excel 2011 for Mac, Excel Online, Excel for iPhone, Excel for iPad, Excel for Android tablets and Excel for Android Mobiles.

Example 1: Replace all occurrences of sub-string “F1” with “Help”

Here is a simple example of the VBA Replace function. This below example macro returns a string. The output of the below macro is ‘VBAHelp’.

'Replace all occurrences of sub-string "F1" with "Help".
Sub VBA_Replace_Function_Ex1()

    Dim sString As String, sSubString As String
    
    sString = "VBAF1"
    
    sSubString = Replace(sString, "F1", "Help")
    
    MsgBox "Replace F1 with Help :" & sSubString, vbInformation, "VBA Replace Function"
    
End Sub

Output: Here is the screen shot of the first example output.
VBA Replace Function

Example 2: Replace all occurrences of substring “Help” with “F1”

Here is a simple example of the VBA Replace function. This below example macro returns a string. The output of the below macro is ‘VBAF1’.

'Replace all occurrences of sub-string "Help" with "F1".
Sub VBA_Replace_Function_Ex2()

    Dim sString As String, sSubString As String
    
    sString = "VBAF1"
    
    sSubString = Replace(sString, "Help", "F1")
    
    MsgBox "Replace Help with F1 :" & sSubString, vbInformation, "VBA Replace Function"
    
End Sub

Output: Here is the screen shot of the second example output.
VBA Replace Function

Example 3: Replace all occurrences of sub-string “F1” with “Help” starting from position 13

Here is a simple example of the VBA Replace function. This below example macro returns a string. It ignores specified ‘N(start)’ characters, when we specify start position. The output of the below macro is ‘VBAHelp-VBAHelp-VBAHelp’.

'Replace all occurrences of sub-string "F1" with "Help" starting from position 13
Sub VBA_Replace_Function_Ex3()

    Dim sString As String, sSubString As String
    
    sString = "VBAF1-VBAF1-VBAF1-VBAF1-VBAF1"
    
    sSubString = Replace(sString, "F1", "Help", 13)
    
    MsgBox "Replace F1 with Help :" & sSubString, vbInformation, "VBA Replace Function"
    
End Sub

Output: Here is the screen shot of the third example output.
VBA Replace Function

Example 4: Replace all occurrences of sub-string “F1” with “Help” starting from position 13 and keep whole string

Here is a simple example of the VBA Replace function. This below example macro returns a string. It ignores specified ’13(start)’ characters, when we specify start position. In this example we are using left function to extract left most characters from the given string. And adding the output to original output. Here is the final output of the below macro is ‘VBAF1-VBAF1-VBAHelp-VBAHelp-VBAHelp’.

'Replace all occurrences of sub-string "F1" with "Help" starting from position 13 and keep whole string
Sub VBA_Replace_Function_Ex4()

    Dim sString As String, sSubString As String
    
    sString = "VBAF1-VBAF1-VBAF1-VBAF1-VBAF1"
    
    sSubString = Left(sString, 12) & Replace(sString, "F1", "Help", 13)
    
    MsgBox "Replace F1 with Help :" & sSubString, vbInformation, "VBA Replace Function"
    
End Sub

Output: Here is the screen shot of the fourth example output.
VBA Replace Function

Example 5: Replace last occurrence of sub-string “F1” with “Help”

Here is a simple example of the VBA Replace function. This below example macro returns a string. Here is the final output of the below macro is ‘VBAF1-VBAF1-VBAF1-VBAF1-VBAHelp’.

'Replace last occurrence of substring "F1" with "Help"
Sub VBA_Replace_Function_Ex5()

    Dim sString As String, sSubString As String
    
    sString = "VBAF1-VBAF1-VBAF1-VBAF1-VBAF1"
    
    sString = StrReverse(sString)
    
    sString = Replace(sString, StrReverse("F1"), StrReverse("Help"), , 1)
    
    sSubString = StrReverse(sString)
    
    MsgBox "Replace F1 with Help :" & sSubString, vbInformation, "VBA Replace Function"
    
End Sub

Output: Here is the screen shot of the fifth example output.
VBA Replace Function

Example 6: Remove all occurrences of sub-string ‘F1’

Here is a simple example of the VBA Replace function. This below example macro returns a string. It removes all occurrences of sub-string within a string. Here is the final output of the below macro is ‘VBA-VBA-VBA-VBA-VBA’.

'Remove all occurrences of sub-string 'F1'
Sub VBA_Replace_Function_Ex6()

    Dim sString As String, sSubString As String
    
    sString = "VBAF1-VBAF1-VBAF1-VBAF1-VBAF1"
    
    sSubString = Replace(sString, "F1", "")
    
    MsgBox "Remove all occurences of F1 :" & sSubString, vbInformation, "VBA Replace Function"
    
End Sub

Output: Here is the screen shot of the sixth example output.
VBA Replace Function

Instructions to Run VBA Macro Code or Procedure:

You can refer the following link for the step by step instructions.

Instructions to run VBA Macro Code

Other Useful Resources:

Click on the following links of the useful resources. These helps to learn and gain more knowledge.

VBA Tutorial VBA Functions List VBA Arrays in Excel Blog

VBA Editor Keyboard Shortcut Keys List VBA Interview Questions & Answers

Главная » Функции VBA »

28 Апрель 2011              351372 просмотров

  • ASC()— эта функция позволяет вернуть числовой код для переданного символа. Например, ASC("D") вернет 68. Эту функцию удобно использовать для того, чтобы определить следующую или предыдущую букву. Обычно она используется вместе с функцией Chr(), которая производит обратную операцию — возвращает символ по переданному его числовому коду.Варианты этой функции — AscB() и AscW():
    • AscB() — возвращает только первый байт числового кода для символа.
    • AscW() — возвращает код для символа в кодировке Unicode
  • Chr() — возвращает символ по его числовому коду. Может использоваться в паре с функцией Asc(), но чаще всего её применяют, когда нужно вывести служебный символ (например кавычки — "), т.к. кавычки просто так в VBA-коде не ввести(нужно ставить двойные). Я обычно именно эту функцию и использую.
        Dim sWord As String
        sWord = Chr(34) & "Слово в кавычках" & Chr(34)

    Есть варианты этой функции — ChrB() и ChrW(). Работают аналогично таким же вариантам для функции Asc().

  • InStr() и InStrRev()— одна из самых популярных функций. Позволяет обнаружить в теле строковой переменной символ или последовательность символов и вернуть их позицию. Если последовательность не обнаружена, то возвращается 0.
        Dim sStr As String
        sStr = "w"
        If InStr(1, "Hello, World!", sStr, vbTextCompare) > 0 Then
            MsgBox "Искомое слово присутствует!"
        Else
            MsgBox "Искомое слово отсутствует!"
        End If

    Разница функций в том, что InStr() ищет указанное слово от начала строки, а InStrRev() с конца строки

  • Left(), Right(), Mid()— возможность взять указанное вами количество символов из существующей строковой переменной слева, справа или из середины соответственно.
        Dim sStr As String
        sStr = "Hello, World!"
        MsgBox Mid(sStr, 1, 5)
  • Len() — возможность получить число символов в строке. Часто используется с циклами, операциями замены и т.п.
  • LCase() и UCase() — перевести строку в нижний и верхний регистры соответственно. Часто используется для подготовки значения к сравнению, когда при сравнении регистр не важен (фамилии, названия фирм, городов и т.п.).
  • LSet() и RSet() — возможность заполнить одну переменную символами другой без изменения ее длины (соответственно слева и справа). Лишние символы обрезаются, на место недостающих подставляются пробелы.
  • LTrim(), RTrim(), Trim() — возможность убрать пробелы соответственно слева, справа или и слева, и справа.
  • Replace()— возможность заменить в строке одну последовательность символов на другую.
        Dim sStr As String
        sStr = "Hello, World!"
        MsgBox Replace(sStr, "Hello", "Bay")
  • Space() — получить строку из указанного вами количества пробелов;
    Еще одна похожая функция — Spc(), которая используется для форматирования вывода на консоль. Она размножает пробелы с учетом ширины командной строки.
  • StrComp() — возможность сравнить две строки.
  • StrConv() — возможность преобразовать строку (в Unicode и обратно, в верхний и нижний регистр, сделать первую букву слов заглавной и т.п.):
        Dim sStr As String
        sStr = "Hello, World!"
        MsgBox StrConv("Hello, World!", vbUpperCase)

    В качестве второго параметра параметра могут применяться константы:

    • vbUpperCase: Преобразует все текстовые символы в ВЕРХНИЙ РЕГИСТР
    • vbLowerCase: Преобразует все текстовые символы в нижний регистр
    • vbProperCase: Переводит первый символ каждого слова в Верхний Регистр
    • *vbWide: Преобразует символы строки из однобайтовых в двухбайтовые
    • *vbNarrow: Преобразует символы строки из двухбайтовых в однобайтовые
    • **vbKatakana: Преобразует символы Hiragana в символы Katakana
    • **vbHiragana: Преобразует символы Katakana в символы Hiragana
    • ***vbUnicode: Преобразует строку в Юникод с помощью кодовой страницы системы по умолчанию
    • ***vbFromUnicode: Преобразует строку из Юникод в кодовую страницу системы по умолчанию
    • * применимо для локализацией Дальнего востока
      ** применимо только для Японии
      *** не поддерживается операционными системами под управлением Macintosh

  • StrReverse() — «перевернуть» строку, разместив ее символы в обратном порядке. Функция работает только начиная от Excel 2000 и выше. Пример использования функции, а так же иные методы переворачивания слова можно посмотреть в этой статье: Как перевернуть слово?
  • Tab() — еще одна функция, которая используется для форматирования вывода на консоль. Размножает символы табуляции в том количестве, в котором вы укажете. Если никакое количество не указано, просто вставляет символ табуляции. Для вставки символа табуляции в строковое значение можно также использовать константу vbTab.
  • String() — позволяет получить строку из указанного количества символов (которые опять-таки указываются Вами). Обычно используются для форматирования вывода совместно с функцией Len().

Статья помогла? Сделай твит, поделись ссылкой с друзьями!

Понравилась статья? Поделить с друзьями:
  • Excel vba заменить символ в ячейке excel
  • Excel vba если или
  • Excel vba заменить лист
  • Excel vba если значение ячейки не число
  • Excel vba замена подстроки в строке