| {\rtf1\ansi\ansicpg1252\deff0\deflang1044{\fonttbl{\f0\fnil\fcharset0 MS Sans Serif;}} \viewkind4\uc1\pard\f0\fs17 Sometimes it can be very useful to have a function that will accept any number of parameters. For example, say you wanted to join a number of strings into one string, but with a semicolon in between each one. You could do it like this: \par \par JoinedString = String1 & \ldblquote ;\rdblquote & String2 & \ldblquote ;\rdblquote & String3 \par \par However, if you were doing the same thing more than once, it would be easier to use a function to do the job, like this: \par \par Function Join(Seperator As String, String1 As String, String2 As String, String3 As String) As String \par \par Join = String1 & Seperator & String2 & Seperator & String3 & Seperator \par End Function \par \par \par Unfortunately, this won\rquote t do the job if you want to join a different number of strings, since you can only pass it three strings to join. You could pass the function an array with the strings you want to join, but then you would need to build up the array before you could call the function. \par \par To create a function that can have a varying number of parameters, you use the ParamArray keyword when you declare a function. The syntax is like this: \par \par Public Function Join(Seperator As String, ParamArray Strings()) As String \par \par \par This makes Strings an array which can hold any number of parameters. When you use the ParamArray keyword, the variable following it must always be a variant array. It is also optional, so you don\rquote t need to pass any parameters for it if you don\rquote t need to. \par Here\rquote s an example for the Join function from before: \par \par Public Function Join(Seperator As String, ParamArray Strings()As Variant) As String \par \par Dim aString As Variant \par For Each aString In Strings \par Join = Join & aString & Seperator \par Next \par \par End Function \par \par \par This can be called like so: \par \par Joined = Join(";", "a", "b", "c") \par \par This passes the Join function a semicolon as the Seperator variable, and \ldblquote a\rdblquote , \ldblquote b\rdblquote , and \ldblquote c\rdblquote will populate \par the Strings array. Then the join function loops through the array using a For Each loop, and adds the Seperator and a string from the array. Unfortunately, since the ParamArray variable is a Variant, the string used to loop round must also be a Variant. \par } |
Create functions with a variable amount of paramet |
India web developer web development India | India web development company India ecommerce web developer