Sie sind auf Seite 1von 21

Excel VBA

Program to practice

Write a program to change the color of alternate cells


Example of Do While loop:
Sub ShadeEverySecondRow()
Range(“A2”).EntireRow.Select
Do while Activecell. Value <> “ “
Selection. Interior. ColourIndex = 15
Activecell. Offset(2, 0) . EntireRow . Select
Loop
End Sub

Example of Do Until loop


Sub shadeEverySecondRow()
Dim 1Row As Long
1Row= 2
Do Until IsEmpty(Cells (1Row, 1))
Cells(1Row , 1). EntireRow. Interior.ColorIndex = 15
1Row= 1Row+ 2
Loop
End Sub

Example of Do Loop
Sub ShadeEverySecondRow()
Dim 1Row as Long
1Row= 0
Do
1Row= 1Row+ 2
If IsEmpty (Cells (1Row, 1) ) Then Exist Do
Rows (1Row). Interior. ColorIndex = 15
Loop
End Sub

Example of Do Until (WAP to accept the value if password is correct)


Sub GetPassword()
Dim sPassWord As String, I As Integer
i= 0
Do
I = I + 1
If i > 3 Then
MsgBox “Sorry, Only three tries”
Exist Sub
End If
sPassword = InputBox(“Enter Password”)
Loop Until sPassword = ”xxx”
MsgBox “Welcome”
End Sub

Saroj Kumar Shrama 1


Excel VBA

Example of For Next Loop ( WAP to set the footer as filename)


Sub FilePathInFooter()
Dim i As Integer, sFilePath As String
sFilePath = ActiveWorkbook. FullName
For i = 1 To Worksheets . Count Step 1
Worksheets(i) . pageSetup . CenterFooter = sFilepath
Next i
End Sub

WAP to get the filename from the given fullpath


The below examples show how you can step backwards. It takes a complete file path and strips out
the filename, excluding the file extension.

Sub GetFileName()
Dim iBackSlash As Integer, iPoint As Integer
Dim sFilePath As String, sFileName As String
Dim i As Integer

sFilePath = ActieWorkbook . FullName


For i = Len(sFilePath) To 1 Step -1
If Mids (sFilePath, i , 1) =” .” Then
i Point = i
Exist For
End If
Next i
If iPoint = 0 Then iPoint = Len (sFilePath) + 1
For i = iPoint - 1 To 1 Step -1
If Mids (sFilePath, i , 1) =”\” Then
iBackSlash = i
Exist For
End If
Next i
sFileName = Mids (sFilePath, iBackSlash + 1 , iPoint - iBackSlash - 1 )
MsgBox sFileName
End Sub

Example of For Each Next (Write a program to display footer)


Sub FilePathInFooter()
Dim sFilePath As String, wks As Worksheet

sFilePath = ActiveWorkbook. FullName


For Each wks In Worksheets
Wks . PageSetup . CenterFooter = sFilePath
Next wks
End Sub

Saroj Kumar Shrama 2


Excel VBA

The below example uses to display the names of all the files in the directory
Sub FileList()
‘Listing files with a for … Each loop

Dim objFSO As Object


Dim ObjFolder As Object
Dim ObjFile As Object
‘Create a reference to the FileSystemObject
Set objFSO = CreatObject (“Scripting . FileSystemObject”)

‘Create a folder reference


Set objFolder = objFSO . GetFolder (“c:\”)

‘List files in folder


For Each objFile In objFolder . Files
MsgBox objFile . Name
Next objFile
End Sub

Saroj Kumar Shrama 3


Excel VBA

Array Example

WAP to store the value in specified array and find out count , sum of that array
Sub Array1()
Dim aiData(10) As Integer
Dim sMessage As String, i As Integer

For i =LBound(aiData) To UBound(aiData)


aiData(i) = i
Next i
sMessage = “Lower Bound = “& LBound(aiData) & vbcr
sMessage =sMessage & “Upper Bound = “ & UBound(aiData) & vbcr
sMessage =sMessage & “Num Element = “ & WorksheetFunction . Count (aiData) & vbcr
sMessage = sMessage & “Sum Element = “ & WorksheetFunction . Sum (aiData )
MsgBox sMessage
End Sub

