-
Hello all,
Consider the following code:
Private Sub Form_Load()
Dim test As Variant
test= Space(5)
test= "8"
MsgBox Len(header)
End Sub
The msgbox gets a length of 1. My question is, is there a way to make it keep a length of 5, by have something like " 8" (4 spaces) put into the variable automatically? ie, have it automatically fill up the not used spaces rather than throwing them out?
Sunny
-
Write a function to do it, for example:
Code:
Public Function AlwaysFive(argText As String) As String
Dim strLen As Long ' string length
strLen = Len(argText)
If strLen > 5 Then strLen = 5
AlwaysFive = Space$(5 - strLen) & argText
End Function
That might work.
-
have a look at the Format function, you could use something like: MsgBox Format(3, "00000") for leading zeros. there are lots of possibilities, just check yoir help.
best regards
Sascha
-
Spaces
Ok, when you put test = "8" it made the string's length 1 as you have just discovered. To make it keep a length of 5 I suggest the following :
Dim Test As Variant
Dim Loop1 As Integer
Test = "8"
If Len(Test) > 5 then
Test = left$(Test,5)
Else
If Len(Test) < 5 then
For Loop1 = 1 to (5 - Len(Test)) ' Loop for all the spaces to include
Test = Test & " "
Next Loop1
End If
End if
Msgbox Len(Test)
Hope this helps
Sal
-
If your only concern is to keep the string 5 characters long, then the simplest solution would be this:
Code:
Dim test As String * 5
Just thought I would mention that.
-
Thanks for all the input, but I had forgot to mention, that the data to be put into the fixed length string will never be longer than the fixed length, so I think HaxSoft's method is the quickest, all your other suggestions have been able to make the string-length fool proof by shorten it if its too long.
Thanks
Sunny
-
Sascha has a good suggestion as well. If you want to right-justify a string in a fixed-length area of 5 characters, you can do this:
Code:
Dim strTest As String
Dim strOutString As String
strTest = "8"
strOutString = Format$(strTest, "@@@@@")
MsgBox strOutString 'Result is bbbb8 (b=blank space)
If you want leading zeroes, you can do this:
Code:
Dim strTest As String
Dim strOutString As String
strTest = "8"
strOutString = Format$(strTest, "00000")
MsgBox strOutString 'Result is 00008
-
There is another silly way of doing this -
Code:
OutString = Right("00000" & Instring, 5)
Told you it was silly...