Results 1 to 4 of 4
  1. #1
    3 Star Lounger
    Join Date
    Aug 2001
    Location
    Cape Town, South Africa, South Africa
    Posts
    399
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Len reads incorrect lenght (XP)

    I've tried the following code and when I change the value to 1 it reads the length value as 2. If I change the code to include trim the len value is 1. Where am I missing the mistery value.

    TIA

    Sub test()
    batchmber (1)
    End Sub

    Function batchmber(batch As Integer) As String
    If Len(batch) = 1 Then
    batchnumber = "000" & batch
    ElseIf Len(batch) = 2 Then
    batchnumber = "00" & batch
    ElseIf Len(batch) = 3 Then
    batchnumber = "0" & batch
    Else
    batchnumber = batch
    End If

  2. #2
    Plutonium Lounger
    Join Date
    Mar 2002
    Posts
    84,353
    Thanks
    0
    Thanked 29 Times in 29 Posts

    Re: Len reads incorrect lenght (XP)

    Len(batch) returns the size of the variable. An Integer takes up 2 bytes, regardless of the actual contents of the variable. If you had declared batch as a Long, the result would have been 4 regardless of the actual contents. By applying Trim (or CStr), you convert the value into a string. For strings, Len returns the actual size.

  3. #3
    3 Star Lounger
    Join Date
    Aug 2001
    Location
    Cape Town, South Africa, South Africa
    Posts
    399
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Re: Len reads incorrect lenght (XP)

    Thanks Hans as always you have the solution.

  4. #4
    Uranium Lounger
    Join Date
    Jan 2001
    Location
    South Carolina, USA
    Posts
    7,295
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Re: Len reads incorrect lenght (XP)

    In addition to Hans' answer, this code is simpler and faster:

    <pre>Option Explicit

    Sub test()
    Dim strWk As String
    strWk = batchmber(1)
    End Sub

    Function batchmber(batch As Integer) As String
    batchmber = Format(batch, "000")
    End Function
    </pre>

    Legare Coleman

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •