How to use RSet statement in VBA?

In VBA (Visual Basic for Applications), the RSet statement is used to right-align a string within a string variable. This means that RSet adjusts the position of a string within a variable by padding it with spaces on the left side so that the last character of the string aligns with the rightmost position of the variable.

Here’s how to use the RSet statement:

Basic Syntax

RSet stringVar = stringExpression
  • stringVar is the name of the string variable in which you want to right-align another string.
  • stringExpression is the string or string expression that you want to right-align within stringVar.

Example Usage

Dim myStr As String * 10  ' Declare a fixed-length string
RSet myStr = "Hello"      ' Right-align "Hello" in myStr
MsgBox "|" & myStr & "|"  ' Displays "|     Hello|"

In this example, myStr is a fixed-length string variable with a length of 10 characters. The RSet statement right-aligns the string “Hello” within myStr, resulting in five spaces being added to the left of “Hello”.

Error Handling

  • If stringExpression is longer than the length of stringVar, a run-time error occurs.
  • If stringVar is not a fixed-length string, a run-time error occurs.

Use with Variable-Length Strings

While RSet is intended for use with fixed-length strings, you can simulate right-alignment with variable-length strings by using string functions like Space and Len. For example:

Dim varLengthStr As String
varLengthStr = "Hello"
varLengthStr = Space(10 - Len(varLengthStr)) & varLengthStr
MsgBox "|" & varLengthStr & "|"  ' Displays "|     Hello|"

Practical Use Cases

The RSet statement is particularly useful in formatting output for fixed-width displays or files, where you need to align text in columns.

Remember that RSet modifies the string in place and is different from functions like Right which return a new string without modifying the original string.

Unlock Your Potential


Basic - Advanced


Access Basic - Advanced

Power BI

Power BI Basic - Advanced

Help us grow the project

Leave a Reply

Your email address will not be published. Required fields are marked *