Excel vba char string

  1. 11-04-2013, 03:22 PM


    #1

    RoOmIE is offline


    Registered User


    Lightbulb How to access a char from a string? vba

    how can i access a char in a string using vba code?? i tried using

    char = left((right(word), i),1)

    but it doesnt work

    thanks in advance!


  2. 11-04-2013, 03:29 PM


    #2

    Re: How to access a char from a string? vba

    Suggest you post an example of what you are trying to do specifically. Your explanation does not provide enough detail and my crystal ball fell on the floor yesterday and shattered.


  3. 11-04-2013, 03:32 PM


    #3

    RoOmIE is offline


    Registered User


    Re: How to access a char from a string? vba

    ok for example i have something like 1,234,567,89 and i would like to access the 9 .. then the 8 then the comma then the 7 then the 6 then .. so on


  4. 11-04-2013, 03:36 PM


    #4

    RoOmIE is offline


    Registered User


    Re: How to access a char from a string? vba

    store them one at a time in the value of char

    The main macro that i am making converts a string of numbers from text so that excel can interprate it as a number


  5. 11-04-2013, 03:38 PM


    #5

    Re: How to access a char from a string? vba

    deleted as the response was not correct.


  6. 11-04-2013, 03:50 PM


    #6

    RoOmIE is offline


    Registered User


    Re: How to access a char from a string? vba

    http://msdn.microsoft.com/en-us/libr…/ms233783.aspx

    i tried this as well but it doesn’t seem to work in excel


  7. 11-04-2013, 04:07 PM


    #7

    Re: How to access a char from a string? vba

    Is 1,234,567,89 the string you want to convert to a number?

    If it is then you could probably do it without going through each character one by one.

    What should the result be, 123456789 or 1234567.89?

    PS That link is for VB.NET.

    If posting code please use code tags, see here.


  8. 11-04-2013, 04:22 PM


    #8

    RoOmIE is offline


    Registered User


    Re: How to access a char from a string? vba

    There are two possibilities 1.234.567,89 becomes 1234567.89 and 1,234,567.89 is also 1234567.89

    yes the 1,234,567,89 is the string i want converted to a number ..

    i am trying to do it for every number possible .. not only those .. so the number 15,65413551 should be 15.65413551


  9. 11-04-2013, 04:32 PM


    #9

    RoOmIE is offline


    Registered User


    Re: How to access a char from a string? vba

    there is the code i made so that it could work


  10. 11-04-2013, 04:45 PM


    #10

    Re: How to access a char from a string? vba

    Don’t you mean at least 3 possibilities?

    1.234.567,89
    1,234,567.89
    1,234,567,89

    1.234.567.89 perhaps?


  11. 11-04-2013, 04:52 PM


    #11

    RoOmIE is offline


    Registered User


    Re: How to access a char from a string? vba

    yes but the program that those are being extracted from (SAP) don’t have the other two .. and there are still some bugs in my code ..


  12. 11-04-2013, 04:58 PM


    #12

    Re: How to access a char from a string? vba

    What 2 does SAP have?

    Your original post was about the string, 1,234,567,89.

    Then in a later post you post 3 more example strings, 1.234.567,89, 1,234,567.89 and 15,65413551.

    I’m pretty sure if you can clarify what you have then a solution that doesn’t involve going through every character could be found.

    By the way, why are you getting this data in different number formats?


  13. 11-04-2013, 05:06 PM


    #13

    RoOmIE is offline


    Registered User


    Re: How to access a char from a string? vba

    sap technically has 3 but one is recongnized by excel as a number right away witch is 1 234 567,89

    and the two that don’t work are 1,234,567.89
    and 1.234.567,89

    sorry about the confusion ..

    norie .. sap is a pice of crap software .. is the best answer i can give you


  14. 11-04-2013, 07:29 PM


    #14

    Re: How to access a char from a string? vba

    I’ve used SAP before and I can’t recall it having different formats like that.

    Actually I think there was some (personal?) setting you could change to control numebr formats.

    Could you attach a workbook with some sample data that shows examples of all the different formats?


  15. 11-05-2013, 09:30 AM


    #15

    RoOmIE is offline


    Registered User


    Re: How to access a char from a string? vba

    yes it is a personal setting, but many people use sap here and if one person extracts with a different setting then i have to change all the numbers from text to numbers especially when we get to the thousands.

    sap errors2.xlsx


  16. 11-05-2013, 09:32 AM


    #16

    Re: How to access a char from a string? vba

    I’ll have a look at the file, but a couple of quick questions.

    When you extract data how are you doing it?

    Also, does the extracted data have always have a mixture of date formats or does each extract always have the same date format?


  17. 11-05-2013, 09:38 AM


    #17

    RoOmIE is offline


    Registered User


    Re: How to access a char from a string? vba

    We usually extract it with the extract to excel button .

    Its a good question I still don’t know the exact answer to that since i am not the one who does the extracts.


  18. 11-05-2013, 09:57 AM


    #18

    Re: How to access a char from a string? vba

    I was able to use Data>Text to columns… in your sample workbook to conver to numeric values.

    All I did was change round the decimal and thousand operators on the last step by going to Advanced…

    I don’t know if that will work for all the formats you are encountering but it does with your sample data.


  19. 11-05-2013, 10:16 AM


    #19

    Re: How to access a char from a string? vba

    Not sure but, is this how you wanted?

    If not, I need to see Before/After in the workbook.


  20. 11-05-2013, 11:20 AM


    #20

    slx is offline


    Forum Contributor


    Re: How to access a char from a string? vba

    to access the a character in a string you can use len() with for loop to get the position of each character in that string


  21. 11-05-2013, 12:19 PM


    #21

    RoOmIE is offline


    Registered User


    Re: How to access a char from a string? vba

    slx that didn’t work in my case … it doesn’t give me the results that i want ..sap errors2.xlsx jindon look on sheet 2 for the desired answer


  22. 11-05-2013, 12:37 PM


    #22

    RoOmIE is offline


    Registered User


    Re: How to access a char from a string? vba

    i made a mistake in the answer sheet … but i believe i just realized something


  23. 11-05-2013, 12:51 PM


    #23

    Re: How to access a char from a string? vba


  24. 11-05-2013, 01:13 PM


    #24

    slx is offline


    Forum Contributor


    Re: How to access a char from a string? vba

    Here’s it is going right to left.

    To fix your problem u need to have clear rules.
    Starting with replace all «,» with «.». Then count the «.», if there is only 1, then remove it If there more than 1, then use the first «.» from the right. If there is none then leave it alone.


  25. 11-05-2013, 02:04 PM


    #25

    RoOmIE is offline


    Registered User


    Re: How to access a char from a string? vba

    nice try but no ciggar .. yudlugar i get an infinite loop and slx it just doesn’t work it does nothing ..


  26. 11-05-2013, 02:29 PM


    #26

    Re: How to access a char from a string? vba

    Have you actually tried my code?


  27. 11-05-2013, 03:21 PM


    #27

    RoOmIE is offline


    Registered User


    Re: How to access a char from a string? vba

    jindon it works just that for the first one it should be 3000 ml and for the second it should be 6000 ml instead of 3 ml and 6 ml sorry..


  28. 11-05-2013, 04:46 PM


    #28

    Re: How to access a char from a string? vba


  29. 11-05-2013, 04:55 PM


    #29

    Re: How to access a char from a string? vba


  30. 11-05-2013, 05:12 PM


    #30

    slx is offline


    Forum Contributor


    Re: How to access a char from a string? vba

    Roomie, it works, you have to be on sheet1 for it work since i didn’t reference worksheets. The answer gets put in column «L» as demonstration.


  31. 11-06-2013, 09:01 AM


    #31

    Re: How to access a char from a string? vba


  32. 11-06-2013, 02:10 PM


    #32

    RoOmIE is offline


    Registered User


    Re: How to access a char from a string? vba

    jindon could we have the range change with the active cell function .. like change the values but only in the cell that is selected.. …. i don’t know if i’m speaking Japanese


  33. 11-07-2013, 02:58 AM


    #33

    Re: How to access a char from a string? vba


Excel Text and String Functions:

Excel CODE & CHAR Functions, VBA Asc & Chr Functions, with examples.

Related Links:

1. Using VBA Chr and Asc functions to convert excel column number to corresponding column letter, and column letter to column number.

2. ASCII Code, Extended ASCII characters (8-bit system) and ANSI Code.

3. Excel Text and String Functions: TRIM & CLEAN.

4. Excel Text and String Functions: LEFT, RIGHT, MID, LEN, FIND, SEARCH, REPLACE, SUBSTITUTE.