‘ The below program will help you to open multiple worksheet and process a series of workbooks.
Sub Array2()
Dim avData As Varient , wkb As Workbook
Dim i As Integer

avData = Array(“North”, “South”, “East”, “West”,)


For i = LBound(avData) To UBound(avData)
Set wkb = Workbooks. Open(Filename:=avData(i) & “.xls”)
,Process data here
Wkb . close SaveChanges:=True
Next i
End Sub

Example of Multiple dimensional array


Sub Array3()
Dim avData As Variant , vUBound As Variant
Dim Message As String , i As Integer

avData = Range (“A1 : A20” ) . Value


i = 1
Do
Message = “Lower Bound = “ & LBound(avData, i) & vbcr
Message = Message & “Upper Bound = “ &UBound(avData, i) & vbcr
MsgBox Message, , “Index Number = “ & i
i = i + 1
On Error Resume Next
vUBound = UBound(avData, i)
If Err. Number <> 0 Then Exist Do
On Error GoTo 0
Loop
Message = “Number of Non Blank Element =” _
& WorksheetFunction. CountA(avData) & vbcr
MsgBox Message
End Sub

Saroj Kumar Shrama 4


Excel VBA

Example of Dynamic Arrays


Sub FileName()
Dim sFName As String
Dim asFName() As String
Dim sFType As String
Dim i As Integer

sFType = “ * .xls “
sFName = Dir (sFType )
Do Until sFName = “ “
i = i +1
ReDim Preserve asFNames (1 To i )
asFNames(i) =sFName
sFName =Dir
Loop
If i = 0 Then
MsgBox “No Files Found”
Else
For i = 1 To UBound (asFNames)
MsgBox asFName (i)
Next i
End If
End Sub

Saroj Kumar Shrama 5


Excel VBA

Error Handling Program

On Error GoTo LineLabel

Sub ErrorTrap1()
Dim 1Answer As Long, sMyFile As String
Dim sMessage As String , sCurrentPath As String

On Error GoTo errTrap


sCurrentPath = CurDir$

ChDrive “A “
ChDrivesCurrentPath
ChDir sCurrentPath
sMyFile = “A:\Data . xls”
Application. DisplayAlerts =False
ActiveWorkbook . SaveAs Filename: = sMyFile
TidyUp:
ChDrive sCurrentPath
ChDir sCurrentPath
Exist Sub
errTrap:
sMessage = “Error No: = “ & Err . Number & vbcr
sMessage = sMessage & Err .Description & vbcr & vbcr
sMessage = sMessage & “Please Place a disk in the A: drive” & vbcr
sMessage = sMessage & “and Press Ok” & vbcr & vbcr
sMessage = sMessage & “Or Press Cancel to abort File Save”

1Answer= MsgBox (sMessage, vbQuestion + vbOkCancel, “Error”)


If 1Answer = vbCancel Then Resume TidyUp
Resume
End Sub

About Resume Statement


Resume causes execution of the statement that caused the error
Resume Next returns execution to the statement following the statement that caused the error, so
the problem statement is skipped
Sub ErrorTrap2()
Dim sMyFile As String, sMessage As String
Dim sAnswer As String

On Error GoTo errTrap


Workbooks . Add
sMyFile = “C:\Data. Xls”
Kill sMyFile
ActiveWorkbook. SaveAs Filename:=sMyFile
ActiveWorkbook . Close
Exist Sub
errTrap:
sMessage = “Error No: = “ & Err .Number & vbcr
sMessage = sMessage & Err .Description & vbcr & vbcr

Saroj Kumar Shrama 6


Excel VBA

sMessage sMessage & “File does not exist”


sAnswer = MsgBox (sMessage, vbInformation , “Error” )
Resume Next
End Sub

On Error Resume Next: This statement causes errors to be ignored, so it should be used with
caustion.
On Error Goto 0 : is used to turn on normal VBA Error handling again. Otherwise, any further errors
would be ignored.

