Database SQL Code to Trim Text Fields

Trevor G

Well-known Member
Joined
Jul 17, 2008
Messages
6,740
Office Version
  1. 365
  2. 2021
  3. 2019
  4. 2016
Platform
  1. Windows
I import data into a Temp Table and there are additional spaces. What I have below is code to loop through all the tables in the database and trim all text fields, what I need it to do is just do this on the TempImport table.

What would I need to adjust this to assign the code to the TempImport only?

Sub TrimAllTextFieldsAllTables()
'The following code will trim all text fields in all tables
Dim db As DAO.Database
Dim tbls As DAO.TableDefs
Dim tbl As DAO.TableDef
Dim thisTable As DAO.TableDef
Dim SQLString As String
Dim flds As DAO.Fields
Dim fld As DAO.Field

Set db = CurrentDb
Set tbls = db.TableDefs
' loop through each appropriate table (i.e. no linked or system tables)
For Each tbl In tbls
If tbl.Attributes = 0 Then
Set thisTable = tbl
' grab all fields
Set flds = thisTable.Fields

SQLString = "UPDATE [" & tbl.Name & "] SET "

' if field is text, create SQL string to trim it
For Each fld In flds
If fld.Type = dbText Then
SQLString = SQLString & "[" & fld.Name & "] = Trim([" & fld.Name & "]),"
End If
Next fld

SQLString = Left(SQLString, Len(SQLString) - 1) & ";"
Debug.Print SQLString
' execute update statement on table
db.Execute SQLString, dbFailOnError

End If
Next tbl

End Sub
 

Excel Facts

Does the VLOOKUP table have to be sorted?
No! when you are using an exact match, the VLOOKUP table can be in any order. Best-selling items at the top is actually the best.
Solved this by changing a line to make it only point a the TempImport table.

If tbl.Name = "TempImport" Then

Its been a long day today, loads of VBA coding.:)
 
Upvote 0

Forum statistics

Threads
1,215,338
Messages
6,124,358
Members
449,155
Latest member
ravioli44

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top