Beruflich Dokumente
Kultur Dokumente
Program to practice
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
Sub GetFileName()
Dim iBackSlash As Integer, iPoint As Integer
Dim sFilePath As String, sFileName As String
Dim i As Integer
The below example uses to display the names of all the files in the directory
Sub FileList()
‘Listing files with a for … Each loop
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
‘ 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
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
Sub ErrorTrap1()
Dim 1Answer As Long, sMyFile As String
Dim sMessage As String , sCurrentPath As String
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”
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
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.
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.
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.
Code: create two Form button in excel spreadsheet as it has given in picture and assign
the macro to it.
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
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
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
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 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
Lrows = 200
LLoop = 2
'Clear all flags
LClearRange = "A2:A" & Lrows
Range(LClearRange).Interior.ColorIndex = xlNone
Sub IsWorkBookOpen()
End With
End Sub
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
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
Sub IsCellVisible()
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
Next i
sGetFilename = Right(sFullname, iFlength - 1)
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
Next wks
End Sub
Sub TurnAutoFilterOn()
' check for filter, turn if none exists
If Not ActiveSheet.AutoFilterMode Then
ActiveSheet.Range("A1").AutoFilter
End If
End Sub
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
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
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