Anonymous user
User:Klever: Difference between revisions
→VBA Examples
No edit summary |
|||
Line 12:
=VBA Examples=
Some nontrivial VBA Examples (until there is a separate VBA category).
In MS Office program (Word, Excel, Access...): open the Visual Basic window. Paste the code in a module. Execute it by typing a suitable command in the Immediate Window. Output will be directed to the Immediate Window unless stated otherwise...
==[[
===Non-recursive version===
<lang>
Public Function Reverse(aString as String) as String
' returns the reversed string
dim L as integer 'length of string
dim newString as string
newString = ""
L = len(aString)
for i = L to 1 step -1
newString = newString & mid$(aString, i, 1)
next
Reverse = newString
End Function
</lang>
===Recursive version===
<lang>
Public Function RReverse(aString As String) As String
'returns the reversed string
'do it recursively: cut the sring in two, reverse these fragments and put them back together in reverse order
Dim L As Integer 'length of string
Dim M As Integer 'cut point
L = Len(aString)
If L <= 1 Then 'no need to reverse
RReverse = aString
Else
M = Int(L / 2)
RReverse = RReverse(Right$(aString, L - M)) & RReverse(Left$(aString, M))
End If
End Function
</lang>
===Example dialogue===
<pre>
print Reverse("Public Function Reverse(aString As String) As String")
gnirtS sA )gnirtS sA gnirtSa(esreveR noitcnuF cilbuP
print RReverse("Sunday Monday Tuesday Wednesday Thursday Friday Saturday Love")
evoL yadrutaS yadirF yadsruhT yadsendeW yadseuT yadnoM yadnuS
print RReverse(Reverse("I know what you did last summer"))
I know what you did last summer
</pre>
==[[Ordered words]]==
<lang>
Public Sub orderedwords(fname As String)
|