Excel CODE Function (Worksheet)

The CODE Function returns the identifying numeric code of the first character in a text string. A ‘character set’ maps characters to their identifying code values, and may vary across operating environments viz. Windows, Macintosh, etc. The Windows operating environment uses the ANSI character set, whereas Macintosh uses the Macintosh character set. The returned numeric code corresponds to this character set — for a Windows computer, Excel uses the standard ANSI character set to return the numeric code. Syntax: CODE(text_string). The text_string argument is the text string whose first character’s numeric code is returned.  

The equivalent of excel CODE function in vba is the Asc function. Note that the Excel CODE function is the inverse of the Excel CHAR function. The formula =CODE(CHAR(65)) returns 65, because =CHAR(65) returns the character «A» and =CODE(«A») returns 65. 

In a Windows computer, Code function will return values as follows:

=CODE(«A») returns 65.

=CODE(«B») returns 66.

=CODE(«a») returns 97.

=CODE(«b») returns 98.

=CODE(«0») returns 48.

=CODE(«1») returns 49.

=CODE(«-1») returns 45, which is the code for «-» (hyphen) .

=CODE(» «) , note the space between inverted commas, returns 32.

=CODE(«»), no space between inverted commas, returns the #VALUE! error value.

=CODE(«America») returns 65, which is the code for «A», the first character in the text string.

=CODE(A1) returns 66, using cell reference. If cell A1 contains the text «Bond», CODE(A1) returns 66, which is the code for «B», the first character in the text string.

=CODE(«?») returns 63.

=CODE(«™») returns 153.


Excel CHAR Function (Worksheet)

Use the CHAR Function to return the character identified to the specified number. A ‘character set’ maps characters to their identifying code values, and may vary across operating environments viz. Windows, Macintosh, etc. The Windows operating environment uses the ANSI character set, whereas Macintosh uses the Macintosh character set. The returned character corresponds to this character set — for a Windows computer, Excel uses the standard ANSI character set. Syntax: CHAR(number). The number argument is a number between 1 and 255 which identifies the returned character. The function returns the #VALUE! error value if this argument is not a number between 1 and 255.

The equivalent of excel CHAR function in vba is the Chr function. Note that the Excel CHAR function is the inverse of the Excel CODE function. The formula =CHAR(CODE(«A»)) returns A, because =CODE(«A») returns the number 65 and =CHAR(65) returns A. 

In a Windows computer, Char function will return values as follows:

=CHAR(65) returns the character «A».

=CHAR(37) returns the character «%».

=CHAR(260) returns the #VALUE! error value.

=CHAR(163) returns the character «£».

=CHAR(A1) returns the character «B», using cell reference. If cell A1 contains the number 66, CHAR(A1) returns the character «B».


Examples of using the Excel CODE & CHAR Functions

Changing case (uppercase / lowercase) of alphabets in a string

Formula  =CHAR(CODE(A1)+32) returns the lowercase letter «b», if cell A1 contains the uppercase letter «B». This is because in the ANSI character set, the lowercase alphabets appear after uppercase alphabets, in an alphabetic order,  with a difference of exactly 32 numbers. Similarly, =CHAR(CODE(A1)-32) returns the uppercase letter «B», if cell A1 contains the lowercase letter «b».

Convert first character of the first word in a text string (consisting of letters), to lowercase, and first character of all subsequent words to uppercase. To convert the string «we like james bond» in cell A1 to «we Like James Bond» use the following formula:

=REPLACE(PROPER(A1), 1,1, CHAR(CODE( LEFT(PROPER(A1)))+32))

=PROPER(A1)   returns the text string «We Like James Bond».

=CHAR(CODE(LEFT( PROPER(A1)))+32)   returns the lowercase text «w».

The formula replaces the first character of the text, by first capitalizing it and then converting it to lowercase using CHAR/CODE functions.

It may however be noted, that the excel UPPER (or LOWER) function can also be used as alternate to CHAR/CODE functions. In this case the Formula  =REPLACE(PROPER(A1),1,1,LOWER(LEFT(PROPER(A1)))) will also give the same result and return the string «we Like James Bond».

—————————————————————————————————————————-

Making the above formula more complex:

Convert first character of the second word in a text string (consisting of letters) to lowercase, and the first character of all other words to uppercase (wherein words are separated by a single space). To convert the string «we Like James bond» in cell A1 to «We like James Bond» use the following formula: 

=REPLACE(PROPER(A1), FIND(» «, A1)+1, 1, CHAR(CODE(MID(PROPER(A1), FIND(» «, A1)+1, 1))+32))

=PROPER(A1)   returns text string «We Like James Bond».

=FIND(» «, A1)+1   returns the position 4.

=MID(PROPER(A1), FIND(» «, A1)+1,1)    returns L.

=CODE(MID(PROPER(A1), FIND(» «, A1)+1,1))    returns 76.

=CHAR(CODE(MID(PROPER(A1), FIND(» «, A1)+1,1))+32)   returns the text «l».

—————————————————————————————————————————  

If a text string has irregular spacing (ie. having lead spaces and multiple spaces between words), insert the TRIM function which removes all spaces from text except for single spaces between words:

=REPLACE(PROPER( TRIM(A1)), FIND(» «, TRIM(A1))+1, 1, CHAR(CODE(MID( PROPER( TRIM(A1)), FIND(» «, TRIM(A1))+1, 1))+32)) 

Note: In addition to the CHAR, CODE, LEFT & MID functions, we have also used the excel worksheet PROPER function. Syntax: PROPER(text).  This function: (i) Capitalizes any letter in a text string which follows a non-letter character, and also the first letter of the text string; (ii) Converts to Lowercase all other letters.

—————————————————————————————————————————

For many letters and controls, it might be much easier to format or otherwise manipulate data with their ANSI codes than using your keyboard.

If the address is currently split in different cells, and you wish to consolidate in a single cell in multiple lines, use the excel CHAR function as follows (refer Image 1):

=A1 & CHAR(10) & B1 & CHAR(10) & C1 & CHAR(10) & D1

The address is currently split in cells A1 to D1 and the above formula consolidates and formats into a single cell in multiple lines.

10 is the ANSI code (number) for line feed, and it provides the line breaks to format data.

Ensure that the cell text wrapping is enabled, by clicking on «Wrap Text».

————————————————————————————————————————-

Format a single line address into multiple lines, using the excel CHAR & SUBSTITUTE functions as follows (refer Image 2):

=SUBSTITUTE(A1,», «,CHAR(10))

The address is currently mentioned in cell A1 in a single line, and the above formula formats it (in cell A3) by removing commas and into multiple lines.

10 is the ANSI code (number) for line feed, and it provides the line breaks to format data.

Ensure that the cell text wrapping is enabled, by clicking on «Wrap Text».

—————————————————————————————————————————

NOTE: To format an address with line breaks (appearing in multiple lines in cell A1) to a single line format (cell A3), use the formula (refer Image 3): =SUBSTITUTE(A1, CHAR(10), «, «) 

——————————————————————————————————————————  

To insert special characters or symbols in a text string, use the excel CHAR function:

=»Exchange Rates Graph of Pound (» & CHAR(163) & «), Euro (» & CHAR(128) & «) and Dollar (» & (CHAR(36) & «)»)

The above formula inserts currency symbols, using the CHAR function.

Returns the text string: «Exchange Rates Graph of Pound (£), Euro(€) and Dollar ($)»


VBA Asc function

The vba Asc function returns the corresponding character code (Integer data type) for the first letter of a string. Syntax: Asc(string). It is necessary to specify the string argument — it is a string expression whose first letter’s character code is returned. You will get a run time error for a string with no characters. For non-DBCS systems the normal range for the returned number is 0 to 255, but on DBCS systems the range is -32768 to 32767.

Use the AscW function to return a Unicode character code, but if the platform does not support Unicode then AscW will give results identical to the Asc function. AscW should not be used in the Macintosh environment because Unicode strings are not supported in Visual Basic for the Macintosh.

VBA Chr function

The vba Chr function returns a character (string data type) identified to the specified character code. Syntax: Chr(charcode). It is necessary to specify the charcode argument — it is the character code (Long data type) which identifies the returned character. The normal range for charcode is 0 to 255, but on DBCS systems (character set that uses 1 or 2 bytes to represent a character, allowing more than 256 characters to be represented — used for languages such as Japanese and Chinese), the actual range for charcode is -32768 to 65535. Numbers from 0 to 31 are the standard ASCII Non-Printing Control Codes.

