开发者

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 开发者_JAVA技巧at a time?


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


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