I want to create a function where I use one parameter so the function returns another value. In this case I want to insert "links" in a function and then the function should give me back "Left" (Im need a of 'translations' so therefore I use case of if statements.
I have the following function
Public Function newParameter(aParameter) As Integer
Select Case aParameter
Case Is = "Links"
aParameter = "ppAlignLeft"
End Select
End Function
Sub finalFunction()
Dim newParameter As String
newParameter = newParameter(Links)
MsgBox (newParameter)
End Sub
This however gives me a compile error that a matrix is required. Any thoughts on how I can get this working?
You're passing the argument ByRef and change it's value. You dont need a function for this. Functions retun values.
Since you are using a Function though, why dont you have the Function return the value you want?
Public Function newParameter(ByVal aParameter As String) As String
Select Case aParameter
Case "Links":
newParameter = "ppAlignLeft"
Case "A":
newParameter = "You passed A"
Case Else:
newParameter = "No match"
End Select
End Function
Sub finalFunction()
Dim newParameter1 As String
newParameter1 = newParameter("Links") 'This reads 'ppAlignLeft'
MsgBox newParameter1
End Sub
Related
So I'm reading through my source code looking for places to improve the code when I come across this unholy chunk of code.
Public Function ReadPDFFile(filePath As String,
Optional maxLength As Integer = 0) As List(Of String)
Dim sbContents As New Text.StringBuilder
Dim cArrayType As Type = GetType(PdfSharp.Pdf.Content.Objects.CArray)
Dim cCommentType As Type = GetType(PdfSharp.Pdf.Content.Objects.CComment)
Dim cIntegerType As Type = GetType(PdfSharp.Pdf.Content.Objects.CInteger)
Dim cNameType As Type = GetType(PdfSharp.Pdf.Content.Objects.CName)
Dim cNumberType As Type = GetType(PdfSharp.Pdf.Content.Objects.CNumber)
Dim cOperatorType As Type = GetType(PdfSharp.Pdf.Content.Objects.COperator)
Dim cRealType As Type = GetType(PdfSharp.Pdf.Content.Objects.CReal)
Dim cSequenceType As Type = GetType(PdfSharp.Pdf.Content.Objects.CSequence)
Dim cStringType As Type = GetType(PdfSharp.Pdf.Content.Objects.CString)
Dim opCodeNameType As Type = GetType(PdfSharp.Pdf.Content.Objects.OpCodeName)
Dim ReadObject As Action(Of PdfSharp.Pdf.Content.Objects.CObject) = Sub(obj As PdfSharp.Pdf.Content.Objects.CObject)
Dim objType As Type = obj.GetType
Select Case objType
Case cArrayType
Dim arrObj As PdfSharp.Pdf.Content.Objects.CArray = DirectCast(obj, PdfSharp.Pdf.Content.Objects.CArray)
For Each member As PdfSharp.Pdf.Content.Objects.CObject In arrObj
ReadObject(member)
Next
Case cOperatorType
Dim opObj As PdfSharp.Pdf.Content.Objects.COperator = DirectCast(obj, PdfSharp.Pdf.Content.Objects.COperator)
Select Case System.Enum.GetName(opCodeNameType, opObj.OpCode.OpCodeName)
Case "ET", "Tx"
sbContents.Append(vbNewLine)
Case "Tj", "TJ"
For Each operand As PdfSharp.Pdf.Content.Objects.CObject In opObj.Operands
ReadObject(operand)
Next
Case "QuoteSingle", "QuoteDbl"
sbContents.Append(vbNewLine)
For Each operand As PdfSharp.Pdf.Content.Objects.CObject In opObj.Operands
ReadObject(operand)
Next
Case Else
'Do Nothing
End Select
Case cSequenceType
Dim seqObj As PdfSharp.Pdf.Content.Objects.CSequence = DirectCast(obj, PdfSharp.Pdf.Content.Objects.CSequence)
For Each member As PdfSharp.Pdf.Content.Objects.CObject In seqObj
ReadObject(member)
Next
Case cStringType
sbContents.Append(DirectCast(obj, PdfSharp.Pdf.Content.Objects.CString).Value)
Case cCommentType, cIntegerType, cNameType, cNumberType, cRealType
'Do Nothing
Case Else
Throw New NotImplementedException(obj.GetType().AssemblyQualifiedName)
End Select
End Sub
Using pd As PdfSharp.Pdf.PdfDocument = PdfSharp.Pdf.IO.PdfReader.Open(filePath, PdfSharp.Pdf.IO.PdfDocumentOpenMode.ReadOnly)
For Each page As PdfSharp.Pdf.PdfPage In pd.Pages
ReadObject(PdfSharp.Pdf.Content.ContentReader.ReadContent(page))
If maxLength > 0 And sbContents.Length >= maxLength Then
If sbContents.Length > maxLength Then
sbContents.Remove(maxLength - 1, sbContents.Length - maxLength)
End If
Exit For
End If
sbContents.Append(vbNewLine)
Next
End Using
'Return sbContents.ToString
Dim ReturnList As New List(Of String)
For Each Line In sbContents.ToString.Split(vbNewLine)
If String.IsNullOrWhiteSpace(Line.Trim) Then
Else
ReturnList.Add(Line.Trim)
End If
Next
Return ReturnList
End Function
All this does is read the text parts of a PDF using PDFSharp. What caught my eye however was line 17. Is that a Sub inside of the function?
So, what exactly is this Sub inside of a function? I didn't write this code so I've never seen anything like this before.
How does this work exactly and why wouldn't I use a function to do the processing and then return the results?
In short, my question is, what is this, how does it work, and why would I want to use something like this?
That's a so-called Lambda expression. They're used to create inline (or more correctly: in-method) methods, which makes them more dynamic than normal methods.
In your example a lambda expression is not necessary and only makes the code harder to understand. I suppose the author of that code wrote a lambda expression instead of a separate method in order to not expose ReadObject to any outside code.
One of the best uses for a lambda expression IMO is when you want to make thread-safe calls to the UI thread, for instance:
If Me.InvokeRequired = True Then
Me.Invoke(Sub() TextBox1.Text = "Process complete!")
Else
TextBox1.Text = "Process complete!"
End If
...where the same code without a lambda would look like this:
Delegate Sub UpdateStatusTextDelegate(ByVal Text As String)
...somewhere else...
If Me.InvokeRequired = True Then
Me.Invoke(New UpdateStatusTextDelegate(AddressOf UpdateStatusText), "Process complete!")
Else
UpdateStatusText("Process complete!")
End If
...end of somewhere else...
Private Sub UpdateStatusText(ByVal Text As String)
TextBox1.Text = Text
End Sub
There are also other examples where lambda expressions are useful, for instance if you want to initialize a variable but do some processing at first:
Public Class Globals
Public Shared ReadOnly Value As Integer = _
Function()
DoSomething()
Dim i As Double = CalculateSomething(3)
Return Math.Floor(3.45 * i)
End Function.Invoke()
...
End Class
Yet another usage example is for creating partially dynamic event handlers, like this answer of mine.
I want to design a Function or Sub that accepts any number of boolean conditions and add them to an IF statement. The code i imagine goes like this:
Function comp (ParamArray list() As Variant)
If (list(0) = True) And (list(1) = true) ..... (list(last) = true) then
'random code
End If
End Function
where list() would be expresions like:
x = y-1,somethingToCompare <> anotherThing, etc...
It would be interesting if i could add the "and" as another argument, to be changed to "or" if i wished to.
Function comp (VyVal compare as Boolean, ParamArray list() As Variant)
dim comparison as String???
If compare then
comparison = "and"
else
comparison = "or"
end if
If (list(0) = True) comparison (list(1) = true) ..... (list(last) = true) then
'random code
End If
End Function
The final idea is to use that function like this:
Sub code ()
if comp(True, condition1, condition2, ...) then
'random code'
End Sub
Avoid directly looking at that code i wrote lest it burn your eyes.
Is something like this posible or should i get a lollipop?
Maybe i'm looking at this in the wrong way, and there's an easier way of doing something similar or even better.
Python (and some other languages) has useful functions all() and any() which take as input an array (or some other iterable) of Booleans and returns either True or False depending on whether or not some, all, or none of the passed Booleans are True. You could write VBA versions of these (using Some() instead of Any() since Any happens to be a somewhat obscure keyword in VBA):
Function All(ParamArray conditions()) As Boolean
Dim i As Long
For i = LBound(conditions) To UBound(conditions)
If Not conditions(i) Then
All = False
Exit Function
End If
Next i
All = True
End Function
Function Some(ParamArray conditions()) As Boolean
Dim i As Long
For i = LBound(conditions) To UBound(conditions)
If conditions(i) Then
Some = True
Exit Function
End If
Next i
Some = False
End Function
You could use these functions directly to conditionally call code.
Arguably it might be more useful to change the above definitions to:
Function All(conditions As Variant) As Boolean
Dim i As Long
For i = LBound(conditions) To UBound(conditions)
If Not conditions(i) Then
All = False
Exit Function
End If
Next i
All = True
End Function
Function Some(conditions As Variant) As Boolean
Dim i As Long
For i = LBound(conditions) To UBound(conditions)
If conditions(i) Then
Some = True
Exit Function
End If
Next i
Some = False
End Function
Now you would need to use calls like Some(Array(c1, c2, c3)) rather than Some(c1,c2,c3) if you had a literal list of conditions, but you would have the flexibility to pass in an entire array of conditions. Using this second definition you could write something like the following (which answers your original question):
Sub Sometimes(when As String, ParamArray conditions())
Dim run As Boolean
Dim cond As Variant
cond = conditions
run = IIf(when = "All", All(cond), Some(cond))
If run Then
Debug.Print "Running random code"
Else
Debug.Print "Not running random code"
End If
End Sub
Then, for example, Sometimes "Some",True,True,False results in Running random code being printed.
sub pointless(byval IsAnd as boolean, paramarray conditions())
dim i as long
for i=lbound(conditions) to ubound(conditions)
if IsAnd then
if not conditions(i) then exit sub
else
if conditions(i) then exit for
end if
next
'random code
end sub
But you should realise that the procedure will receive results of the comparisons passed to it, not the comparisons themselves. So there is no point really to have such procedure in the first place, you can just write directly in your code:
if x = y-1 and somethingToCompare <> anotherThing then
'random code
end if
Is it possible to check if the passed variable in a function is a specific text? For example, I have a function:
Function dateCheck2(dateValue As String) As Boolean
If IIf(IsDate(frmResponse.txtEndDate), Format(CDate(frmResponse.txtEndDate), _
"mm\/dd\/yyyy"), "") = dateValue Then
dateCheck2 = True
Exit Function
End If
End Function
Then I have to call this in a UForm, lets say :
dateCheck2(sample)
What I want is to check if the passed variable is sample. Is there any way to do that?
Or you can create your own class (in VBA its called data type) which will hold variable name and values. Something like this
Public Type myFluffyType
fluffyName as string
fluffyValue as string
end Type
Then you can dim your variable like this
Dim fluffyVariable as myFluffyType
and initialize
fluffyVariable.fluffyName = "fluffyVariable"
fluffyVariable.fluffyValue = "notSoMuchFluffyValue"
and then when you passed it into your function you have all informations you need
Edit: on your problem you can do something like this. But im not sure what you exactly wana do next
Public type myType
varName as string
varValue as string
end type
Sub callDateCheck2
Dim sample as myType
sample.varName = "sample"
sample.varValue = "whateverValues"
Call dateCheck2(sample)
end sub
Function dateCheck2(dateValue As myType) As Boolean
if dateValue.varName = "sample" then
msgbox "everything ok"
else
msgbox "bad variable name"
end function
end if
If IIf(IsDate(frmResponse.txtEndDate), Format(CDate(frmResponse.txtEndDate), _
"mm\/dd\/yyyy"), "") = dateValue Then
dateCheck2 = True
Exit Function
End If
End Function
Just a very quick question: I want to create a function with an optional parameter because I can't find a need for a parameter in the function. As a result I have coded the following function in visual basic:
Sub characterListLength(ByVal Optional)
Dim rowCount As Integer
Dim endOfArray As Boolean
While endOfArray = False
If dataArray(0, rowCount) And dataArray(1, rowCount) = "" Then
arrayLength = rowCount
endOfArray = True
Else
rowCount += 1
End If
End While
End Sub
However on the first line:
Sub characterListLength(ByVal Optional)
There is an error where an identifier is expected where the code says (ByVal Optional). I am not sure how to fix this error and have the optional parameter. If anyone could explain what else I need to do to fix it, that would be very useful.
You need an actual variable, something like:
Sub characterListLength(Optional ByVal optionalNumber As Integer = 0)
If you said:
because I can't find a need for a parameter in the function
Then use method without parameters:
Sub characterListLength()
'Here your code
End Sub
You need to give the parameter a name and switch the order of the keywords
Sub characterListLength(Optional ByVal p = Nothing)
A better "dot-nettier" alternative to optional parameters is to use overloaded methods. Consider following:
Overloads Sub ShowMessage()
ShowMessage("This is the default alter message")
End Sub
Overloads Sub ShowMessage(ByVal Message As String)
Console.WriteLine(Message)
End Sub
Written like this you can call the above method both ways:
ShowMessage() 'will display default message
ShowMessage("This is custom message") 'will display method from the parameter
Demo: http://dotnetfiddle.net/OOi26i
I've been doing some code review and this code seemed weird to me since it doesn't have any return statement:
Protected Function AddZero(ByVal vsInput As String) As String
If Len(vsInput) = 1 Then
AddZero = "0" & vsInput
Else
AddZero = vsInput
End If
End Function
Visual Basic treats the function name as the return value and does not return until the end of the function. In the code, you can see that AddZero (the function name) is set to one of two values depending on the if condition. That is how you can determine what is returned.
In VB, you have an implicit return at the end of the function.
The function name gets assigned the return value, like this:
Protected Function AddZero(ByVal vsInput As String) As String
AddZero = "0" ' The return value is "0"
End Function
You can exit a function (return) like this:
Protected Function AddZero(ByVal vsInput As String) As String
If vsInput = "0" Then
AddZero = vsInput;
Exit Function
End If
AddZero = "0" ' The return value is "0"
End Function