Coding Basics
- How to use more than one condition in Select case statement
- Code:
Sub Main()
Select Case True
Case Combo1.ListIndex = 0 And List1.ListIndex = 0
MsgBox "combo listindex = 0 and list.listindex=0"
Case Combo1.ListIndex = 0 And List1.ListIndex = 1
MsgBox "combo listindex = 0 and list.listindex=1"
Case Combo1.ListIndex = 0 And List1.ListIndex = 2
MsgBox "combo listindex = 0 and list.listindex=2"
Case Else
MsgBox "none of the previous"
End Select
End Sub
- Sendkeys example
- Code:
Private Sub Command1_Click()
Dim i As Integer
Dim retval As Double
retval = Shell("notepad", vbNormalFocus)
AppActivate retval
For i = 0 To 1000
SendKeys i & " ", True
Next i
End Sub
- How to find the number of a name, used in a numerology program
- Code:
Public Function NameNum(namelen, name) As Long
name2 = LCase(name)
For letter = 1 To namelen
Name4 = Mid(name2, letter, 1)
Debug.Print Name4
Select Case Name4
Case "a"
Number = Number + 1
Case "b"
Number = Number + 2
Case "c"
Number = Number + 3
Case "d"
Number = Number + 4
Case "e"
Number = Number + 5
Case "f"
Number = Number + 6
Case "g"
Number = Number + 7
Case "h"
Number = Number + 8
Case "i"
Number = Number + 9
Case "j"
Number = Number + 1
Case "k"
Number = Number + 2
Case "l"
Number = Number + 3
Case "m"
Number = Number + 4
Case "n"
Number = Number + 5
Case "o"
Number = Number + 6
Case "p"
Number = Number + 7
Case "q"
Number = Number + 8
Case "r"
Number = Number + 9
Case "s"
Number = Number + 1
Case "t"
Number = Number + 2
Case "u"
Number = Number + 3
Case "v"
Number = Number + 4
Case "w"
Number = Number + 5
Case "x"
Number = Number + 6
Case "y"
Number = Number + 7
Case "z"
Number = Number + 8
Case " "
Number = Number + 0
End Select
Next letter
Debug.Print Number
Nu = Val(Number)
Do
Nu = Val(Mid(CVar(Nu), 1, 1)) + Val(Mid(CVar(Nu), 2, 1))
Debug.Print Nu
Loop Until Nu < 10
NameNum = Nu
End Function
- How to Convert Binary to Decimal
- Code:
Public Function BinToDec(value As String) As Long
Dim result As Long, i As Integer, exponent As Integer
For i = Len(value) To 1 Step -1
Select Case Asc(Mid$(value, i, 1))
Case 48 ' "0", do nothing.
Case 49 ' "1", add the corresponding power of 2.
result = result + Power2(exponent)
Case Else
Err.Raise 5 ' Invalid procedure call or argument
End Select
exponent = exponent + 1
Next
BinToDec = result
End Function
- How to Convert Binary to Octal
- Code:
Public Function ConvertBinaryToOctal(BinVal As String) As String
Dim i%, Length%
Select Case (Len(BinVal) Mod 3)
Case 1:
BinVal = "00" + BinVal
Case 2:
BinVal = "0" + BinVal
End Select
Length = Len(BinVal)
For i = Length - 2 To 1 Step -3
ConvertBinaryToOctal = GetValue(Mid(BinVal, i, 3), False) + ConvertBinaryToOctal
Next i
End Function
Private Function GetValue(strBinary As String, blnRemainder As Boolean) As String
Dim intPwrOfTwo As Integer
Dim intResult As Integer
intResult = 0
intPwrOfTwo = -1
For i = Len(strBinary) To 1 Step -1
intPwrOfTwo = intPwrOfTwo + 1
strChar = Mid(strBinary, i, 1)
If strChar = "1" Then
intResult = intResult + 2 ^ intPwrOfTwo
End If
Next
GetValue = LTrim(Str(intResult))
End Function
- How to Convert Decimal to Hexadecimal
- Code:
Public Function ConvertDecimalToHexadecimal(Value As Double) As String
Dim iVal#, temp#, ret%, i%, Str$
Dim BinVal$()
iVal = Value
Do
temp = iVal / 16
ret = InStr(temp, ".")
If ret > 0 Then
temp = Left(temp, ret - 1)
End If
ret = iVal Mod 16
ReDim Preserve BinVal(i)
BinVal(i) = NoToHex(ret)
i = i + 1
iVal = temp
Loop While temp > 0
For i = UBound(BinVal) To 0 Step -1
Str = Str + CStr(BinVal(i))
Next
ConvertDecimalToHexadecimal = Str
End Function
Private Function NoToHex(i As Integer) As String
Select Case i
Case 0 To 9
NoToHex = CStr(i)
Case 10:
NoToHex = "A"
Case 11:
NoToHex = "B"
Case 12:
NoToHex = "C"
Case 13:
NoToHex = "D"
Case 14:
NoToHex = "E"
Case 15:
NoToHex = "F"
End Select
End Function
- How to Convert from decimal to binary
- Code:
Function Bin(ByVal value As Long) As String
Dim result As String, exponent As Integer
' This is faster than creating the string by appending chars.
result = String$(32, "0")
Do
If value And Power2(exponent) Then
' We found a bit that is set, clear it.
Mid$(result, 32 - exponent, 1) = "1"
value = value Xor Power2(exponent)
End If
exponent = exponent + 1
Loop While value
Bin = Mid$(result, 33 - exponent) ' Drop leading zeros.
End Function
- How to find a given year is leap year or not
- Code:
Function IsLeapYear(year As Integer) As Boolean
' Are February 29 and March 1 different dates?
IsLeapYear = DateSerial(year, 2, 29) <> DateSerial(year, 3, 1)
End Function
- How to generate random numbers, with the info
- Code:
'1) How many values - txtValue
'2) What the max is - txtMax
'3) What the min is - txtMin
'4) If they want duplicate random numbers, or not
' - OptionBoxes
' - Option1 = Double
' - Option2 = No Double
Option Explicit
Dim HowMany As Integer
Dim RndNum As Integer
Dim Answer As String
Dim I As Integer
Dim Search As Integer
Private Sub cmdGenerate_Click()
On Error GoTo Problem
Randomize
ReDim Ans(TxtValue)
If Option1.Value = True And TxtMax - TxtMin < TxtValue Then
MsgBox "It is impossible to generate that amount of random numbers without doubles."
Exit Sub
End If
Answer = ""
For HowMany = 1 To TxtValue 5
RndNum = Int(Rnd * TxtMax) + TxtMin
If RndNum > TxtMax Then GoTo 5
If Option2.Value = True Then
Ans(HowMany) = RndNum
Else
For Search = 1 To HowMany
If RndNum = Ans(Search) Then GoTo 5
Next Search
Ans(HowMany) = RndNum
End If
Next HowMany
For I = 1 To TxtValue
Answer = Answer & Ans(I)
If I <> TxtValue Then Answer = Answer & ", "
Next I
MsgBox Answer
Exit Sub
Problem:
MsgBox Err.Description
End Sub
- How to converte color value(longint) into RGB value
- Code:
Public Function rgbcolortovalue(rslt As Long) As String
Dim tmphasil1 As Byte
Dim tmphasil2 As Byte
Dim tmphasil1a As Byte
Dim tmphasil1b As Byte
Dim tmphasil1c As Long
If rslt < 256 Then
rgbcolortovalue = Trim(Format(rslt, "0##")) + ",000,000"
ElseIf (rslt > 256) And (rslt < 65536) Then
tmphasil1 = rslt Mod 256
tmphasil2 = Int(rslt / 256)
rgbcolortovalue = Trim(Format(tmphasil1, "0##")) + "," + Trim(Format(tmphasil2, "0##")) + ",000"
ElseIf rslt > 65535 Then
tmphasil2 = Int(rslt / 65536)
tmphasil1c = rslt Mod 65536
If tmphasil1c < 256 Then
rgbcolortovalue = Trim(Format(tmphasil1c, "0##")) + ",000," + Trim(Format(tmphasil2, "0##"))
Else
tmphasil1a = tmphasil1c Mod 256
tmphasil1b = Int(tmphasil1c / 256)
rgbcolortovalue = Trim(Format(tmphasil1a, "0##")) + "," + Trim(Format(tmphasil1b, "0##")) + "," + _
Trim(Format(tmphasil2, "0##"))
End If
End If
End Function
- How to accept any number of arguments in a function
You can implement a routine that accepts any number of arguments using the ParamArray keyword
- Code:
Function Sum(ParamArray args() As Variant) As Double
Dim I As Integer
' All ParamArrays are zero-based.
For I = 0 To UBound(args)
Sum = Sum + args(I)
Next
End Function
- How to Convert text into the Currency data type
- Code:
Option Explicit
' Convert any value into currency format. If the value does not make sense, return 0.00.
Public Function cvCur(ByVal Value As Variant) As Currency
On Error Resume Next
cvCur = CCur(Value)
If Err.Number <> 0 Then cvCur = 0
End Function
Private Sub cmdConvert_Click()
lblCurrency.Caption = Format$(cvCur(txtCurrency.Text), "Currency")
End Sub
- How to Convert Hexadecimal to Decimal
- Code:
Public Function ConvertHexadecimalToDecimal(BinVal As String) As String
Dim iVal#, temp#, i%, Length%
Length = Len(BinVal)
For i = 0 To Length - 1
temp = HexToNo(Mid(BinVal, Length - i, 1))
iVal = iVal + (temp * (16 ^ i))
Next i
ConvertHexadecimalToDecimal = iVal
End Function
Private Function HexToNo(i As String) As Integer
Select Case i
Case "0", "1", "2", "3", "4", "5", "6", "7", "8", "9":
HexToNo = CInt(i)
Case "A", "a":
HexToNo = 10
Case "B", "b":
HexToNo = 11
Case "C", "c":
HexToNo = 12
Case "D", "d":
HexToNo = 13
Case "E", "e":
HexToNo = 14
Case "F", "f":
HexToNo = 15
End Select
End Function
- How to use InputBox function and get values
- Code:
Dim sInput As String
sInput = InputBox("Test Title", "InputBox", "Some text here")
If StrPtr(sInput) = 0 Then
MsgBox "Cancel was pressed"
Else
If Len(sInput) = 0 Then
MsgBox "OK pressed but nothing entered."
Else
MsgBox "OK pressed: value= " & sInput
End If
End If
- How to use Like() function
- Code:
'Like() function used for Pattern-Matching in Code
Dim strTest As String
strTest = "@ciSmith v. Barney, 21 A2d 459, 35 ME2d 256 (1985)@ec"
'The following comparisons will result in True or False results as indicated:
Result = strTest Like "*F2d*" '(Result would be False)
Result = strTest Like "*A2d*" '(Result would be True)
Result = strTest Like "@ci*@ec" '(Result would be True)
'One glitch is that It doesn't recognized "[0-9]@" whereas it will recognize
'particular occurrences of the character class. "[0-9][0-9][0-9]"
- How to convert Octal to Decimal number
- Code:
Public Function ConvertOctalToDecimal(BinVal As String) As String
Dim iVal#, temp#, i%, Length%
Length = Len(BinVal)
For i = 0 To Length - 1
temp = CInt(Mid$(BinVal, Length - i, 1))
iVal = iVal + (temp * (8 ^ i))
Next i
ConvertOctalToDecimal = iVal
End Function
- How to copy/cut the content of the text box to the clipboard
- Code:
Sub cmdCopy_Click()
Clipboard.SetText Text1.SelText 'Copies only selected text
'Clipboard.SetText Text1.Text 'Copies whole TextBox content
End Sub
Private Sub cmdCut_Click()
Clipboard.SetText Text1.SelText
Text1.SelText = ""
End Sub
- What exactly does ByVal and ByRef mean and when do you use it?
- Code:
'ByVal means to pass just the Value of a Variable, where as
'ByRef means to pass a Reference to the Variable itself.
'For Example,
Function AddOne(ByVal iNum As Integer) As Integer
iNum = iNum + 1
AddOne = iNum
End Function
Sub Main()
Dim I As Integer
I = 1
Debug.Print AddOne(I)
Debug.Print I
End Sub
'This would Print 2, then 1 as only the Value 1 is passed to
'the Function so the value of I never actually changes.
Function AddOne(ByRef iNum As Integer) As Integer
iNum = iNum + 1
AddOne = iNum
End Function
Sub Main()
Dim I As Integer
I = 1
Debug.Print AddOne(I)
Debug.Print I
End Sub
'This would Print 2, then 2 again as a Refernce to the Actual
'Variable was passed, so changing iNum was like Changing I itself.
'If ByVal/ByRef isn't specified, default is ByRef
- How to display a message in two lines in MSG Box
- Code:
Call MsgBox("This is First line." & vbCrLf & "This is Second line.")
- How to Check whether the user pressed the Cancel Button on Input Box
- Code:
Private Sub Command1_Click()
Dim str As String
str = InputBox("Press OK or Cancel")
If StrPtr(str) = 0 Then
MsgBox "The user pressed the Cancel button"
End If
End Sub