Vba excel регистр букв

Смена регистра буквенных символов в VBA Excel с помощью функции StrConv. Преобразование всех букв в верхний или нижний регистр, а также первых букв каждого слова в верхний.

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

В VBA Excel доступны следующие типы преобразования:

  • символов строки в верхний или нижний регистр;
  • однобайтовых символов в двухбайтовые и обратно;
  • знаков хирагана в катакана и наоборот (формы японской слоговой азбуки);
  • символов строки из формата системной кодовой страницы по умолчанию в Юникод и обратно.

Далее рассмотрим только преобразование букв в верхний или нижний регистр, используя сокращенный синтаксис функции StrConv. Со всеми возможностями этой функции вы можете ознакомиться на сайте разработчика.

Синтаксис функции StrConv

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

StrConv(string, conversion)

  • string – исходное строковое выражение;
  • conversion – тип преобразования.

Тип преобразования

Для смены регистра букв используются следующие типы преобразования (conversion):

Константа Значение Описание
vbUpperCase 1 преобразование всех символов исходной строки в верхний регистр
vbLowerCase 2 преобразование всех символов исходной строки в нижний регистр
vbProperCase 3 преобразование первой буквы каждого слова исходной строки в верхний регистр

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

Пример 1

Стандартное преобразование регистра букв:

Sub Primer1()

Dim a, b, c

a = StrConv(«чиСтота – зАЛОг здОроВья», 1)

b = StrConv(«чиСтота – зАЛОг здОроВья», 2)

c = StrConv(«чиСтота – зАЛОг здОроВья», 3)

MsgBox a & vbNewLine & b & vbNewLine & c

‘Результат:

‘ЧИСТОТА – ЗАЛОГ ЗДОРОВЬЯ

‘чистота – залог здоровья

‘Чистота – Залог Здоровья

End Sub

Обратите внимание, что при указании типа преобразования vbProperCase (3), не только первые буквы слов преобразуются в верхний регистр, но и все остальные – в нижний.

Пример 2

Преобразование только первой буквы предложения в заглавную (в верхний регистр):

Sub Primer2()

Dim a, b

a = «чиСтота – зАЛОг здОроВья»

‘преобразуем все символы в нижний регистр

a = StrConv(a, 2)

‘извлекаем первую букву предложения и

‘преобразуем ее в верхний регистр

b = StrConv(Left(a, 1), 1)

‘заменяем первую букву в предложении

a = b & Mid(a, 2)

MsgBox a

‘Результат: «Чистота – залог здоровья»

End Sub

То же самое, но немного по-другому:

Sub Primer2()

Dim a

a = «чиСтота – зАЛОг здОроВья»

‘преобразуем все символы в нижний регистр

a = StrConv(a, 2)

‘заменяем первую букву в предложении этой же буквой,

‘преобразованной в верхний регистр

a = Replace(a, Left(a, 1), StrConv(Left(a, 1), 1), 1, 1)

‘смотрим результат

MsgBox a

End Sub

Подробнее о функции Replace в следующей статье.

Return to VBA Code Examples

In this Article

  • UCase – Convert String to Upper Case
  • LCase – Convert String to Lower Case
  • StrConv – Convert String to Proper Case
  • StrConv – Convert String to Upper or Lower Case
  • VBA Upper, Lower, and Proper Case – Case Functions in Access

This tutorial will demonstrate how to use the UCASE, LCASE and STRCONV functions in VBA.

While working in VBA, you often need to convert strings into lowercase, uppercase or proper case. This is possible by using the UCase, LCase and StrConv functions.

These functions are important when manipulating strings in VBA, as VBA is case sensitive. If you wish to make VBA case-insensitive, you need to add Option Compare Text at the top of your module. You can find out more about this here: Prevent VBA Case Sensitive

UCase – Convert String to Upper Case

The UCase function in VBA converts all letters of a string into uppercase. There is only one argument, which can be a string, variable with string or a cell value. This function is often used if you want to compare two strings. Here is the code for the UCase function:

Dim strText As String
Dim strTextUCase As String

strText = "running Uppercase function"

strTextUCase = UCase(strText)

MsgBox strTextUCase

In the example, we want to convert all letters of the strText variable to upper case and assign the converted string to the strTextUCase variable. At the end we call the message box with the converted string:vba-uppercase-function

LCase – Convert String to Lower Case