Use the ChrW function to return a Unicode character, but if the platform does not support Unicode ChrW will give results identical to the Chr function. ChrW should not be used in the Macintosh environment because Unicode strings are not supported in Visual Basic for the Macintosh.

MsgBox Chr(65), returns the letter «A».

MsgBox Asc(«A»), returns the number 65.

—————————————————————————————————————————-  

Sub Chr_Replace()
‘using vba Chr() function to replace characters in a string

Dim str As String

‘replaces letter «A» with «B»

str = Replace(«ABC», Chr(65), Chr(66))

‘returns the text «BBC»

MsgBox str

End Sub

————————————————————————————————————————-  

Sub TextFormat1()
‘using vba chr() function to remove commas and provide line breaks.

‘Chr(10) provides line feed/new line, and it replaces all instances of comma & following space, in the text string. Refer Image 4.
ActiveSheet.Cells(3, 1) = Replace(ActiveSheet.Cells(1, 1), «, «, Chr(10))

End Sub

————————————————————————————————————————————————————  

Sub TextFormat2()
‘inserting symbols using vba chr() function

Dim str As String

‘evaluates to text string «Exchange Rates Graph of Pound (£), Euro (€) and Dollar ($)»
str = «Exchange Rates Graph of Pound (» & Chr(163) & «), Euro (» & Chr(128) & «) and Dollar (» & (Chr(36) & «)«)

‘displays the text string «Exchange Rates Graph of Pound (£), Euro (€) and Dollar ($)»
MsgBox str

End Sub

————————————————————————————————————————————————————  

Sub DeleteSpaces()
‘remove spaces from a text string, in vba, using the vba Replace function

Dim str As String

str = «Removing  Spaces In Text String «

‘removes space character with ANSI code 32

str = Replace(str, Chr(32), «»)

‘returns the text «RemovingSpacesInTextString»

MsgBox str

End Sub

————————————————————————————————————————————————————  

Sub RemoveNumbers()
‘remove characters, say all numericals, from a text string, using the vba Replace function

Dim str As String, i As Integer

str = «RemovingNumbers 12in4 Text6 9String5″
 

‘chr(48) to chr(57) represent numericals 0 to 9 in ANSI/ASCII character codes

For i = 48 To 57

‘remove all numericals from the text string using vba Replace function:

str = Replace(str, Chr(i), «»)

Next i

‘returns text «Removing Numbers in Text String»

MsgBox str

End Sub

————————————————————————————————————————————————————

Sub ManipulateTextString()
‘manipulate text string consisting of only letters & spaces: remove all spaces, separate each word with comma, capitalize first letter of each word & convert all other letters to lowercase

Dim str As String

str = « red   Blue white  GREEN  yellow    «

‘use the worksheet Trim function to remove all spaces from text leaving only single spaces between words — also deletes all leading & trailing spaces

str = Application.Trim(str)

‘replaces space character (ANSI code 32) with comma character (ANSI code 44)

str = Replace(str, Chr(32), Chr(44))

‘use the worksheet Proper function to: Capitalize the first letter & any other letter which follows a non-letter character; also converts to Lowercase all other letters.

str = Application.Proper(str)

‘returns the text «Red,Blue,White,Green,Yellow»

MsgBox str


End Sub

————————————————————————————————————————————————————

VBA Codes:

Using VBA Chr and Asc functions to convert excel column number to corresponding column letter, and column letter to column number.

The CHAR function in Excel returns a specific character based on a code number from the operating system’s character set.

Each operating system has it’s own character set:

  • Windows has the Windows -1251 character set, which is more commonly known as ANSI
  • Mac uses the Mac OS Roman character set.
  • Excel online has a limited version of the Windows character set.

The character set contains the primary printed and non-printed characters available on a computer.  Those characters can be letters, numbers, punctuation, symbols, and even characters that are not displayed (such as line breaks).

Every character in the set has a code.  The CHAR function in Excel returns the character associated with each code.

It is probably most useful when:

  • inserting line breaks into a formula
  • inserting double quotes into a formula
  • combined with SUBSTITUTE to remove non-printed characters

We’ll look at each of these as examples later in this post.

Download the example file

I recommend you download the example file for this post.  Then you’ll be able to work along with examples and see the solution in action, plus the file will be useful for future reference.

Download Icon
Download the file: 0045 CHAR function in Excel.xlsx

The arguments of the CHAR function

The CHAR function is easy to use.

Basic Example of CHAR function

The example above uses the character code 36 from cell B3 and converts it into a character.

=CHAR(B3)

The CHAR function in Excel has just one argument

=CHAR(number)
  • number: an integer value from 1 to 255 representing the character to be returned for the operating system’s character set.

Working with different character sets

With each operating system having its own character set, it makes the translation between Excel versions a little tricky.

Windows vs. Mac:

If the spreadsheet is likely to be used on another operating system, we can use the INFO function to determine which operating system is running.

As an example, the line break character is different on Windows and Mac:

  • Windows – CHAR(10) is a line break
  • Mac – CHAR(13) is a line break

The formula below tests if the operating system is a Mac and assigns CHAR(13) if it is, or CHAR(10) if it is not.

=IF(INFO("SYSTEM")="mac",CHAR(13),CHAR(10))

Excel online:

Excel online has a limited character set.  We can only use the codes 9, 10, 13, and 32 onwards.

Don’t worry; you’re not missing out. The missing items are generally non-printed characters that Excel online does not require.

Examples of using the CHAR function

In this section, we’ll look at some practical examples of using the CHAR function.

Inserting special characters

The screenshot below shows some of the special characters which are available when using the CHAR function.

Insert Special Characters with CHAR function

As can be seen, Code 128 is equivalent to the € symbol; code 153 is equivalent to the Trade Mark ™ symbol, etc., etc.  These are just a small sample of the available characters.

Create line break in formula

In this example, we have what is probably the most common usage of the CHAR function.

CHAR(10) (or CHAR(13) on a Mac) is equivalent to inserting a new line into a formula.

CHAR(10) to insert a line break in a formula

In cell B19 in the screenshot above, we have the following formula:

="Excel"&CHAR(10)&"Off"&CHAR(10)&"The"&CHAR(10)&"Grid"

The CHAR(10) part of the formula is inserting a line break between each word.  As a result, the value in cell B19 is separated over 4 lines.

The cell needs to be formatted with Wrap Text, else the text will be displayed on a single line without any line breaks.

Instead of using CHAR(10), a line break can also be entered directly into the formula bar by pressing ALT + Enter.

Insert double quotes into a text string

Double quotes are used in Excel at the start and end of a text string.  But what if we need to create a string that contains a double quote?  That can be tricky.

The easiest option is to use CHAR(34).  Look at the screenshot below; we have created a sentence that includes two double-quote characters.

CHAR(34) to insert a double quote in a formula

The formula in cell B22 is:

="Use CHAR(34) to add "&CHAR(34)&"double quotes"&CHAR(34)&" in a formula"

In this formula, we are using & to join text strings together.  CHAR(34) is used to create the double quote.

An alternative approach is to use two double quotes next to each other inside a text string.  The same formula written using this method would be:

="Use CHAR(34) to add"&" """&"double quotes"" "&"in a formula"

Look at all those double-quotes, that’s a lot!  Basically, it’s so confusing and difficult to read that you’re better off using CHAR(34).

Removing non-printed characters

If we have non-printed characters that we want to remove, we can use CHAR combined with the SUBSTITUTE function.

Look at the screenshot below.

Remove special characters

There is an address in cell B25.  The address includes line breaks.  We can convert it into a comma-separated text string, as seen in cell C25.

The formula in cell C25 is:

=SUBSTITUTE(B25,CHAR(10),", ")

This formula replaces every instance of a CHAR(10) and replaces it with a comma and space.

Using CHAR with VBA

Most functions in Excel can be used within VBA by using code similar to the following:

Range("A1") = Application.WorksheetFunction.CHAR(36)

However, the CHAR worksheet function cannot be used within VBA.  However, we can use the VBA only CHR function.

Range("A1") = Chr(36)

The Excel CHAR function and the VBA Chr function both operate in the same way.

Finding the code for a character

The CHAR function is for converting a code into text character, but what if we want the inverse?  In that circumstance, we can use the CODE function.

The formula below will give the result of 36, as that is the character code number for the $ symbol.

=CODE("$")

Other information

  1. If we use CHAR to return a non-printed character, Excel will display a rectanglar placeholder.
  2. Most non-printed characters can be removed using the CLEAN function.
  3. #VALUE errors occur when the number provided is not an integer between 1 and 255.
  4. The UNICHAR function provides access to an extended character set using codes above 255.

Conclusion