Sub ErrorTrap3()
Dim sMyFile As string

Workbooks . Add
sMyFile = “C:\Data . xls”
On Error Resume Next
Kill sMyFile
On Error GoTo 0
ActiveWorkbook . SaveAs Filename:=sMyFile
ActiveWorkbook . Close
End Sub

Sub TestForName()
If bNameExists (“SalesData”)Then
MsgBox “Name Exists”
Else
MsgBox “Name does not exist”
End If
End Sub
Function bNameExists (sMyName As String ) As Boolean
Dim sName As string
On Error Resume Next
sName = Names (sMyName) .RefersTo
If Err . Number <> 0 Then
bNameExists = False
Err . Clear
Else
bNameExists = True
End If
End Function

Saroj Kumar Shrama 7


Excel VBA

Important TIPS
Display Alerts: It can be annoying to have to respond to system alerts while a macro runs. For
example, if a macro delete a worksheet, an alert message appears and you have to click the OK
button to continue. However, there is also the possibility of a user clicking the Cancel button, which
would abort the delete operation.

Application.DisplayAlerts=False
Activesheet.Delete
Application.DisplayAlerts=True

Note: It is not necessary to reset DisplayAlerts to True at the end of your macro because VBA does
this automatically. However, it is usually a good idea after suppressing a particular message to run
the alerts back on so that any unexpected warnings do appear on screen.

Screen Updating: It is better to avoid selecting objects in VBA. It is seldom necessary to do this and
your code will run faster if you can avoid selecting or activating objects.

Application.ScreenUpdating=False

Inputbox: VBA has inputbox function that provides an easy way to prompt for input data.

Saroj Kumar Shrama 8


Excel VBA

Working with Range

Example: To select a range specified by user

Sub GetRange()
Dim rng as Range
On Error Resume Next
Set rng=Application.Inputbox(“Prompt:=”Enter Range”,Type:=8)
If rng is nothing then
Msgbox “Operation Cancelled”
Else
Rng.select
End if
End Sub

Active Properties:

The application object provides many shortcuts that allow you to refer to active objects without
naming them explicity. This makes it possible to discover what is currently active when your macro
runs.

Activecell: to select current cell (cursor location in active sheet)


ActiveChart : To select the current chart selected in activesheet
ActivePrinter : To select the default printer
ActiveSheet : To select the default sheet
ActiveWindow: To select the current window
ActiveWorkbook : to select the current workbook. Example: Activeworkbook.Save

Selection: Selections.Font.Bold=True (Selected Range)

Statusbar: The status bar property allows you to assign a text string to be displayed at the left and
side of Excel Status bar at the bottom of the screen.

Private Sub Worksheet_SelectionChange(ByVal Target As Range)


Rows.Interior.ColorIndex = xlColorIndexNone
Target.EntireColumn.Interior.ColorIndex = 36
Target.EntireRow.Interior.ColorIndex = 15
End Sub

Saroj Kumar Shrama 9


Excel VBA

Write a program with declaration of variable or without declaration of variable

Code: create two Form button in excel spreadsheet as it has given in picture and assign
the macro to it.

Code with Dim Statement

Sub TimeTest1()
Dim x As Long, y As Long
Dim A As Double, B As Double, C As Double
Dim i As Long, j As Long
Dim StartTime As Date, EndTime As Date
' Store the starting time
StartTime = Timer
x = 0 ' Perform some calculations
y=0
For i = 1 To 5000
x=x+1
y=x+1
For j = 1 To 5000
A=x+y+i
B=y-x-i
C=x/y*i
Next j
Next i
' Get ending time
EndTime = Timer
' Display total time in seconds
MsgBox Format(EndTime - StartTime, "0.0")
End Sub

Code without variable declaration

Sub TimeTest2()
' Store the starting time
StartTime = Timer
' Perform some calculations
x=0
y=0
For i = 1 To 5000
x=x+1
y=x+1
For j = 1 To 5000
A=x+y+i
B=y-x-i
C=x/y*i
Next j
Next i
' Get ending time
EndTime = Timer
' Display total time in seconds
MsgBox Format(EndTime - StartTime, "0.0")
End Sub

