BenV
BenV

Reputation: 12452

Trim null characters from a string in VBA

I'm calling a Win32 API function and getting back a string padded with null characters. Trim$() doesn't remove them. Is there an easier solution then removing them one character at a time?

Upvotes: 2

Views: 9324

Answers (4)

Kurt Schultz
Kurt Schultz

Reputation: 799

This will remove all nulls from the string, strWithNulls. I have also used it to convert from unicode to single byte characters.

strResult = Replace( strWithNulls, Chr$(0), "")

Upvotes: 1

Don Dickinson
Don Dickinson

Reputation: 6258

if it's just padded to the right, you can use something like this:

function ntrim(byval theString as string) as string
  dim iPos as long
  iPos = instr(theString, chr$(0))
  if iPos > 0 then theString = left$(theString, iPos - 1)
  ntrim = theString
end function

Upvotes: 6

darekk
darekk

Reputation: 81

In my case Replace() and InStr() don't work with Chr(0) (can't see it not displaying any error), but Nulls can be removed comparing and using Mid(), Left() and Len() as above or in this example:

If Mid$(str, 1, 1) = Chr$(0) Then str = Mid$(str, 2)
If Mid$(str, Len(str), 1) = Chr$(0) Then str = Left$(str, Len(str) - 1)

This is Null removal from ends, for example from objFile.ExtendedProperty("Dimensions") value, like "?600 x 400?". Nulls (?) are insterted here in Windows 10 but not in Windows XP.

Upvotes: 0

JonTheNiceGuy
JonTheNiceGuy

Reputation: 641

Loosely based on the last one, maybe this might be better if there's a risk you might have NULLs in your text for some other reason?

Function nTrim2(theString As String) As String
    Dim iPos As Long
    iPos = Len(theString)
    For i = iPos To 0 Step -1
        iPos = i
        If Mid$(theString, i, 1) <> Chr$(0) Then Exit For
    Next
    nTrim2 = Left$(theString, iPos)
End Function

Upvotes: 0

Related Questions