VBA Notes
VBA Notes
3. VB Scrip:
It is installed by default with windows
It has no IDE(Integrated Development Environment)
.vbs is the file extension
It is used for login s script and web application
Bug :(An Error) : A bug may syntaxical error , (Compile error) , runtime error. (resource missing) or a logical
problem in the program (wrong variables or approach)
Recording Macros:
Rules:
Any letter
Store Macro in :
a. This work book: Current macro will be stored in the active work book
b. New work book: If this option is selected a new work book will be created (with single worksheet) and the
macro will be stored in it.
c. Personal Macro work book(pmw)
Optionally a pmw is created for each user
By default there is no pmw in excel
If this option is created for the first time pmw is created for the macro will be recorded in it.
Next time onwards the save pmw is anabled to store in unlimited no of macros
Macros in pmw can be accessed from all work books
PMW is a hidden workbook
Pmw is opened automatically whenever an excel session starts
Name of the pmw, personal .xlsb binary
Note: Binary files are optional for fast loading and space
Path of pmw(windows 7)
<<Drive>> : \ <<username>> \ appdata\roaming\microsoft\excel\XLSTART
4. Description: (optional):
Note: perform some action in excel click stop recorded button on the start bar
Click “Ok”
Perform required action in excel and click stoop record button on the status bar
If this option is selected macros are recoded with actions relative to the initial selected cell
MACRO SECURITY
Each VBA project has default category called Microsoft excel objects. (sheet1, sheet2, shee3,…..sheet, this
workbook)
Note: generally code in a module is opn(public) for all open work books
THE BASIC STRUCTURE OF A MACRO
Sub macro_name()
code
end sub
Way1:
Way2:
Code Window:
This drop down list displays all available objects (default is general)
This window displays the properties of the selected item, alphabetically or category wise and enables the user to
modify
IMMIDIATE WINDOW(CTRL G)
Example:
?10+30
40
?activesheet.name
Sheet6
?activeprinter
WebEx Document Loader on Ne00:
?activecell.Address
$A$1
OPERATIONS IN VBS
1. ARTHEMETIC: +, -, *, /
MOD: returns reminder
Ex : 13 mod 2 -> 1
^ (power)
Ex: 3 ^ 3 result 9
\ (Integer division)
Returns values executed decimals
Ex: 13/2 result 6
2. LOGICAL
AND , OR , NOT
DATA TYPES:
1. NUMBER
a. BYTE
(A-Z: 65-90, a-z, 97-122, 0-9, 48-57)
A data type is used to hold positive integer number ranging from 0 to 255
b. INTEGER
Numbers ranging in value from -32,768 to 32,767 (65536)
c. LONG
Numbers ranging in value from 2,147,483,648 to 2,147,483,647
d. SINGLE
Can store decimal values
e. DOUBLE (always we work with it) ----
Note: Declaring a data type for the variable is not mandatory in VBA
ALT+F11
INSERT – MODULE (ctrl R)
Type SUB key word space and the name of the macro
Example :
Sub macrosample()
Sheets.Add Count:=10
End Sub
ALT + f8
Select macro -> click run
Customize quck access toolbar or right click on tab and select customize quick access tool bar
Select macros option from choose commands drop down list
Select the macro and click add
Note: use move up or down option to change the order of commands
Click ok
Right click the image , select assign macro , press deleted key and click ok
?ABS(-345.678)
345.678
?ABS(9-34)
25
?ABS(30)
30
Example :
?ASC("A")
65
?ASC("R")
82
?ASC("34")
51
?ASC("%")
37
?ASC(" ")
32
3. CHR
Exaple
? CHR(89)
Y
?CHR(120)
X
Note: test(string) must be in “ “
Note : date must be in # #
Example :
?ROUND(3455.45667)
3455
?ROUND(34566.56789,2)
34566.57
Example:
?len("34567")
5
?len("")
0
?len("ac de")
5
Example:
?left(" az bc z",3)
az
?left("a23sdfd",4)
a23s
Example
?right("innovation",4)
tion
?right("sadaf 89 as",4)
9 as
EXAMPLE:
?MID("AKE2345SDF",3,4)
E234
?MID("EA1A D32E",3,5)
1A D3
10. INSTR([start],string1,string2)
Find pos of string2 in string 1 and returns the position if found. Returns 0 if not found
EXAMPLE:
?INSTR("CORPORATE FLOOR","OR")
?INSTR(3,"CORPORATE FLOOR","OR")
?INSTR(3,"CORPORATE FLOOR","ABC")
?INSTR(3,"CORPORATE FLOOR","OR",vbTextCompare)
11. STRREVERSE: whatever you want reverser this function will reverse
EXAMPLE:
?STRREVERSE("ABC DEF")
FED CBA
?STRREVERSE("34343DSS ")
SSD34343
12. LCASE: This function will convert into lcase
?LCASE("SFSDFSDFDS")
sfsdfsdfds
?lcase("DSsd2334AS")
dssd2334as
13. UCASE: this fuction will convert the string into Ucase
Example:
?ucase("sdfsAERE sfddf")
SDFSAERE SFDDF
14. StrConv:
22. VAL: return the value from the given number cum string combination
?val("34sdfs")
34
?val("skfdsfs")
0
?val("")
0
?val(" ")
0
?val("sfdsf34")
0
?val(45)
45
23. Time :
?time
1:39:12 PM
?time$ '24 hours format
13:39:23
?now
11/1/2012 1:39:46 PM
?hour(time)
13
?minute(time)
40
?second(time)
14
?month(#23-oct-2012#)
10
24. Datediff:
Syntax: Datediff(Interval, date1, date2)
?datediff("m",#23-oct-2012#,#12-1-2014#)
26
?datediff("yyyy",#23-oct-2012#,#12-1-2014#)
2
?datediff("s",#23-oct-2012#,#12-1-2014#)
66441600
?datediff("w",#23-oct-2012#,#12-1-2014#)
109
VARIABLE
A temporary memory location (in RAM) that can be used by a program while the program is being run
Note:- Memory used by object variables must be cleared by using “NOTHING” key
Dim a as integer
Sub abc()
A=10
end sub
Sub deff()
Msgbox a
End sub
Sub ghi()
End sub
Eample 2:
Sub operex()
MsgBox a + b
MsgBox a - b
MsgBox a / b
MsgBox a * b
MsgBox a ^ b
MsgBox a \ b
MsgBox a Mod b
MsgBox a & b
End Sub
Promt: message
Example:
Sub oper()
End Sub
LOCAL WINDOW
Displays the values of all variables in the current program in the break mode (step into mode : F8)
Note: 1. Variable can be used without declaring. 2. Those variables are VARIANT by default
OPTION EXPLICIT: To make variable declaration mandatory for all programs in the current module. OPTION
EXPLICIT can be used it is a module level statement that is applicable for all programs in the current module
Example:
Option Explicit
Sub opeex()
Dim a As Integer, b As Integer
End Sub
Question: how to set OPTION EXPLICIT as default for all new modules?
DATE : 27/10/12
IMPORTANT NOTE:
DATA DEFAULT
TYPE VALUES
STRING IS BLANK
VARIANT IS EMPTY
BOOLEAN IS FALSE
DATE IS 12:00 AM
INTEGER 0
Example1:
Sub iifex()
Dim n As Integer
End Sub
Example2:
Sub iifex2()
Dim n As Integer
End Sub
Example
Sub exam()
Dim n As Variant
MsgBox result
End Sub
Sub iifex2()
Dim n As Integer
n = ActiveCell.Value 'read value from active cell
End Sub
Example4:
Sub iifex2()
Dim n As Integer
End Sub
Example5:
Sub iffex3()
Dim n As Integer
n = ActiveCell.Value
End Sub
Example5:
Sub iffex()
Selection.Font.Bold = True
Selection.Offset(0, 3).Font.ColorIndex = 5
End Sub
Sub exam()
Dim n As String
Dim w As Worksheet
Set w = Sheets("sheet1")
Range("b:b").Clear
Dim i As Long
For i = 1 To w.UsedRange.Rows.Count
n = Cells(i, 1).Value
Cells(i, 2) = result
End If
Next
Set w = Nothing
End Sub
B. IF statement
IF is used to validate single or multiple level condition statements
If an IF statement written in a single line, END IF is not required
If an IF is written in multiple lines, it needs end IF
To validate multi level conditions Else If required
ELSE is optional in IF statement
ELSE is used to handle false or default
Syntax 3 : Multiline
Syntax 4 : Multiline)
NESTED IF
EXAMPLE:
SELECT CASE
It is used to look for different values (cases) in a variable an expression and then to execute concerned
Syntax:
End select
Example:
Sub seelctcaseexa()
w = InputBox("enter w value")
Select Case w
MsgBox res
End Sub
Application: Excel
Sub rangeex()
'Range("a3").Value = Date
'Range("a2").Value = "sample data"
Range("a1:b20").Value = ("new text")
End Sub
2. Select Object
Sub exsss()
'Range("a10").Select
'Range("a1:b10").Select
'Range("a1:b10,d5:d8,k8").Select
'Range("a:a").Select ' complete column
Range("a:c,e:f,h20,k:k").Select
End Sub
?selection.address
$A:$C,$E:$F,$H$20,$K:$K
?selection.address
$1:$1048576,$E:$F,$H$20,$K:$K
Row Property
?range("a1:x20").Rows.Count
20
?range("b1:c23").rows.count
23
?selection.rows.count
1048576
?selection.columns.count
16384
Sub excap()
Range("a1:b6").Font.Name = "algeria"
Range("a1:b6").Font.Bold = True
Range("a1:b6").Font.Italic = True
Range("a1:b6").Font.ColorIndex = 5
End Sub
Color example
Note: there are 56 default colors in excel
Example:
Sub colorex()
Dim i As Integer
For i = 1 To 56
Cells(i, 1).Interior.ColorIndex = i
Next
End Sub
Purpose:
Sub coloexc()
Dim sh As Worksheet
Set sh = Sheets("sheet1")
For i = 1 To sh.UsedRange.Count
Cells(i, 1).Interior.ColorIndex = 34
Cells(i, 1).Interior.ColorIndex = 35
Cells(i, 1).Interior.ColorIndex = 36
Else
Cells(i, 1).Interior.ColorIndex = 37
End If
Next
Set sh = Nothing
End Sub
Range("a1:a7").Cut Range("b2")
End Sub
Example 2
Sub cutex()
Range("a8:a15").Cut Sheets("sheet2").Range("d2")
End Sub
Sub cutex()
Workbooks("book1").Sheets("sheet1").Range("a1:b10").Cut Workbooks("book2").Sheets("sheet1").Range("d10")
End Sub
Ex 1:
'Range("a1:a5").Copy Range("b2")
Ex2
Range("b1:b8").Copy
Range("f1").PasteSpecial
Ex3
Sub passpex()
Range("a1:a5").Copy
Range("c1").PasteSpecial , xlPasteSpecialOperationNone
Application.CutCopyMode = False
End Sub
Ex4:
Sub passpex()
Range("a1:a5").Copy
Range("c1").PasteSpecial , xlPasteSpecialOperationAdd
Application.CutCopyMode = False
End Sub
LOOP
FOR : For is a number based loop i.e it runs for fixed no of times
FOR LOOP:
Code to be repeat
Next [variable_name]
EX1
Example:
Sub forex()
Dim i As Integer
For i = 1 To 10
MsgBox "done"
Next
End Sub
Ex2
Sub forex()
Dim i As Integer
For i = 1 To 10
Debug.Print "abc"
Next
End Sub
EX3
Sub forex()
Dim i As Integer
For i = 1 To 10
Debug.Print i
Next
End Sub
Ex4
Sub forex()
Dim i As Integer
For i = 1 To 10 Step 2
Debug.Print i
Next
End Sub
EX5
Print 10 to 1 numbers in immidate window
Sub forex()
Dim i As Integer
For i = 10 To 1 Step -1
Debug.Print i
Next
End Sub
EX6
Sub forex()
Dim i As Integer
For i = 1 To 10
Sheets("sheet2").Range("b" & i) = i
Next i
End Sub
EX7
Sub forex()
Dim i As Integer
For i = 1 To 10
'Sheets("sheet3").Cells(i, 1) = i
Sheets("sheet3").Cells(i, "a") = i
Next
End Sub
EX8
Print 10 to 1 in column A
Sub forex()
Dim i As Integer
For i = 10 To 1 Step -1
Sheets("sheet1").Cells(11 - i, 1) = i
Next
End Sub
EX9
Sub forex()
Cells.Clear
For i = 10 To 1 Step -1
j=j+1
Cells(j, "a") = i
Next i
End Sub
EX10
Sub forex()
Dim i As Integer
Cells.Clear
For i = 1 To 10
Next i
End Sub
EX12
r = 1: c = 1
Cells.Clear
For i = 1 To n
Cells(r, c) = i
r=r+1
If r = 120 Then
r = 1: c = c + 1
End If
Next
End Sub
Sub cheadex()
Dim y As Integer
y = 2011
Cells.Clear
Dim i As Integer
For i = 1 To 10
Cells(1, i + 1) = y + 1
Next
For i = 1 To 4
Next
End Sub
Ex14
Sub extracnum()
Dim i As Integer
Dim j As Integer
For j = 1 To 10
Cells(j, 2).Clear
str = Cells(j, 1)
For i = 1 To Len(str)
End If
Next
Cells(j, 2) = Nums
Nums = blank
Next j
Columns.AutoFit
End Sub
Ex15
Dim i As Integer
n = InputBox("enter n value")
For i = 1 to n
If n Mod i = 0 Then
factor = factor + 1
End If
Next
If factor = 2 Then
MsgBox "prime"
Else
End If
End Sub
Ex16
Sub speex()
str = StrReverse([a1])
Dim i As Integer
For i = 1 To Len(str)
Exit For
End If
Next
End Sub
Ex17 : remove last comma
str = StrReverse(str)
Dim i As Integer
For i = 1 To Len(str)
Exit For
End If
Next
End Function
FOR EACH
EX1
Sub forec
Pprasad.hfm@gmail.com
EX2:
Sub repex()
rpt = c.Next.Value
For i = 1 To rpt
Cells(rowno + i, 3) = c.Value
Next i
End Sub
Ex3
Sub repex()
rpt = c.Next.Value
Dim i As Integer
j=j+1
Cells(j, 3).Clear
For i = 1 To rpt
If Len(c.Next.Next.Value) = 0 Then
c.Next.Next.Value = c.Value
Else
End If
Next
Next
Columns.AutoFit
End Sub
Sub sheetsexist()
Dim i As Integer
i=i+1
shfound = True
Exit For
End If
Next
MsgBox sheetname & ":" & "sheet sequence is :" & i & " found"
Else
MsgBox "out of " & i & " sheets " & sheetname & " sheet is not found"
End If
End Sub
Sub sheetfouex()
Sheets(sheetname).Name = sheetname
Exit Sub
Dothis:
End Sub
WHILE LOOP
Syntax:
Code
Wend
Example:
Sub printex()
Dim i As Integer
i=1
While i <= 10
Debug.Print i
i=i+1
Wend
End Sub
DO LOOP:
Condition based
While – pre check
Do post check
Runs the loop at least one time
Syntax:
Do
Code
Note: While(after loop) runs the loop as long as the conditional part is true whereas until(after loop)runs the loop as long as the
conditional part is false
EX:
Sub printex()
Dim i As Integer
i=1
Do
Debug.Print i
i=i+1
End Sub
Example
Sub printex()
Dim i As Integer
i=1
Do
Debug.Print i
i=i+1
Loop Until i = 11
End Sub
Example:
Sub wordcount()
For i = 1 To Len(str)
End If
Next
Cells(1, 2) = wcount
Columns.AutoFit
End Sub
Example:
Sub wordcount()
For j = 1 To 10
For i = 1 To Len(str)
wcount = wcount + 1
End If
Next
Cells(j, 2) = wcount
wcount = blank
Next
Columns.AutoFit
End Sub
Example:
Sub wordcount()
Cells(1, 2) = wcount
Columns.AutoFit
End Sub
Example : same
Sub wordcount()
Cells(1, 2) = wcount
Columns.AutoFit
End Sub
Example:
Sub commamt()
Do
Else
comm = 1000
End If
MsgBox "salse is : " & samt & ", commission: " & Round(comm, 2)
End Sub
Example:
Sub wordex()
Set w = CreateObject("word.application")
Set wd = w.documents.Add
wd.SaveAs "D:\prasadmacro.docx"
Set wd = Nothing
w.Quit
Set w = Nothing
End Sub
Example:
Sub pptex()
ppt.Visible = True
Sheets("sheet1").ChartObjects(1).Copy
ppt.ActiveWindow.View.Paste
Application.CutCopyMode = False
pps.SaveAs "d:\newppt.pptx"
pps.Close
ppt.Quit
End Sub
Ex 2
Sub pptex()
m.To = "abc@yahoo.com"
m.Subject = "Main"
m.attachment = "C:\abc.txt"
m.send
otl.Quit
Set m = Nothing
End Sub
Example 2 ‘ send mail with function
Sub sendml()
End Sub
End Function
m.To = sendto
m.subject = subject
m.body = body
m.attachment = attachment
End If
m.send
otl.Quit
Set m = Nothing
End Function
Scripting.filesystemobject – FSO
Example:
TV - > DVD Player - > DVD
Sub getdrive()
Dim fs As Object
Set fs = CreateObject("scripting.filesystemobject")
Dim d, i As Integer
Cells.Clear
i=i+1
Cells(i, 1) = d
Next
End Sub
Example2
Sub subfolders()
Set fs = CreateObject("scripting.filesystemobject")
fpath = "d:\"
Dim f, i As Integer
Cells.Clear
i=i+1
Cells(i, 1) = f.Name
Next
Cells(i + 1, 1) = "total sub folders:" & fol.subfolders.Count
Cells(i + 1, 1).Interior.ColorIndex = 7
Columns.AutoFit
Set fs = Nothing
End Sub
Sub getfiles()
Set fs = CreateObject("scripting.filesystemobject")
fpath = "D:\Others\foster"
Cells.Clear
Cells(1, 1) = "name"
Cells(1, 2) = "type"
Cells(1, 3) = "extension"
Cells(1, 4) = "size"
Cells(1, 7) = "path"
Dim f, i As Integer
i=1
i=i+1
Cells(i, 1) = f.Name
Cells(i, 2) = f.Type
'Cells(i, 3) = f.getextensionname(f.Name)
Cells(i, 4) = f.Size
Cells(i, 5) = f.datecreated
Cells(i, 6) = f.datelastmodified
Cells(i, 7) = f.Path
Next
Columns.AutoFit
Set fs = Nothing
End Sub
Purpuse:
Sub exce()
With Application.FileDialog(msoFileDialogFolderPicker)
.InitialFileName = "c:\"
.Show
fpath = .SelectedItems(1)
End With
MsgBox fpath
End Sub
Sub exce()
Cells.Clear
With Application.FileDialog(msoFileDialogFilePicker)
.Title = "Select on or more files"
.InitialFileName = "C:\"
'.AllowMultiSelect = True
.Show
Dim f, i As Integer
i=i+1
Cells(i, 1) = f
Next
End With
Columns.AutoFit
End Sub
Sub exce()
Cells.Clear
With Application.FileDialog(msoFileDialogFilePicker)
.Filters.Clear
.InitialFileName = "c:\"
.AllowMultiSelect = True
.Show
Dim f, i As Integer
i=i+1
Cells(i, 1) = f
Next
End With
Columns.AutoFit
End Sub
Sub exce()
Cells.Clear
With Application.FileDialog(msoFileDialogFolderPicker)
.Show
fpath = .SelectedItems(1)
End With
Dim fs As Object
Set fs = CreateObject("scripting.filesystemobject")
Dim f, i As Integer
i=i+1
Workbooks.Open f.Path
ActiveWorkbook.Close
End If
Next
MsgBox "Excel files are converted to PDF", vbInformation
End Sub
Sub workshname()
Dim i As Integer
Worksheets.Add Count:=9
For i = 1 To Sheets.Count
Next i
End If
End Sub
Purpuse:
Sub workshname()
For y = 1 To ycount
For s = 1 To 12
Sheets.Add after:=Sheets(Sheets.Count)
Next y
End Sub
Purpose:
Sub jan2decassheetnames()
prevshcount = Sheets.Count
Set ts = Sheets.Add(after:=Sheets(Sheets.Count))
For s = 1 To prevshcount
i=i+1
ts.Cells(i, 1) = Sheets(i).Name
Next
Dim y As Integer
For y = 1 To yrcount
For s = 1 To 12
Sheets.Add after:=Sheets(Sheets.Count)
Next
Next
Application.DisplayAlerts = False
Sheets(c.Value).Delete
Next
ts.Delete
Application.DisplayAlerts = True
End Sub
Purpose:
Sub jan2decasSheetNames()
Workbooks.Add
Application.DisplayAlerts = flse
sh.Delete
Next
Dim y As Integer
For y = 1 To yrcount
For s = 1 To 12
Sheets.Add after:=Sheets(Sheets.Count)
Next
Next
Application.DisplayAlerts = True
End Sub
Dim ws As Worksheet
ws.Name = "Summary"
applicaiton.ScreenUpdating = False
sh.UsedRange.Copy ws.Range("a1")
HeadingCopied = True
Else
End If
End If
Next
Set ws = Nothing
Application.ScreenUpdating = False
End Sub
Sub findShName()
Exit For
End If
Next
Else
End If
End Sub
Sub DeleteHiddenSheets()
'
'
i=1
Worksheets(i).Delete
Else
i=i+1
End If
Wend
End Sub
Purpuse:
Sub consolidateFromAllWbksFromSelFolder()
With Application.FileDialog(msoFileDialogFolderPicker)
.Show
folpath = .SelectedItems(1)
End With
With Application.FileDialog(msoFileDialogFilePicker)
.Filters.Clear
.AllowMultiSelect = False
.Show
fpath = .SelectedItems(1)
End With
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Set fs = CreateObject("scripting.filesystemobject")
For i = 1 To tgtwbk.Sheets.Count
srcwbk.Sheets(i).UsedRange.Copy tgtwbk.Sheets(i).Range("a1")
Next
HeadingsCopied = True
Else
For i = 1 To tgtwbk.Sheets.Count
Frow = srcwbk.Sheets(i).UsedRange.Row
NextRowInTgt = tgtwbk.Sheets(i).UsedRange.Rows.Count + 1
Next
End If
End If
Next
tgtwbk.Close True
Application.DisplayAlerts = True
Application.ScreenUpdating = True
MsgBox "Done"
End Sub
Purpose:
Sub consolidateEx()
sname = "summary"
shFound = True
End If
Next
Sheets("Summary").Cells.Clear
Set ws = Sheets("summary")
Else
'first sheet
Set ws = Sheets.Add(before:=Sheets(1))
ws.Name = "Summary"
'last sheet
'Set ws = Sheets.Add(after:=Sheets(Sheets.Count))
End If
Application.ScreenUpdating = False
For Each sh In Sheets
sh.UsedRange.Copy ws.Range("a1")
HeadingsCopied = True
Else
End If
End If
Next
Application.ScreenUpdating = True
End Sub
Sub findSheet()
shFound = True
End If
Next
If shFound = True Then
Else
End If
End Sub
08/12/2012
Sub deleteEmptyShs()
Dim sh
Application.DisplayAlerts = flase
If IsEmpty(sh.UsedRange) Then
sh.Delete
End If
Next
Application.DisplayAlerts = True
End Sub
Sub filterNCopy()
Dim t
t = Now()
Dim ws As Worksheet
Set ws = Sheets("sheet1")
Dim ts As Worksheet
'Application.ScreenUpdating = False
'the above line stops the excel screen update for each line of code and speed up execution
Set ts = Sheets.Add(after:=Sheets(Sheets.Count))
ws.Range("a:a").Copy ts.Range("a1")
ts.UsedRange.RemoveDuplicates 1, xlYes
Dim c
Sheets.Add after:=Sheets(Sheets.Count)
ActiveSheet.Name = c.Value
ws.UsedRange.AutoFilter 1, c.Value
ws.UsedRange.Copy ActiveSheet.Range("a1")
End If
Next
ws.UsedRange.AutoFilter
ws.Activate
Application.DisplayAlerts = False
ts.Delete
Application.DisplayAlerts = True
'Application.ScreenUpdating = True
Set ws = Nothing
Set ts = Nothing
End Sub
Sub colorcells()
Dim t
t = Now()
'Application.ScreenUpdating = False
Dim i As Integer, j As Integer
For i = 1 To 100
For j = 1 To 56
Range("a1:b500").Interior.ColorIndex = j
Next j
Next i
'Application.ScreenUpdating = True
End Sub
Sub removelastcom()
str = Cells(1, 1)
Dim i As Integer
Next
Cells(2, 1) = Left(str, i)
End Sub
ARRAYS
Array: -
Note: Lbound and Ubound are used to find out lower bound and upper bound of an array respectively usage
Single dim:
Lbound(arrayname)/Ubound(arrayname)
Multi dim:
Sub arrayex()
cities(1) = "Hyd"
cities(2) = "Bang"
cities(3) = "Delhi"
'Get Lbound and Ubound
MsgBox LBound(cities)
MsgBox UBound(cities)
'Get an element
MsgBox cities(2)
End Sub
Option Base 1
Sub arrex()
cities(1) = "Hyd"
cities(2) = "Bang"
cities(3) = "Delhi"
MsgBox LBound(cities)
MsgBox UBound(cities)
'get an element
MsgBox cities(1)
End Sub
Option Base 1
Sub arrex()
Dim i As Integer
For i = 1 To 3
a(i) = Cells(i, 1)
Next
End Sub 'Ctrl+F8 -> run to cursor, view-> local window, expand
Option Base 1
Sub arrayex()
Dim n As Integer
n = ActiveSheet.UsedRange.Rows.Count
'Note: PRESERVE keyword is used to keep the existing data unearased in the current array while resize
ReDim a(n)
Dim i As Integer
' for i = 1 to n
a(i) = Cells(i, 1)
Next i
End Sub
Sub arrayex()
n = ActiveSheet.UsedRange.Rows.Count
ReDim a(n)
Dim i As Integer
a(i) = Cells(i, 1)
Next
'sort values
tempval = a(i)
a(i) = a(j)
a(j) = tempval
End If
Next
Next
End Sub
09/12/2012
Sub variantex()
Dim a
MsgBox a(3)
End Sub
Example:
Sub importdatafromaTextfileWithDelimeter
Sub importdatafromaTextfileWithDelimeter()
Set fs = CreateObject("scripting.filesystemobject")
s = f.readline
Dim a, i As Integer
'a = split(s,",")
a = Split(s, Chr(vbKeyTab))
r=r+1
'Cells(r, i + 1) = a(i)
Else
Cells(r, i + 1) = a(i)
End If
Next
Wend
With Range("1:1")
.HorizontalAlignment = xlCenter
.Font.Bold = True
.Font.Underline = True
End With
Columns.AutoFit
Set fs = Nothing
Set f = Nothing
End Sub
Sub getmaxoflast2daydesalConsum()
Dim ws As Worksheet
Set ws = Sheets("sheet2")
ws.UsedRange.AutoFilter 1, StrIndusID
Dim c, dc As Double
dc = dc + c.Previous.Value
End If
End If
Next
ws.UsedRange.AutoFilter
MsgBox dc
End Sub
Example:
Multi-dimensional Arrays:
Option Base 1
Sub multidim()
a(r, c) = Cells(r, c)
Next
Next
End Sub
Example:
Option Base 1
Sub multidim()
a(r, c) = Cells(r, c)
Next
Next
End Sub
Example”:
Sub multidimex()
Dim a(1 To 4, 1 To 3)
a(r, c) = Cells(r, c)
Next
Next
Next
Next
Cells(r, c) = a(r, c)
Next
Next
End Sub
Example:
Sub variantarraywithrange()
Dim a, rng As Range
For r = 1 To rng.Rows.Count
For c = 1 To rng.Columns.Count
Next
Next
rng = a
End Sub
Sub N2FOREACH()
c.Value = Abs(c.Value)
End If
Next
End Sub
Example:
Sub n2pwithforeach()
Dim c
(xlCellTypeConstants, xlNumbers)
End Sub
Example:
Work on Text
Syntax:
Code
End Function
Note: These parameters work as placeholders for the values supplied while using the UDF
Example: 1
Sub sample()
Dim str As String, TempStr As String
str = Range("a1")
Dim i As Integer
For i = 1 To Len(str)
End If
Next
Range("b1") = TempStr
End Sub
Dim i As Integer
For i = 1 To Len(str)
End If
Next
GetNum = TempStr
End Function
Example 2
Sub callgnums()
Dim c As Range
Next
Set c = Nothing
End Sub
Dim i As Integer
For i = 1 To Len(str)
End If
Next
GetNum = TempStr
End Function
Example 3
Sub callgnums()
Dim s As String
s = InputBox("Enter a string")
MsgBox GetNum(s)
End Sub
Dim i As Integer
For i = 1 To Len(str)
End If
Next
GetNum = TempStr
End Function
Example 4