Saroj Kumar Shrama 10


Excel VBA

Write a program to pint table of any number in excel spreadsheets

Sub printTable()
Dim i As Integer
Dim n As Integer
Dim s As String
s = "" ‘initilization of string variable
n = InputBox("Enter the number")
If IsNumeric(n) = False Then
Exit Sub
End If

For i = 1 To 10
s = n & "*" & i & "=" & n * i & vbCrLf
' MsgBox s
'
Range("A" & i).Value = s
Next
MsgBox s
'Range("A1").Value = s
End Sub

Write a program to hide and unhide sheets in a workbook

Solutions: Create a spreadsheets with name “Main” and copy the below program in
Module. Create two buttons with name “Hide All” and “Unhide All”.

Sub HideAll() ‘ Assign this program to “HideAll” button in the spreadsheets


Dim i As Integer
For i = 1 To Sheets.Count
If Sheets(i).Name <> "Main" Then
Sheets(i).Visible = False
End If
Next
End Sub

Sub ShowAll() ‘ Assign this program to “Unhide All” Button in the spreadsheets
Dim i As Integer
For i = 1 To Sheets.Count
If Sheets(i).Name <> "Main" Then
Sheets(i).Visible = True
End If
Next
End Sub

Write a program to find the duplicate and marked as Red color


Sub TestForDups()
Dim LLoop As Integer
Dim LTestLoop As Integer
Dim LClearRange As String
Dim Lrows As Integer
Dim LRange As String
Dim LChangedValue As String
Dim LTestValue As String
'Test first 200 rows in spreadsheet for uniqueness

Saroj Kumar Shrama 11


Excel VBA

Lrows = 200
LLoop = 2
'Clear all flags
LClearRange = "A2:A" & Lrows
Range(LClearRange).Interior.ColorIndex = xlNone

'Check first 200 rows in spreadsheet


While LLoop <= Lrows
LChangedValue = "A" & CStr(LLoop)
If Len(Range(LChangedValue).Value) > 0 Then
'Test each value for uniqueness
LTestLoop = 2
While LTestLoop <= Lrows
If LLoop <> LTestLoop Then
LTestValue = "A" & CStr(LTestLoop)
'Value has been duplicated in another cell
If Range(LChangedValue).Value = Range(LTestValue).Value Then
'Set the background color to red
Range(LChangedValue).Interior.ColorIndex = 3
Range(LTestValue).Interior.ColorIndex = 3
End If
End If
LTestLoop = LTestLoop + 1
Wend
End If
LLoop = LLoop + 1
Wend
End Sub

‘ Write a macro to check the workbook is opened or not

Sub IsWorkBookOpen()

'Test to see if a Workbook is open.


Dim wBook As Workbook
On Error Resume Next
set wBook = Workbooks("Personal.xls")
If wBook Is Nothing Then 'Not open
MsgBox "Workbook is not open", _
vbCritical,"TEST"
Set wBook = Nothing
On Error GoTo 0
Else 'It is open
MsgBox "Yes it is open", _
vbInformation,"tEST”
Set wBook = Nothing
On Error GoTo 0
End If
End Sub

Saroj Kumar Shrama 12


Excel VBA

Write a macro to check whether the file exists in folder or not


Sub DoesWorkBookExist()
'Test to see if a Workbook exists
Dim i As Integer
With Application.FileSearch
.LookIn = "C:\MyDocuments"
'* represents wildcard characters
.FileName = "Book*.xls"
If .Execute > 0 Then 'Workbook exists
MsgBox "There is a Workbook."
Else 'There is NOt a Workbook
MsgBox "The Workbook does not exist"
End If

End With

End Sub

Write a program to open all the files in a specified folder

Sub OpenAllWorkbooksInFolder()