In this post, we’ve seen how to use the CHAR function in Excel.  While at the outset, it may not seem like a useful function, through the examples, we’ve seen that it can help us in many tricky scenarios.


Headshot Round

About the author

Hey, I’m Mark, and I run Excel Off The Grid.

My parents tell me that at the age of 7 I declared I was going to become a qualified accountant. I was either psychic or had no imagination, as that is exactly what happened. However, it wasn’t until I was 35 that my journey really began.

In 2015, I started a new job, for which I was regularly working after 10pm. As a result, I rarely saw my children during the week. So, I started searching for the secrets to automating Excel. I discovered that by building a small number of simple tools, I could combine them together in different ways to automate nearly all my regular tasks. This meant I could work less hours (and I got pay raises!). Today, I teach these techniques to other professionals in our training program so they too can spend less time at work (and more time with their children and doing the things they love).


Do you need help adapting this post to your needs?

I’m guessing the examples in this post don’t exactly match your situation. We all use Excel differently, so it’s impossible to write a post that will meet everybody’s needs. By taking the time to understand the techniques and principles in this post (and elsewhere on this site), you should be able to adapt it to your needs.

But, if you’re still struggling you should:

  1. Read other blogs, or watch YouTube videos on the same topic. You will benefit much more by discovering your own solutions.
  2. Ask the ‘Excel Ninja’ in your office. It’s amazing what things other people know.
  3. Ask a question in a forum like Mr Excel, or the Microsoft Answers Community. Remember, the people on these forums are generally giving their time for free. So take care to craft your question, make sure it’s clear and concise.  List all the things you’ve tried, and provide screenshots, code segments and example workbooks.
  4. Use Excel Rescue, who are my consultancy partner. They help by providing solutions to smaller Excel problems.

What next?
Don’t go yet, there is plenty more to learn on Excel Off The Grid.  Check out the latest posts:

The String data type represents text. A string is an array of characters. VBA strings use 16-bit Unicode characters. VBA has a built-in Strings module with functions for manipulating strings. Efficiency is an important topic when it comes to dealing with strings.

String Literals

String literals are used to represent strings in code. Text surrounded by double quotes represents a string literal in VBA.

Public Sub Example()

    Debug.Print "Hello, World!" 'Prints: Hello, World!

End Sub

To create a string literal that contains double quotes, use double double quotes.

Public Sub Example()

    Debug.Print "Hello, World!"       'Prints: Hello, World!

    Debug.Print """Hello, World!"""   'Prints: "Hello, World!"

    Debug.Print "Hello, ""World""!"   'Prints: Hello, "World"!

    Debug.Print """"                  'Prints: "

    Debug.Print """"""                'Prints: ""

End Sub

String Type Conversion

To explicitly convert a value to a string use the CStr function. The Str function can be used to convert a number to a string. The Str function only recognizes the period as a decimal place, so when working with international numbers where the decimal may be a comma, use the CStr function.

Public Sub Example()

    Dim S As String

    S = CStr(350)         ' -> "350"

    S = CStr(3.5)         ' -> "3.5"

    S = CStr(True)        ' -> "True"

    S = CStr(#1/1/2021#)  ' -> "1/1/2021"

    S = CStr(3.5@)        ' -> "3.5"

End Sub

String Concatenation

Both the & and + operators can be used to concatenate strings in VBA. Using the & operator will implicitly convert non-string values to strings. Using the + operator will not implicitly convert non-strings to strings. Trying to concatenate a string value with a non-string value using + will cause a type mismatch error. The CStr function can be used to explicitly convert non-string values to strings. There is no significant difference in speed between using & and +.

Public Sub Example()

    Debug.Print "Hello, " + "World!"

    'Debug.Print "Hello, " + 1 'Causes Error

    Debug.Print "Hello, " + Cstr(1)

End Sub

Public Sub Example()

    Debug.Print "Hello, " & "World!"

    Debug.Print "Hello, " & 1

    Debug.Print "Hello, " & Cstr(1) 'Not necessary to use CStr with &

End Sub

Variable-Length Strings

Variable-Length Strings can hold a large number of characters (2 ^ 31). The size of a Variable-Length String is determined by the number of characters in the String. The Len and LenB functions can be used to return the number of characters and bytes respectively in a String.

Public Sub Example()

    Dim S As String

    S = "Hello, World!"

    Debug.Print S

    Debug.Print Len(S)
    Debug.Print LenB(S)

End Sub

Fixed-Length Strings

Fixed-length strings are given a specific length at design-time when they are declared which cannot be altered at run-time. When a string is too long to fit in the fixed-length string it will be truncated. When a string is shorter than the fixed-length string the remaining space will be set to space characters (Chr 32). An uninitialized fixed-length string will be all null characters (Chr 0) for the length of the string. Fixed-Length strings can store from 1 to 65,535 characters. The Len and LenB functions can be used to get the length of a string in terms of characters and bytes respectively.

Public Sub Example()

    Dim S As String * 10

    S = "Hello, World!"
    Debug.Print """" & S & """" 'Prints: "Hello, Wor"

    S = "ABCD"
    Debug.Print """" & S & """" 'Prints: "ABCD      "

    Debug.Print Len(S)
    Debug.Print LenB(S)

End Sub

Byte Arrays

Byte arrays and Strings are interchangeable. Byte Arrays can be assigned directly to Strings and Strings can be assigned directly to Byte Arrays.

Public Sub Example()

    Dim S As String
    S = "Hello, World!"

    Dim Arr() As Byte
    Arr = S

    Debug.Print Arr

End Sub

VBA Strings use two bytes to store each character so every two bytes in a byte array represents one character. Most common characters only require one byte to store and thus the second byte will be zero.

Public Sub Example()

    Dim Arr(0 To 9) As Byte
    Arr(0) = 72
    Arr(1) = 0
    Arr(2) = 101
    Arr(3) = 0
    Arr(4) = 108
    Arr(5) = 0
    Arr(6) = 108
    Arr(7) = 0
    Arr(8) = 111
    Arr(9) = 0

    Debug.Print Arr 'Prints: Hello

End Sub

String Comparison

Strings can be compared using comparison operators or the StrComp function.

Comparison Operators

Strings can be compared in VBA using comparison operators: =, >, <, >=, <=, <>, Like. Comparing strings using comparison operators will return True or False. The compare method used to compare strings when using comparison operators is determined by the Option Compare statement. The Option Compare statement can specify Binary or Text. Binary comparison compares the binary representations of each character. Because the binary representations of uppercase and lowercase characters differ, binary comparison is case-sensitive. Text comparison compares characters using the case-insensitive sort order determined by the system’s locale. In Microsoft Access, Database comparison can be used to compare strings based on the sort order given the locale ID of the database where strings are being compared. If no Option Compare statement is specified the default comparison method is Binary comparison.

Option Compare Binary

Public Sub Example()
    Debug.Print "A" = "a" 'Prints: False
End Sub

Option Compare Text

Public Sub Example()
    Debug.Print "A" = "a" 'Prints: True
End Sub

StrComp Function

The StrComp function can be used to compare two strings. The function takes two string arguments and an optional compare method argument (vbBinaryCompare, vbDatabaseCompare, or vbTextCompare). If no compare argument is specified then the Option Compare statement determines the compare method. The function can return 1, 0, -1, or Null depending on the result of the comparison. The StrComp function is the most explicit way to compare strings because the function can take the compare method as an explicit argument instead of relying on the Option Compare statement.

Syntax: StrComp(string1, string2, [compare])

Result Return Value
string1 < string2 -1
string1 = string2 0
string1 > string2 1
string1 = Null Or string2 = Null Null
Public Sub Example()

    Debug.Print StrComp("A", "a", vbTextCompare) = 0 'Prints: True

End Sub

Mid

The Mid function can be used to retrieve sections of a string, iterate over each individual character in a string, and to assign sections of a string without reallocating an entirely new string. Using Mid to alter strings is faster than allocating new strings.

Public Sub Example()

    Dim S As String

    S = "Hello, World!"

    'Get slice of string
    Debug.Print Mid$(S, 1, 2)

    'Loop over each character
    Dim i As Long
    For i = 1 To Len(S)
        Debug.Print Mid$(S, i, 1)
    Next i

    'Reassign character
    Mid(S, 1, 1) = "A"
    Debug.Print S 'Prints: Aello, World!

End Sub

StrConv

The StrConv function can be used to convert a string’s case and encoding.

Constant Value Description
vbUpperCase 1 Converts the string to uppercase characters.
vbLowerCase 2 Converts the string to lowercase characters.
vbProperCase 3 Converts the first letter of every word in a string to uppercase.
vbWide* 4 Converts narrow (single-byte) characters in a string to wide (double-byte) characters.
vbNarrow* 8 Converts wide (double-byte) characters in a string to narrow (single-byte) characters.
vbKatakana** 16 Converts Hiragana characters in a string to Katakana characters.
vbHiragana** 32 Converts Katakana characters in a string to Hiragana characters.
vbUnicode 64 Converts the string to Unicode using the default code page of the system. (Not available on the Macintosh.)
vbFromUnicode 128 Converts the string from Unicode to the default code page of the system. (Not available on the Macintosh.)

*Applies to East Asia locales. **Applies to Japan only.

Public Sub Example()

    Debug.Print StrConv("hello, world!", vbProperCase) 'Prints: Hello, World!

End Sub

Public Sub Example()

    Dim Arr(0 To 4) As Byte
    Arr(0) = 72
    Arr(1) = 101
    Arr(2) = 108
    Arr(3) = 108
    Arr(4) = 111

    Debug.Print StrConv(Arr, vbUnicode) 'Prints: Hello

End Sub

LSet and Rset

LSet and RSet can be used to assign strings while aligning the text to the left or right of the string. LSet and RSet are used with fixed-length strings and strings that are already assigned so that they have a specific length. There is some performance improvement using LSet and RSet compared to normal string assignment. Any unassigned characters will be filled with space characters. If the string is longer than the string variable it will be truncated.

Public Sub Example()

    Dim S As String
    S = Space$(10)

    LSet S = "Hello"
    Debug.Print """" & S & """" 'Prints: "Hello     "

    RSet S = "Hello"
    Debug.Print """" & S & """" 'Prints: "     Hello"

End Sub

Public Sub Example()

    Dim S As String * 10

    LSet S = "Hello"
    Debug.Print """" & S & """" 'Prints: "Hello     "

    RSet S = "Hello"
    Debug.Print """" & S & """" 'Prints: "     Hello"

End Sub

Cleaning Text

Text may contain characters that need to be removed. Extra spaces, non-printable characters, non-breaking spaces, and new line characters are some examples of characters that may need to be removed from text.

Trimming Text

The Trim functions can be used to remove leading spaces, trailing spaces, or both from a string.

Public Sub Example()

    Dim S As String
    S = "   Hello, World!   "

    Debug.Print """" & LTrim$(S) & """" 'Prints: "Hello, World!   "

    Debug.Print """" & RTrim$(S) & """" 'Prints: "   Hello, World!"

    Debug.Print """" & Trim$(S) & """"  'Prints: "Hello, World!"

End Sub

The VBA Trim function does not remove extra consecutive spaces in the middle of a String. To accomplish this, use a user-defined function.

Public Function TrimAll(S As String) As String

    TrimAll = Trim$(S)

    Do While InStr(TrimAll, "  ") > 0
        TrimAll = Replace(TrimAll, "  ", " ")
    Loop

End Function

Remove Non-Printable Characters

Any character in the ASCII table with a value less than 32 is a non-printable character. Thus, to remove non-printable characters, remove all characters with an ASCII value less than 32.

Public Function RemoveNonPrintableCharacters(S As String) As String

    Dim OutString As String
    Dim CurrentCharacter As String * 1
    Dim i As Long
    Dim j As Long

    OutString = Space$(Len(S))

    For i = 1 To Len(S)

        CurrentCharacter = Mid$(S, i, 1)

        If Asc(CurrentCharacter) > 31 Then
            j = j + 1
            Mid$(OutString, j, 1) = CurrentCharacter
        End If

        RemoveNonPrintableCharacters = Left$(OutString, j)

    Next i

End Function

Non-Breaking Spaces

Non-breaking spaces can cause issues when processing text input. Non-breaking spaces appear the same as normal spaces when displayed but they are not the same character. Normal spaces have the value 32 in the ASCII table whereas non-breaking spaces have the value 160 in the ASCII table. It is often beneficial when working with text data to replace non-breaking spaces with normal spaces before doing any other processing on the text.

Public Function ReplaceNonBreakingSpaces(S As String) As String

    ReplaceNonBreakingSpaces = Replace(S, Chr(160), Chr(32))

End Function

New Line Characters

New line characters can cause issues with processing text input. It is common when processing text input to replace new line characters with a space character. Depending on the source of the text there could be different new line characters which must be handled in a particular order.

Public Function ReplaceNewLineCharacters( _
S As String, Optional Replacement As String = " ") As String

    ReplaceNewLineCharacters = _
        Replace(S, vbCrLf, Replacement)

    ReplaceNewLineCharacters = _
        Replace(ReplaceNewLineCharacters, vbLf, Replacement)

    ReplaceNewLineCharacters = _
        Replace(ReplaceNewLineCharacters, vbCr, Replacement)

End Function

Formatting Functions

VBA provides useful built-in functions for formatting text.

Format function

The Format/Format$ function is used to format dates, numbers, and strings according to a user-defined or predefined format. Use the $ version of the function to explicitly return a String instead of a Variant/String.

Public Sub Example()

    '''Dates
    Debug.Print Format$(Now, "mm/dd/yyyy")
    Debug.Print Format$(Now, "Short Date")
    Debug.Print Format$(Now, "mmmm d, yyyy")
    Debug.Print Format$(Now, "Long Date")
    Debug.Print Format$(Now, "Long Time")

    '''Numbers
    Debug.Print Format$(2147483647, "#,##0")
    Debug.Print Format$(2147483647, "Standard")
    Debug.Print Format$(2147483647, "Scientific")

    '''Strings
    'Fill from right to left
    Debug.Print Format$("ABCD", "'@@_@@_@@'")

    'Fill from left to right
    Debug.Print Format$("ABCD", "!'@@_@@_@@'")

    'Lower case
    Debug.Print Format$("ABCD", "<'@@_@@_@@'")

    'Upper case
    Debug.Print Format$("ABCD", ">'@@_@@_@@'")

    'No spaces for missing characters
    Debug.Print Format$("ABCD", "'&&_&&_&&'")

    'Escape double quotes
    Debug.Print Format$("ABCD", "!""@@_@@_@@""")

End Sub

Number Formats

To retrieve a string representing a number in a specific format use one of the number format functions.

Function Description
FormatCurrency Returns a formatted currency as a string using the currency symbol defined in the system control panel.
FormatDateTime Returns a formatted date as string.
FormatNumber Returns a formatted number as a string.
FormatPercent Returns a formatted percentage as a string.

Character Constants

Character Constants are constants used to represent certain special characters. Character constants are defined in the built-in VBA.Constants module.

VBA Constant Character Code Description
vbCr 13 Carriage Return
vbLf 10 Line Feed
vbCrLf 13 + 10 Carriage Return + Line Feed
vbNewLine vbCrLf on Windows or vbLf on Mac New Line Character for current platform
vbNullChar 0 Null Character
vbNullString N/A String pointer to null. vbNullString is equal to an empty string («») when compared but they are different. vbNullString takes less memory because it is only a pointer to null. An empty string is a string with its own location allocated in memory. vbNullString is clearer in meaning than an empty string and should generally be preferred. However, vbNullString cannot be passed to DLLs. Empty strings must be passed to DLLs instead.
vbTab 9 Tab Character
vbBack 8 Backspace Character
vbFormFeed 12 Not useful on Windows or Mac.
vbVerticalTab 11 Not useful on Windows or Mac.

Built-in Strings Module Functions

