Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Function to Trim Variables 3

Status
Not open for further replies.

ironhide1975

Programmer
Feb 25, 2003
451
US
Is there a way easy way to create a Sub that you can pass a variable and the number to trim the variable and add the typical '...' on the end?

 
I'd use a function...

Function myTrim(myvar, myLen)
myTrim = left(myvar, myLen - 3) & "..."
End Function
 
Did you mean something like this?
Code:
Function trimvariable(inputvar)
trimvariable = left(inputvar, 75) & "..."
End Function

-DNG

 
now how do I pass something to that function?
And don't functions not return items? Don't you want to use a sub?

 
function returns a value...i dont know what you meant by saying functions not return items....

just call the function as follows...

trimvariable(yourinputstring)

-DNG
 
Subs do not return values, Functions do return values.

Using mbiro's example (Sorry DNG, he beat you by a few seconds :) ):


[highlight]Function myTrim(myvar, myLen)[/highlight]

This line defines the function and what values it is expecting you to pass. So in this case you need to pass it two values when you call it. Based on the names of the variables and the second line of the function, we can see that it is expecting a string to shorten and the maximum length of the return value. So we would call it something like:
Dim a
a = myTrim("This is my string",10)

By assigning a value to a function name inside a function, you are defining the functions return value. If your function is not going to return a value or if you don't want the value it's returning, you would call the function without the parentheses.


One problem both of the previous examples overlooked is that if you pass the function a string that is shorter than your maximum value, your going to get an error from the Left function. An alternative would be:
Code:
Function TrimVariable(inputString,targetLength)
   If Len(inputString) > targetLength Then
      TrimVariable = Left(inputString,targetLength - 3) & "..."
   Else
      TrimVariable = inputString
   End If
End Function

Hope this helps,
-T

 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top