Dim i As Integer
With Application.FileSearch
.LookIn = "C:\OzGrid Dell"
'* represents wildcard characters
.FileType = msoFileTypeExcelWorkbooks
If .Execute > 0 Then 'Workbook exists
For i = 1 To .FoundFiles.Count
Workbooks.Open (.FoundFiles(i))
Next i
Else 'There is NOt a Workbook
MsgBox "The Workbook does not exist"
End If

End With
End Sub

Saroj Kumar Shrama 13


Excel VBA

Write a program to check whether the sheets exists in the activeworkbook

Sub DoesSheetExist()
Dim wSheet As Worksheet
On Error Resume Next
Set wSheet = Sheets("Sheet1")
If wSheet Is Nothing Then 'Doesn't exist
MsgBox "Worksheet does not exist", _
vbCritical," Rks.vba "
Set wSheet = Nothing
On Error GoTo 0
Else 'Does exist
MsgBox "Sheet 1 does exist", _
vbInformation,"Rks.vba"
Set wSheet = Nothing
On Error GoTo 0
End If
End Sub

Write a program to check whether the name exists in activeworkbook or not?


Sub DoesRangeExist()
Dim rRange As Range
On Error Resume Next
Set rRange = Range("MyRange")
If rRange Is Nothing Then 'Doesn't exist
MsgBox "The named range does not exist", _
vbCritical,"Rks.vba"
Set rRange = Nothing
On Error GoTo 0
Else 'Does exist
MsgBox "The named range does exist", _
vbInformation,"Rks.vba"
Set rRange = Nothing
On Error GoTo 0
End If
End Sub

How to hide the range in Autofilters

Sub IsCellVisible()

Dim bHidden as Boolean


With Sheet1
If .FilterMode = True Then
bHidden = .Range("A5").EntireRow.Hidden
MsgBox "Filters are on and A5 row hidden is " & bHidden
End If
End With
End Sub

Saroj Kumar Shrama 14


Excel VBA

Write a program to count the number of pages need to printed

Sub HowManyPagesBreaks()
Dim iHpBreaks As Integer, iVBreaks As Integer
Dim iTotPages As Integer
iHpBreaks = Sheet1.HPageBreaks.Count + 1
iVBreaks = sheet1.VPageBreaks.Count + 1
iTotPages = iHpBreaks * iVBreaks
MsgBox iTotPages
End Sub

Write a program to make sure that the files have been saved before close
Code:
Private Sub Workbook_BeforeClose(Cancel As Boolean)
If Not ThisWorkbook.Saved Then
IAnswer = MsgBox("Do you want to save your Changes", vbQuestion + vbYesNo)
If IAnswer = vbYes Then
ThisWorkbook.Save
MsgBox ThisWorkbook.Name & " has been Saved"
End If
End if
End Sub

Write a program to add new workbook


Sub NewWorkbook1()
Dim wkb As Workbook
Dim wks As Worksheet
Set wkb = Workbooks.Add
Set wks = wkb.Worksheets.Add(After:=wkb.Sheets(wkb.Sheets.Count))
wks.Name = "January"
wks.Range("A1").Value = "Sales Data"
wkb.SaveAs Filename:="JanSales.xls"
End Sub
Sub NewWorkbook()
Dim wks As Worksheet
With Workbooks.Add ' adding new workbook
Set wks = .Worksheets.Add(After:=.Sheets(.Sheets.Count))
wks.Name = "January"
wks.Range("A1").Value = "Sales Data"
.SaveAs Filename:="JanSales.xls"
End With
End Sub

Saroj Kumar Shrama 15


Excel VBA

Write a program to find the lastrow in a Defined column


Sub test()
Lrow = Range("A6500").End(xlUp).Row ' to find the last row in column A from down
Lrow = Range("A1:A65000").End(xlDown).Row ' to find the last row in column A from top
Lrow = ActiveSheet.UsedRange.Rows.Count
Lrow = Sheet1.UsedRange.Rows.Count
Lrow = Workbooks(WB1).Sheets(SH1).Range("A65000").End(xlUp).Row
MsgBox Lrow
End Sub
Function LastRowInColumn(intCol As Integer) As Integer
On Error GoTo LRICError
Application.Volatile 'This will make sure that this function is called if anything is changed
on the Worksheet
LastRowInColumn = Cells(Rows.Count, intCol).End(xlUp).Row
ExitFnxn:
Exit Function
LRICError:
LastRowInColumn = CVErr(xlErrNA)
Resume ExitFnxn
End Function