Member Description
Asc Returns the character code of the first letter in a string.
AscB Returns the first byte of a string.
AscW Returns the Unicode character code when Unicode is supported. If Unicode is not supported it works the same as Asc. *Do not use on Mac. **AscW only Works properly up to 32767 and then returns negative numbers. This problem occurs because Unicode characters are represented by unsigned 16-bit integers and VBA uses signed 16-bit integers. See the wrapper functions below to correct for this problem.
Chr Returns a character given a character code. Returns a Variant/String.
Chr$ Returns a character given a character code. Returns a String.
ChrB Returns a single-byte string representing a character given a character code. Returns a Variant/String. *Try StrConv(ChrB(65),vbUnicode)
ChrB$ Returns a single-byte string representing a character given a character code. Returns a String. *Try StrConv(ChrB$(65),vbUnicode).
ChrW Returns a character given a Unicode character code if Unicode is supported. If Unicode is not supported it is the same as Chr. Returns Variant/String. *Do not use ChrW on a Mac.
ChrW$ Returns a character given a Unicode character code if Unicode is supported. If Unicode is not supported it is the same as Chr$. Returns String. *Do not use ChrW$ on a Mac.
Filter Returns an array containing a filtered subset of a string array.
Format Returns a string formatted by a given a format expression. Returns Variant/String.
Format$ Returns a string formatted by a given a format expression. Returns String.
FormatCurrency Returns a string formatted as a currency. Uses the currency symbol defined in the system control panel.
FormatDateTime Returns a string formatted as a date or time.
FormatNumber Returns a string formatted as a number.
FormatPercent Returns a string formatted as a percentage.
InStr Returns the position of the first occurrence of one string within another string.
InStrB Returns the byte position of the first occurrence of one string within another string.
InStrRev Returns the position of an occurrence of one string within another string starting from the end of the string and searching toward the start of the string.
Join Returns a string containing the elements of an array joined together by a delimiter.
LCase Returns a string converted to lowercase. Returns Variant/String.
LCase$ Returns a string converted to lowercase. Returns String.
Left Returns a substring of a given length from the left side of a string. Returns Variant/String.
Left$ Returns a substring of a given length from the left side of a string. Returns String.
LeftB Returns a substring of a given length in bytes from the left side of a string. Returns Variant/String.
LeftB$ Returns a substring of a given length in bytes from the left side of a string. Returns String.
Len Returns the number of characters in a string or the number of bytes required to store a variable.
LenB Returns the number of bytes in a string or the number of bytes required to store a variable.
LTrim Returns a string without leading spaces. Returns Variant/String.
LTrim$ Returns a string without leading spaces. Returns String.
Mid Returns a substring of a given length. Returns Variant/String. Can be used to alter sections of a string.
Mid$ Returns a substring of a given length. Returns String. Can be used to alter sections of a string.
MidB Returns a substring of a given length in bytes. Returns Variant/String. Can be used to alter sections of a string.
MidB$ Returns a substring of a given length in bytes. Returns String. Can be used to alter sections of a string.
MonthName Returns a string representing a given month.
Replace Returns a string with a given substring replaced by another string. Returns String.
Right Returns a substring of a given length from the right side of a string. Returns Variant/String.
Right$ Returns a substring of a given length from the right side of a string. Returns String.
RightB Returns a substring of a given length in bytes from the right side of a string. Returns Variant/String.
RightB$ Returns a substring of a given length in bytes from the right side of a string. Returns String.
RTrim Returns a string without trailing spaces. Returns Variant/String.
RTrim$ Returns a string without trailing spaces. Returns String.
Space Returns a given number of spaces. Returns Variant/String.
Space$ Returns a given number of spaces. Returns String.
Split Returns a string array by splitting up a string on a delimiter.
StrComp Returns the result of a string comparison.
StrConv Returns a string converted according to a given option.
String Returns a string repeated for a given number of times. Returns Variant/String.
String$ Returns a string repeated for a given number of times. Returns String.
StrReverse Returns a reversed string.
Trim Returns a string without leading or trailing spaces. Returns Variant/String.
Trim$ Returns a string without leading or trailing spaces. Returns String.
UCase Returns a string converted to uppercase. Returns Variant/String.
UCase$ Returns a string converted to uppercase. Returns String.
WeekdayName Returns a string representing a given day of the week.
Public Function AscW2(Char As String) As Long

    'This function should be used instead of AscW

    AscW2 = AscW(Char)

    If AscW2 < 0 Then
        AscW2 = AscW2 + 65536
    End If

End Function

Public Function AscW2(Char As String) As Long

    'This function should be used instead of AscW

    AscW2 = AscW(Char) And &HFFFF&

End Function

Types of String Functions

The behaviors of several string functions in VBA can be altered by affixing a $, B, W, or some combination of the three to the end of the function name.

$ Functions

$ String functions explicitly return a String instead of a Variant/String. The String type uses less memory than the Variant/String type.

B Functions

B (Byte) String functions deal with bytes instead of characters.

W Functions

W (Wide) functions are expanded to include Unicode characters if the system supports Unicode.

String Classes

Using custom string classes can facilitate working with strings and make working with strings more efficient. the StringBuilder and ArrayList classes have high-level functionality and are designed to mitigate the inefficiencies of with working with strings.

StringBuilder

The StringBuilder class represents a single string that can be manipulated and mutated. The StringBuilder class improves efficiency by avoiding frequent reallocation of memory. The StringBuilder class has a number of high-level properties and methods that facilitate working with strings. Download and import the clsStringBuilder class into a VBA project.

Public Sub Example()

    '''Must import clsStringBuilder to VBA project

    Dim SB As clsStringBuilder
    Set SB = New clsStringBuilder

    SB.Append "ABC"
    SB.Append "123"

    SB.Insert 3, "XYZ"

    Debug.Print SB.Substring(3, 5)

    SB.Remove 3, 5

    Debug.Print SB.ToString

End Sub

ArrayList

The ArrayList class represents a list which can be manipulated and mutated. The ArrayList class improves efficiency by avoiding frequent reallocation of memory. The ArrayList class has a number of high-level properties and methods that facilitate working with a list of strings. Download and import the clsArrayListString class into a VBA project.

Public Sub Example()

    '''Must import clsArrayListString to VBA project

    Dim AL As clsArrayListString
    Set AL = New clsArrayListString

    'Build message
    AL.Append "Hello"
    AL.Append "How are you?"
    AL.Append "I'm great! Thank you."
    Debug.Print AL.JoinString(vbNewLine)

    AL.Reinitialize

    'Sort strings
    AL.Append "C"
    AL.Append "B"
    AL.Append "A"
    Debug.Print AL.JoinString
    AL.Sort
    Debug.Print AL.JoinString

End Sub

  • 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)

    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»
    )

    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)

    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
    ().

В разделе на вопрос Люди,объясните подробно,пожалуйста,что значит в Паскале функция ord(x) и ей обратная chr(x) ? заданный автором Nick Brown
лучший ответ это Есть специальная таблица символов (расширенного кода ASCII, когда каждому символу принадлежит числовое значение, всего в таблице имеется 255 значений, то есть каждому символу присвоено число,
chr(0..254) преобразует число (один байт) в символ которому принадлежит данное число, например chr(71) результатом будет буква «G», так же нажатие клавиш на клавиатуре выдаёт свой код вот как раз этот код при постановке в данный оператор и выдаст результатом какая клавиша нажата, это я к примеру. А вот оператор ORD(x) делает данный процесс в обратном порядке.
Задаём значение символ и получаем число от 0 до 254 (один байт)
например ORD(«G») даст нам результат 71 (в десятичном формате)
Вот вроде и всё !!!

Ответ от Katyonachik
[новичек]
Все просто, на самом деле)
Орд («Х») — вернет код символа Х из таблицы АСКИИ.
Результатом обратной ей функции будет символ, который соответствует введенному коду (от которого берется функция) из той же таблицы АСКИИ.

Ответ от Jurii
[гуру]
Это не взаимообратные функции!
Функция Ord возвращает порядковый номер значения перечислимого типа.
Счёт начинается с ноля.
Для типа byte функция вернёт собственно значение — порядковый номер совпадает со значением.
Для типа char функция вернёт порядковый номер символа, который (число случайно) совпадает с ASCII кодом.
Функция chr возвращает символ с заданным кодом в ASCII.
Вывод: Просто, в отношении символьных значений, они действительно работают как обратные друг другу.. .
Поэтому можно сказать, что функция ord обратная функции chr, но не наоборот — функция chr не является обратной для функции ord, т. к. область применения функции ord не ограничивается работой с символами!

В этой статье разберем работу со строками в VBA на примерах функций InStr, LCASE, UCase, Left, Right, Mid, LTrim, RTrim, Trim, Len, Replace, Space, StrComp, String, StrReverse.

Строки — это последовательность символов, которая может состоять либо из алфавитов, цифр, специальных символов, либо из всех них. Переменная называется строкой, если она заключена в двойные кавычки «».

Синтаксис

variablename = «string»

Примеры

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

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

Название функции и описание

InStr

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

Синтаксис

InStr(string1,string2[,compare])

Параметр Описание

  • Пуск — необязательный параметр. Указывает начальную позицию для поиска. Поиск начинается с первой позиции слева направо.

пример

Private Sub Constant_demo_Click()
Dim Var As Variant
Var = «Microsoft VBScript»
MsgBox («Line 1: » & InStr(1, Var, «s»))
MsgBox («Line 2: » & InStr(7, Var, «s»))
MsgBox («Line 3: » & InStr(1, Var, «f», 1))
MsgBox («Line 4: » & InStr(1, Var, «t», 0))
MsgBox («Line 5: » & InStr(1, Var, «i»))
MsgBox («Line 6: » & InStr(7, Var, «i»))
MsgBox («Line 7: » & InStr(Var, «VB»))
End Sub