If you want to convert all letters of a string into lower cases, you need to use the LCase function. This function has one argument, the same as the UCase. This is the code for the LCase function:

Dim strText As String
Dim strTextLCase As String

strText = "RUNNING lowerCASE FUNCTION"

strTextLCase = LCase(strText)

MsgBox strTextLCase

In this example, we convert all letters of the string variable strText into lower case. After that, the converted string is assigned to the variable strTextLCase.

vba-lowercase-function

StrConv – Convert String to Proper Case

The StrConv function enables you to convert a string of text into proper case. The function has two arguments. First is the string that you want to convert. The second is the type of the conversion which you want. In order to convert a string to a proper case, you need to set it to vbProperCase. The code for the function is:

Dim strText As String
Dim strTextProperCase As String
    
strText = "running proper case function"
    
strTextProperCase = StrConv(strText, vbProperCase)
    
MsgBox strTextProperCase

You will see on the example how the function works. It takes the string from the cell B1, converts it to proper case and returns the value in the cell A1.

vba-proper-case-function

StrConv – Convert String to Upper or Lower Case

Using the StrConv function, you can also convert a string to upper or lower cases. To do this, you just need to set the second argument to the vbUpperCase or vbLowerCase:

strTextConverted = StrConv(strText, vbUpperCase)
strTextConverted = StrConv(strText, vbLowerCase)

VBA Upper, Lower, and Proper Case – Case Functions in Access

All of the above examples work exactly the same in Access VBA as in Excel VBA.

Private Sub ClientName_AfterUpdate()
   'this will convert the text in the client name box to uppercase
   Me.ClientName = UCase(Me.ClientName)
End Sub

vba ucase access

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
vba save as

Learn More!

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

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

  • 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 StrConv Function

The StrConv function in VBA comes under String functions, a conversion function. One may use this function because it changes the case of the string with the input provided by the developer. In addition, the arguments of this function are the string. So, for example, the input for a case like 1 is to change the string to lowercase.

StrConv stands for “String Conversion.” We can convert the supplied string to the specified format using this VBA functionVBA functions serve the primary purpose to carry out specific calculations and to return a value. Therefore, in VBA, we use syntax to specify the parameters and data type while defining the function. Such functions are called user-defined functions.read more. You need to understand that we can use this formula as a VBA function only, not as an Excel worksheet function. This article will tour detailed examples of the “VBA StrConv” formula.

Look at the syntax of the StrConv function.

VBA StrConv syntax

String: This is nothing but the text we are trying to convert.

Conversion: What kind of conversion do we need to do? We have a wide variety of options. Here, below is the list of conversions we can perform.

  • vbUpperCase or 1: This option converts the supplied Text value to upper case character. It works similarly to the UCASE function. For example, if you supply the word “Excel,” it will convert to “EXCEL.”
  • vbLowerCase or 2: This option converts the supplied Text value to lowercase character in excelThere are six methods to change lowercase in excel — Using the lower function to change case in excel, Using the VBA command button, VBA shortcut key, Using Flash Fill, Enter text in lower case only, Using Microsoft word.
    read more
    . It works similarly to the LCASE function. For example, if you supply the word “Excel,” it will convert to “excel.”
  • vbProperCase or 3: This option converts the supplied Text value to the proper case character. Every first character of the word converts to uppercase. All the remaining letters convert to lowercase. For example, if you supply the word “excEL,” it will convert to “Excel.”
  • vbUniCode or 64: This option converts the string to Unicode code.
  • vbFromUnicode or 128: It converts the string Unicode to the default system code.

Even though we have several other options with the Conversion argument above, three are good enough for us.

LCID: This is the Locale ID. By default, it takes the system ID. It will not use 99% of the time.

Table of contents
  • Excel VBA StrConv Function
    • Examples of StrConv Function in VBA
      • Example #1
      • Example #2
      • Example #3
      • Example #4
    • Recommended Articles

VBA StrConv

You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA StrConv (wallstreetmojo.com)

You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA StrConv (wallstreetmojo.com)

Examples of StrConv Function in VBA

You can download this VBA StrConv Function Template here – VBA StrConv Function Template

Example #1

Now, look at the example of converting the string to the UPPER CASE character. We are using the word “Excel VBA” here. Below is the VBA codeVBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task.read more.

Code:

Sub StrConv_Example1()

    Dim TextValues As String
    Dim Result As String

    TextValues = "Excel vba"

    Result = StrConv(TextValues, vbUpperCase)

    MsgBox Result

End Sub

VBA StrConv Example 1

It will convert the string “Excel VBA” to upper case.

Run this code using the F5 key or manually and see the result.

VBA StrConv Example 1-1

Example #2

Now, take a look at the same string with lowercase conversion. Below is the code.

Code:

Sub StrConv_Example2()

    Dim TextValues As String
    Dim Result As String

    TextValues = "Excel vba"

    Result = StrConv(TextValues, vbLowerCase)

    MsgBox Result

End Sub

VBA StrConv Example 2

It will convert the string “Excel VBA” to a lowercase.

You can run it manually or through excel shortcut keyAn Excel shortcut is a technique of performing a manual task in a quicker way.read more F5. Below is the result.

VBA StrConv Example 2-1

Example #3

Now, take a look at the same string with proper case conversion. Below is the code.

Code:

Sub StrConv_Example3()

    Dim TextValues As String
    Dim Result As String

    TextValues = "Excel vba"

    Result = StrConv(TextValues, vbProperCase)

    MsgBox Result

End Sub

Example 3

It will convert the string “Excel VBA” to a proper case. Every first letter of the string is upper case. Moreover, it converts every letter after space to uppercase. All the remaining characters convert to lowercase. Below is the result of the same.

Example 3-1

Example #4

Now, look at the Unicode character’s example. Look at the below code.

Code:

Sub StrConv_Example4()

  Dim i As Long
  Dim x() As Byte
  x = StrConv("ExcelVBA", vbFromUnicode)
  For i = 0 To UBound(x)
  Debug.Print x(i)
 Next

End Sub

It will print all the Unicode characters to the immediate window.

Example 4

In ASCII code, “E” Unicode is 69, “x” Unicode is 120, and so on. Like this, using VBA StrConv, we can convert the string to Unicode.

Example 4-1

Recommended Articles

This article has been a guide to VBA StrConv. Here, we learn how to use the VBA StrConv function to convert the supplied string to the specified format, along with practical examples and a downloadable Excel template. Below you can find some useful Excel VBA articles: –

  • VBA Operators
  • VBA Charts
  • VBA Boolean Operator
  • VBA End

totn Excel Functions


This Excel tutorial explains how to use the Excel STRCONV function with syntax and examples.

Description

The Microsoft Excel STRCONV function returns a string converted to uppercase, lowercase, proper case or Unicode.

The STRCONV function is a built-in function in Excel that is categorized as a String/Text Function. It can be used as a VBA function (VBA) in Excel. As a VBA function, you can use this function in macro code that is entered through the Microsoft Visual Basic Editor.

Syntax

The syntax for the STRCONV function in Microsoft Excel is:

StrConv ( text, conversion, [LCID] )

Parameters or Arguments

text
The string that you wish to convert.
conversion

The type of conversion to perform. The following is a list of valid parameters for conversion.

Parameter Value Description
vbUpperCase 1 Converts the string to all uppercase.
vbLowerCase 2 Converts the string to all lowercase.
vbProperCase 3 Converts the first letter to every word to uppercase. All other characters are left as lowercase. This option is similar to the InitCap function in Oracle.
vbUnicode 64 Converts the string to Unicode.
vbFromUnicode 128 Converts the string from Unicode to the default code page of the system.
LCID
Optional. If this parameter is omitted, it assumes the system LocaleID.

Returns

The STRCONV function returns a string value.

Applies To

  • Excel for Office 365, Excel 2019, Excel 2016, Excel 2013, Excel 2011 for Mac, Excel 2010, Excel 2007, Excel 2003, Excel XP, Excel 2000

Type of Function

  • VBA function (VBA)

Example (as VBA Function)

The STRCONV function can only be used in VBA code in Microsoft Excel.

Let’s look at some Excel STRCONV function examples and explore how to use the STRCONV function in Excel VBA code:

StrConv("tech on the net", 1)
Result: "TECH ON THE NET"

StrConv("TECH ON THE NET", 2)
Result: "tech on the net"

StrConv("TECH ON THE NET", 3)
Result: "Tech On The Net"

For example:

Dim LResult As String

LResult = StrConv("TECH ON THE NET", vbProperCase)

In this example, the variable called LResult would now contain the value «Tech On The Net».

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