How to select range through Inputbox?


Sub GetRange()
Dim rng as range
On Error resume next
Set rng=Application.inputbox(Prompt:=”Enter Range”,Type:=8)
If rng is Nothing then
Msgbox “Operation Cancelled”
Else
Rng.select
End if
End sub

Function sGetFilename(sFullname As String) As String


' sGetfilename returns the file name, such as cash.xls from the end of a full path
' sFullname is returned if no Path Separator is found
Dim sPathSeparator As String
Dim iFlength As String ' Path separator character
Dim i As Integer
sPathSeprator = Application.PathSeparator
iFlength = Len(sFullname)
' find the last path separator if any

For i = iFlength To 1 Step -1


If Mid(sFullname, i, 1) = sPathSeparator Then Exit For

Next i
sGetFilename = Right(sFullname, iFlength - 1)
End Function

Saroj Kumar Shrama 16


Excel VBA

Function bIsWorkbookopen(wkbname As String) As Boolean


' this function returns True if wkbname is a member of the workbooks collection.
Dim wkb As Workbook

On Error Resume Next


Set wkb = Workbooks(wkbname)
If Not wkb Is Nothing Then
bIsWorkbookopen = True
End If
End Function

Sub InsertChartsBeforeWorksheets()
' Insert Charts before worksheets
Dim wks As Worksheet
For Each wks In Worksheets

Charts.Add Before:=Sheets(wks.Index)

Next wks
End Sub

Sub InsertChartsAfterWorksheets()
' Insert Charts before worksheets
Dim wks As Worksheet
Dim cht As Chart
For Each wks In Worksheets

Set cht = Charts.Add


cht.Move after:=wks
'Charts.Add Before:=Sheets(wks.Index)

Next wks
End Sub

Saroj Kumar Shrama 17


Excel VBA

How to find last row and last column in worksheet


Dim LastRow as Integer, LastColumn as Integer
Options1:
Comment: Start from A1 and look at the first empty row occurance downwards
Command: LastRow=SheetName.Cells(1,1).End(xlDown).row
LastRow=SheetName.Range(“A1”).End(xlDown).Row
Options2:
Comment: Start from A65000 and look at the first empty row occurance upwards
LastRow = SheetName.Cells(65000,1).End(xlUp).Row
LastRow=SheetName.Range(“A65000”).End(xlUp).Row
Option3:
Comment: How to pick from last column
LastColumn = SheetName.Cells(1,1).End(xlToRight).Column
LastColumn=SheetName.Range(“A1”).End(XltoRight).column

How to clear the clipboard after a copy/paste operation?


Application.CutCopyMode=False

Why am I not able to copy a range?


SourceSheetName.Activate
SourchSheetName.Range(“A1:H50”).copy
TargetSheetName.Activate
TargetSheetName.Range(“B1:I50”).PasteSpecial xlPasteValues

How to Select a Range and Cells


Range(“A2”).Activate: To Activate the Range A2
Range(“A1:A10”).select ‘ Select a range
Cells(1,2).select ‘ select a cell
Cells.select: To select complete cell in the activesheet
Cells.EntireColumn.AutoFit : To fit the complete column

How to clear Range or cells


Range(“A1:A10”).Clear
Cells(1,2).clear
Cells.select: To select complete cell in the activesheet
Cells.EntireColumn.AutoFit : To fit the complete column

How to show all records


Sub ShowAllRecords()
' the below code will show you all the records if the filter has been applied
If ActiveSheet.FilterMode Then
ActiveSheet.ShowAllData
End If
End Sub

Sub TurnAutoFilterOn()
' check for filter, turn if none exists
If Not ActiveSheet.AutoFilterMode Then
ActiveSheet.Range("A1").AutoFilter
End If
End Sub

Saroj Kumar Shrama 18


Excel VBA