Line 1: 6
Line 2: 0
Line 3: 8
Line 4: 9
Line 5: 2
Line 6: 16
Line 7: 11

Возвращает первое вхождение указанной подстроки. Поиск происходит слева направо.

InStrRev

Функция InStrRev возвращает первое вхождение одной строки в другую строку. Поиск происходит справа налево.

Синтаксис

InStrRev(string1,string2[,start,])

Параметр Описание

  • String1 — требуемый параметр. Строка для поиска.
  • String2 — требуемый параметр. Строка, по которой выполняется поиск String1.
  • Пуск — необязательный параметр. Указывает начальную позицию для поиска. Поиск начинается с первой позиции справа налево.
  • Compare — Необязательный параметр. Указывает сравнение строк.Он может принимать следующие значения.
  • 0 = vbBinaryCompare — выполняет двоичное сравнение (по умолчанию)
  • 1 = vbTextCompare — выполняет сравнение текста

пример

Добавьте кнопку и установите следующую функцию.

Private Sub Constant_demo_Click()
var = «Microsoft VBScript»
msgbox(«Line 1: » & InStrRev(var,»s»,10))
msgbox(«Line 2: » & InStrRev(var,»s»,7))
msgbox(«Line 3: » & InStrRev(var,»f»,-1,1))
msgbox(«Line 4: » & InStrRev(var,»t»,5))
msgbox(«Line 5: » & InStrRev(var,»i»,7))
msgbox(«Line 6: » & InStrRev(var,»i»,7))
msgbox(«Line 7: » & InStrRev(var,»VB»,1))
End Sub

После выполнения вышеуказанного скрипта он производит следующий результат.

Line 1: 6
Line 2: 6
Line 3: 8
Line 4: 0
Line 5: 2
Line 6: 2
Line 7: 0

Возвращает первое вхождение указанной подстроки. Поиск происходит справа налево.

LCASE

Функция LCase возвращает строку после преобразования введенной строки в строчные буквы.

Синтаксис

Lcase(String)

пример

Private Sub Constant_demo_Click()
var = «Microsoft VBScript»
msgbox(«Line 1: » & LCase(var))
var = «MS VBSCRIPT»
msgbox(«Line 2: » & LCase(var))
var = «microsoft»
msgbox(«Line 3: » & LCase(var))
End Sub

Line 1: microsoft vbscript
Line 2: ms vbscript
Line 3: microsoft

Возвращает нижний регистр указанной строки.

UCase

Функция UCase возвращает строку после преобразования введенной строки в буквы буквы UPPER.

Синтаксис

UCase(String)

пример

Добавьте кнопку и поместите следующую функцию внутри нее.

Private Sub Constant_demo_Click()
var = «Microsoft VBScript»
msgbox(«Line 1: » & UCase(var))
var = «MS VBSCRIPT»
msgbox(«Line 2: » & UCase(var))
var = «microsoft»
msgbox(«Line 3: » & UCase(var))
End Sub

После выполнения вышеуказанного скрипта он производит следующий вывод.

Line 1: MICROSOFT VBSCRIPT
Line 2: MS VBSCRIPT
Line 3: MICROSOFT

Возвращает верхний регистр указанной строки.

Left

Функция Left возвращает указанное количество символов с левой стороны данной входной строки.

Синтаксис

Left(String, Length)

Параметр Описание

  • String — обязательный параметр. Строка ввода, из которой указанное число символов должно быть возвращено с левой стороны.
  • Длина — требуемый параметр. Целое число, определяющее количество возвращаемых символов.

пример

Добавьте кнопку и добавьте следующую функцию.

Private Sub Constant_demo_Click()
Dim var as Variant
var = «Microsoft VBScript»
msgbox(«Line 1: » & Left(var,2))
var = «MS VBSCRIPT»
msgbox(«Line 2: » & Left(var,5))
var = «microsoft»
msgbox(«Line 3: » & Left(var,9))
End Sub

Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

Line 1: Mi
Line 2: MS VB
Line 3: microsoft

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

Right

Функция Right возвращает указанное количество символов с правой стороны данной входной строки.

Синтаксис

Right(String, Length)

Параметр Описание

  • String — обязательный параметр. Строка ввода, из которой указанное число символов должно быть возвращено с правой стороны.
  • Длина — требуемый параметр. Целое число, которое задает количество возвращаемых символов.

пример

Добавьте кнопку и добавьте следующую функцию.

Private Sub Constant_demo_Click()
var = «Microsoft VBScript»
msgbox(«Line 1: » & Right(var,2))
var = «MS VBSCRIPT»
msgbox(«Line 2: » & Right(var,5))
var = «microsoft»
msgbox(«Line 3: » & Right(var,9))
End Sub

Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

Line 1: pt
Line 2: CRIPT
Line 3: microsoft

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

Mid

Mid функция возвращает указанное количество символов из заданной входной строки.

Синтаксис

Mid(String,start[,Length])

Параметр Описание

  • String — обязательный параметр. Строка ввода, из которой задано количество символов, которые нужно вернуть.
  • Начало — требуемый параметр. Целое число, определяющее начальную позицию строки.
  • Длина — необязательный параметр. Целое число, определяющее количество возвращаемых символов.

Добавьте кнопку и добавьте следующую функцию.

Private Sub Constant_demo_Click()
Dim var as Variant
var = «Microsoft VBScript»
msgbox(«Line 1: » & Mid(var,2))
msgbox(«Line 2: » & Mid(var,2,5))
msgbox(«Line 3: » & Mid(var,5,7))
End Sub

Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

Line 1: icrosoft VBScript
Line 2: icros
Line 3: osoft V

Возвращает определенное количество символов из строки на основе указанных параметров.

LTrim

Функция Ltrim удаляет пробелы с левой стороны строки.

Синтаксис

LTrim(String)

пример

Добавьте кнопку и добавьте следующую функцию.

Private Sub Constant_demo_Click()
Dim var as Variant
var = » Microsoft VBScript»
msgbox «After Ltrim: » & LTrim(var)
End Sub

Когда вы выполняете функцию, она производит следующий вывод.

After Ltrim: Microsoft VBScript

Возвращает строку после удаления пробелов в левой части указанной строки.

RTrim

Функция Rtrim удаляет пробелы с правой стороны строки.

Синтаксис

RTrim(String)

пример

Добавьте кнопку и добавьте следующую функцию.

Private Sub Constant_demo_Click()
Dim var as Variant
var = «Microsoft VBScript »
msgbox(«After Rtrim: » & RTrim(var))
End Sub

Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

After Rtrim: Microsoft VBScript

Возвращает строку после удаления пробелов в правой части указанной строки.

Trim

Функция Trim удаляет как ведущее, так и конечное пустое пространство данной входной строки.

Синтаксис

Trim(String)

пример

Добавьте кнопку и добавьте следующую функцию.

Private Sub Constant_demo_Click()
var = «Microsoft VBScript»
var = » Microsoft VBScript »
msgbox («After Trim: » & Trim(var))
End Sub

Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

After trim: Microsoft VBScript

Возвращает строковое значение после удаления как верхнего, так и конечного пробелов.

Len

Функция Len возвращает длину данной входной строки, включая пробелы.

Синтаксис

Len(String)

пример

Добавьте кнопку и добавьте следующую функцию.

Private Sub Constant_demo_Click()
Dim var1 as Variant
Dim var2 as Variant
var1 =»Microsoft VBScript»
msgbox(«Length of var1 is: » & Len(var1))
var2 = » Microsoft VBScript »
msgbox («Length of var2 is: » & Len(var2))
End Sub

Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

Length of var1 is: 18
Length of var2 is: 36

Возвращает длину данной строки.

Replace

Функция Replace заменяет указанную часть строки на определенную строку, указанное количество раз.

Синтаксис

Replace(string,find,replacewith[,start[,count[,compare]]])

Параметр Описание

  • String — обязательный параметр. Строка ввода, которую нужно искать для замены.
  • Find — требуемый параметр. Часть строки, которая будет заменена.
  • Replacewith — обязательный параметр. Строка замены, которая будет заменена на параметр find.
  • Start — необязательный параметр. Задает начальную позицию, из которой нужно искать и заменять строку. Значение по умолчанию — 1.
  • Count — необязательный параметр. Указывает количество раз, которое должна выполняться замена.
  • Compare — Необязательный параметр. Указывает метод сравнения, который будет использоваться. Значение по умолчанию — 0.
  • 0 = vbBinaryCompare — выполняет двоичное сравнение
  • 1 = vbTextCompare — выполняет текстовое сравнение

