String, String$ Functions

Named Arguments

Yes

Syntax

String(number, character)

number

Use: Required

Data Type: Long

The length of the required string.

character

Use: Required

Data Type: Variant

Character or character code used to create the required string.

Return Value

A Variant of subtype string made up of character, repeated number times.

Description

Creates a string comprising a specified single character repeated a specified number of times.

Rules at a Glance

  • If number contains Null, Null is returned.

  • If character contains Null, Null is returned.

  • character can be specified as a string or as an ANSI character code. For example:

    strBuffer1 = String(128, "=")     ' Fill with "="
    strBuffer2 = String(128, 0)       ' Fill with Chr$(0)

Programming Tips and Gotchas

  • The String function is useful for creating long strings of "_" , "-", or "=" characters to create horizontal lines for delimiting sections of a report.

  • When calling Win32 API functions that write string values to a buffer, the String function is typically used beforehand to create a string variable of the proper length and to fill it with a single character, like Chr$(0). For example, given the following statements in the declarations section of a code module:

    Private Declare Function GetWindowsDirectory _
            Lib "kernel32" _
            Alias "GetWindowsDirectoryA" _
            (ByVal lpBuffer As String, _
            ByVal nSize As Long) As Long
    
    Private Const MAX_PATH = 260

    the following code fragment retrieves the drive and path to the Windows directory:

    Dim strWinDir ...

Get VB & VBA in a Nutshell: The Language now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.