Sub TurnAutoFilterOff()
' check for filter, turn if none exists
ActiveSheet.AutoFilterMode = False
'or
Worksheets("SheetName").AutoFilterMode = False
End Sub

Sub HideArrows()
'hides all arrows except column 2
'Perhaps you want users to filter only one of the columns in a table. The following Excel AutoFilter
VBA procedure hides the arrows for all columns except column 2.
Dim c As Range
Dim i As Integer
i = Cells(1, 1).End(xlToRight).Column
Application.ScreenUpdating = False

For Each c In Range(Cells(1, 1), Cells(1, i))


If c.Column <> 2 Then
c.AutoFilter Field:=c.Column, _
Visibledropdown:=False
End If
Next
Application.ScreenUpdating = True
End Sub

Sub HideSpecifiedArrows()
'hides arrows in specified columns
'In other cases, you might want to hide the arrows on specific columns, and leave all the other arrows
visible. The following procedure hides the arrows for columns 1, 3 and 4.
Dim c As Range
Dim i As Integer
i = Cells(1, 1).End(xlToRight).Column
Application.ScreenUpdating = False
For Each c In Range(Cells(1, 1), Cells(1, i))
Select Case c.Column
Case 1, 3, 4
c.AutoFilter Field:=c.Column, _
Visibledropdown:=False
Case Else
c.AutoFilter Field:=c.Column, _
Visibledropdown:=True
End Select
Next
Application.ScreenUpdating = True
End Sub

Saroj Kumar Shrama 19


Excel VBA

Sub ShowArrows()
'To show all the arrows, you can use the following Excel AutoFilter VBA code:
Dim c As Range
Dim i As Integer
i = Cells(1, 1).End(xlToRight).Column
Application.ScreenUpdating = False
For Each c In Range(Cells(1, 1), Cells(1, i))
c.AutoFilter Field:=c.Column, _
Visibledropdown:=True
Next
Application.ScreenUpdating = True
End Sub

Sub HideArrowsRange()
'If your table doesn't start in cell A1, you can specify the heading range, and hide arrows in
specific cells in that range.
'hides arrows in specified range
Dim c As Range
Dim i As Integer
Dim rng As Range
Set rng = Range("D14:J14")
i = rng.Cells(1, 1).Column - 1
Application.ScreenUpdating = False
For Each c In Range("D14:J14")
Select Case c.Address
Case "$E$14", "$G$14", "$J$14"
c.AutoFilter Field:=c.Column - i, _
Visibledropdown:=False
Case Else
c.AutoFilter Field:=c.Column - i, _
Visibledropdown:=True
End Select
Next
Application.ScreenUpdating = True
End Sub

Sub ShowArrowsRange()
'If your table doesn't start in cell A1, you can specify the heading range, and show all the arrows in that
range.
'shows arrows in specified range
Dim c As Range
Dim i As Integer
Dim rng As Range
Set rng = Range("D14:J14")
i = rng.Cells(1, 1).Column - 1
Application.ScreenUpdating = False
For Each c In Range("D14:J14")
c.AutoFilter Field:=c.Column - i, _
Visibledropdown:=True
Next
Application.ScreenUpdating = True
End Sub

Saroj Kumar Shrama 20


Excel VBA

How to Save Activeworkbook?


ActiveWorkbook.save

How to work with Selection and Activate ?


Selection: Selection is the keyword which refers multiple cells or Range
ActiveCell: ActiveCell Refers only one cell
Range(“A1:A10”).select
Range(“A1”).Activate
How to work with Range?
Application.Range(“B2”) .Select= Range Property of the Application object to refer to a Range
object on the active worksheet.
Range(“A1:D10”).Select = Refer to SingOffsetle block of cells on the active worksheet
Range(“A1:A10,C1:C10,E1:E10”): Refer to non-Contiguous range of cells
Range(“A1”,”D10”) : Alternative way to refer to the range A1:D10
Range(“SalesData”) : Defined a range of cells with the name SalesData , we can use the name
as argument.

Saroj Kumar Shrama 21

Das könnte Ihnen auch gefallen