пример

Private Sub Constant_demo_Click()
Dim var as Variant
var = «This is VBScript Programming»
«VBScript to be replaced by MS VBScript
msgbox(«Line 1: » & Replace(var,»VBScript»,»MS VBScript»))
«VB to be replaced by vb
msgbox(«Line 2: » & Replace(var,»VB»,»vb»))
«»is» replaced by ##
msgbox(«Line 3: » & Replace(var,»is»,»##»))
«»is» replaced by ## ignores the characters before the first occurence
msgbox(«Line 4: » & Replace(var,»is»,»##»,5))
«»s» is replaced by ## for the next 2 occurences.
msgbox(«Line 5: » & Replace(var,»s»,»##»,1,2))
«»r» is replaced by ## for all occurences textual comparison.
msgbox(«Line 6: » & Replace(var,»r»,»##»,1,-1,1))
«»t» is replaced by ## for all occurences Binary comparison
msgbox(«Line 7: » & Replace(var,»t»,»##»,1,-1,0))
End Sub

Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

Line 1: This is MS VBScript Programming
Line 2: This is vbScript Programming
Line 3: Th## ## VBScript Programming
Line 4: ## VBScript Programming
Line 5: Thi## i## VBScript Programming
Line 6: This is VBSc##ipt P##og##amming
Line 7: This is VBScrip## Programming

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

Space

Функция Space заполняет строку конкретным количеством пробелов.

Синтаксис

space(number)

Параметр Описание

Номер — требуемый параметр. Количество пробелов, которые мы хотим добавить к данной строке.

пример

Private Sub Constant_demo_Click()
Dim var1 as Variant
var1 = «Microsoft»
Dim var2 as Variant
var2 = «VBScript»
msgbox(var1 & Space(2)& var2)
End Sub

Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

Microsoft VBScript

Заполняет строку указанным количеством пробелов.

StrComp

Функция StrComp возвращает целочисленное значение после сравнения двух заданных строк. Он может возвращать любое из трех значений -1, 0 или 1 на основе входных строк для сравнения.

  • Если String1 меньше String2, то StrComp возвращает -1
  • Если String1 равно String2, то StrComp возвращает 0
  • Если String1 больше String2, то StrComp возвращает 1

Синтаксис

StrComp(string1,string2[,compare])

Параметр Описание

  • String1 — требуемый параметр. Первое строковое выражение.
  • String2 — требуемый параметр. Второе строковое выражение.
  • Compare — Необязательный параметр. Указывает сравнение строк.Он может принимать следующие значения.
  • 0 = vbBinaryCompare — выполняет двоичное сравнение (по умолчанию)
  • 1 = vbTextCompare — выполняет сравнение текста

пример

Добавьте кнопку и добавьте следующую функцию.

Private Sub Constant_demo_Click()
Dim var1 as Variant
msgbox(«Line 1:» & StrComp(«Microsoft»,»Microsoft»))
msgbox(«Line 2:» &StrComp(«Microsoft»,»MICROSOFT»))
msgbox(«Line 3:» &StrComp(«Microsoft»,»MiCrOsOfT»))
msgbox(«Line 4:» &StrComp(«Microsoft»,»MiCrOsOfT»,1))
msgbox(«Line 5:» &StrComp(«Microsoft»,»MiCrOsOfT»,0))
End Sub

Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

Line 1:0
Line 2:1
Line 3:1
Line 4:0
Line 5:1

Возвращает целочисленное значение после сравнения двух указанных строк.

String

Функция String заполняет строку указанным символом для указанного количества раз.

Синтаксис

String(number,character)

Параметр Описание

  • Номер — требуемый параметр. Целочисленное значение, которое будет повторяться в течение определенного количества раз против параметра символа.
  • Символ — требуемый параметр. Значение символа, которое должно повторяться определенное количество раз.

пример

Добавьте кнопку и добавьте следующую функцию.

Private Sub Constant_demo_Click()
msgbox(«Line 1:» & String(3,»$»))
msgbox(«Line 2:» & String(4,»*»))
msgbox(«Line 3:» & String(5,100))
msgbox(«Line 4:» & String(6,»ABCDE»))
End Sub

Когда вы выполняете вышеуказанную функцию, она производит следующий вывод.

Chr

Функция Chr

Chr(CharCode)
Chr$(CharCode)
ChrB(CharCode)
ChrW(CharCode)

Функция Chr
(Ch
aracter
)позволяет получить символ по значению его числового кода ANSI или Unicode

Возвращаемое значение

Функции Chr
, ChrB
, ChrW
возвращают значение субтипа String типа Variant , содержащее символ, соответствующий указанному коду символа ANSI или Unicode. Функции Chr$
, ChrB$
, ChrW$
возвращают соответственно значение типа String

Примечание

Chr
и Chr$
возвращают символ по его кодировке в стандарте ANSI
ChrB
и ChrB$
возвращают однобайтовую
строку
ChrW
возвращает символ Unicode, однако в системах, не поддерживающих Unicode, ее поведение аналогично Chr

Использование в параметре CharCode
значения больше, чем 255, генерирует ошибки стадии выполнения 5: Invalid procedure call or argument или 6: Overflow

Параметры

CharCode Обязательный аргумент является значением типа Long , определяющим символ. Обычно, функция Chr
применяется при вставке в текстовые строки непечатных символов(возврат каретки, перевод строки, табулятор и т.д.). Коды 0-31 соответствуют стандартным управляющим символам ASCII. Например, Chr
(10) возвращает символ перевода строки
Пример

Dim retval
retval = Chr
(65)
Debug.Print retval » возвращается A

Категория

Итак, продолжаем наши уроки Паскаль для начинающих. В прошлом уроке мы разобрали , но там мы упомянули про символы, поэтому прежде чем глубоко изучать тип данных , мы узнаем о типе Char. Символьный тип данных Char
— тип данных, значениями которого являются одиночные символы. Данный тип может содержать всего один любой символ (Например: «*», «/», «.», «!» и другие). Каждый такой символ занимает 8 бит памяти, всего существует 256 восьмибитовых символов. Все символы, используемые символьным типом Char записаны в таблице символов ASCII (American Standart Code for Information Interchange) или Американский стандарт кода для обмена информацией.

Символьные константы заключаются в апострофы, например «.», «*», «7», «s». Также символьную константу можно записать с помощью символа — «решетки», например #185 — выведет символ под номером 185 из таблицы ASCII (это символ «№»).

К символьному типу применимы 5 функций: Ord, Chr, Pred, Succ и Upcase.

Функция Ord
преобразовывает символ в её числовой код из таблицы ASCII
. Например для символа «№» она возвратит значение 185. Функция Chr обратна функции Ord. Функция Chr
преобразует числовой код символа в сам символ, например, если взять числовой код 64, то функция Chr (64) возвратит символ «@».

Пример программы на Паскаль с использованием функции Ord:

Begin //Начало программы

writeln (ord (x)); //Вывод номера в таблице ASCII
end. //Конец программы

Пример программы на Паскаль с использованием функции Chr:

Var x:integer; // Описание переменных (x — целочисленный тип)
Begin //Начало программы
readln (x); //Считывание переменной
writeln (chr (x)); //Вывод символа по номеру в таблице ASCII
end. //Конец программы

Функция Pred
возвращает значение предыдущего символа из таблицы ASCII, например для символа «P» (Pred (P)) эта функция возвратит символ «O». Функция Succ
обратная функции Pred. Для символа «P» функция Succ (P) возвратит символ «Q», то есть следующий символ из вышеописанной таблицы ASCII.

Пример программы на Паскаль с использованием функций Pred и Succ:

Var x:char; // Описание переменных (x — символьный тип)
Begin //Начало программы
readln (x); //Считывание переменной
writeln (pred (x)); //Вывод предыдущего символа в таблице ASCII
writeln (succ (x)); //Вывод следующего символа в таблице ASCII
end. //Конец программы

Функция UpCase
применима только для строчных букв английского алфавита. Данная функция преобразует строчные английские буквы в заглавные.

Пример программы на Паскаль с использованием функции UpCase:

Приложение к уроку — таблицы символов ASCII:

На сегодня урок окончен. Помните, что программирование на паскале
просто и является основой для многих языков программирования.

Loading...Loading…

Понравилась статья? Поделить с друзьями:
  • Excel vba change all cells
  • Excel vba autofilter criteria not
  • Excel vba cells value get value
  • Excel vba autofilter array
  • Excel vba cells not empty