Saturday, October 22, 2022

Data type - String

Data type String is any characters in sequence, 2 type of string:

  • Variable-length contain up to approximately 2 billion (2^31) characters.
    Declare Dim StrText as String or Dim StrText$
  • Fixed-length strings contain 1 to approximately 64 K (2^16) characters.
    Declare Dim StrText as String * 3, where 3 is length of string

To reset or assign String as empty StrText = "" (Use double-quotation-marks) and to include double-quotation-marks inside string StrText = """" (Indicate single double-quotation-marks inside string).

For more example refer below table and code.

Below example is to get folder name and files name from path.

VBA Vode:

Option Explicit
Sub Examples_StringVariablelength()

    Dim i As Integer
    Dim StrPath As String, StrFldr As String
    
    i = 2
    With ActiveSheet
        Do
            
            StrPath = .Range("B" & i)
            StrFldr = Left(StrPath, InStrRev(StrPath, "\", -1) - 1)
            .Range("C" & i) = Right(StrFldr, Len(StrFldr) - _
            InStrRev(StrFldr, "\", -1))
            .Range("D" & i) = Right(StrPath, Len(StrPath) - _
            InStrRev(StrPath, "\", -1))
            
            StrPath = "": StrFldr = ""
            i = i + 1
        Loop Until .Range("A" & i) = ""
    End With

End Sub

Note: 

Above example include Left function, Right function and InStrRev function.

Below example is to get months name in short form (3 Characters) with fixed length variables and left function.

VBA Vode:

Option Explicit
Sub Examples_StringFixedLength()

    Dim i As Integer
    Dim StrMnth As String * 3
    i = 2
    With ActiveSheet
        Do
            
            StrMnth = .Range("B" & i)
            .Range("C" & i) = Left(.Range("B" & i), 3)
            .Range("D" & i) = StrMnth
            
            StrMnth = ""
            i = i + 1
        Loop Until .Range("A" & i) = ""
    End With

End Sub

Note: 

The variables length string is widely used compare with fixed length string.

Microsoft Reference-String-data-type
Other Reference-String-data-type

Practice makes perfect. Thank You.

excelmacros
macro excel
excel programming
excel vba

No comments:

Post a Comment