Here Is An Example Of The VBA Trim Function

The “Trim” function is useful in eliminating the blank spaces in a string
normally caused by some data entry error.

Why do you want to do this? Well because a sorting error can happen if you are trying to
sort ” Dan, “Fred”, and “Ann”. ” Dan” will show up on top before “Ann” because of that space.

I normally use the “Trim” function before the “Len” function (which checks the length of the string in VBA), otherwise I can get an incorrect string length.

In this example we’ll read the values of a column and we’ll clean up the string that
has some stray spaces.

Sub VBATrimFunction()

    Dim rst As Object
    Dim strFname As String
    Dim intLen As Integer
    
    Set rst = CurrentDb.OpenRecordset("SELECT FirstName FROM tblNames ORDER BY ID")
    
    Do Until rst.EOF
        strFname = rst.Fields("FirstName")
        intLen = Len(strFname)
                
        Debug.Print "Name Before Trim: " & strFname
        Debug.Print "Length Before Trim: " & intLen
        
        strFname = Trim(strFname)
        intLen = Len(strFname)
        
        Debug.Print "Name After Trim: " & strFname
        Debug.Print "Length After Trim: " & intLen

        rst.MoveNext
    Loop

    rst.Close
    Set rst = Nothing

End Sub

Let me know if you have any questions, or click here for related posts




By the way, if you got or are getting value from the VBA information, please give me a tip, thanks!


These posts may help answer your question too...

How To Parse A Flat File In Excel VBA

In another post I demonstrated how to access a file on your computer using the MS Office Library. Here it is if you don’t know what I’m talking about. In this post, I am going to show you how to access the file and load it into your spreadsheet. I will do the same thing […]

How can I interact with other Office applications (Excel) using VBA in Access?

Need to write your Access data or query to an Excel file? Here is the how to do it: Most people are familiar with Excel and know how to use it well (enough), and when you start talking about Access, they get scared off, and don’t know what to do anymore. Well, here you are […]

How To Generate A XML File With Access VBA

XML is used to structure your data. You can send a CSV file to another person, but using XML, you can structure your data in a more elegant format, and get very specific about your fields, and what data is contained within your tags (your field names). This is different than a basic CSV file […]

Mouse Click Counter On Access Form

This post will demonstrate how you can count the number of clicks on your button in a certain time frame. It will function like a game . Here is the database form all in one: Option Compare Database Public m_dteStartTime As Date Public m_dteStopTime As Date Private Sub btnClicker_Click() Dim intValue As Integer Dim rst […]

Previous Post

VBA Msgbox New Line Example

Next Post

How To Use The VBA Input Box Cancel Button To Exit Sub