Presentation is loading. Please wait.

Presentation is loading. Please wait.

Visual Basic for Applications in Microsoft Excel (1)

Similar presentations


Presentation on theme: "Visual Basic for Applications in Microsoft Excel (1)"— Presentation transcript:

1 Visual Basic for Applications in Microsoft Excel (1)
Week 10

2 Week 10 Protecting Code Protecting Worksheets Error Handling Charts

3 Last Week Using form tools Changing the QAT Revision Exercises

4 Data Input Form - Example
Run the Add Customer form from the button on the Data Sheet Features: Auto number Customer ID Accommodates other ranges in the worksheet Design Issues: Uses Named Range to place details on the sheet Code attached to Initialize event generates an autonumber The text box’s Enabled property is set to False to disallow editing Need to update the named range after input some data below the named range which we don’t want to overwrite

5 Protecting VBA projects
Locking the project for viewing means that the macros will still run but that users will need a password to access the code in the editor. Close the file and reopen it. To access the code of a protected project, from the Project Window, double click on the appropriate project and enter the password at the prompt. You can protect a VBA project just like you can protect an Excel worksheet or workbook. Open the Visual Basic Editor Right-click the Project (corresponding to a file) to be protected …… and choose VBAProject Properties Choose the Protection tab Make sure that Lock Project for viewing is turned on and type in a password (twice), then choose OK The code associated with this project can still be seen after you have done this. To make the password protection come into effect, Close the file, then re-open it With the project (i.e., the file) re-opened, go to the Visual Basic Editor and (from Project Explorer) double-click the icon for the password-protected project to view its contents

6 Protecting sheets You can password protect sheets using the Review tab in excel where you can specify the limits of the protection You can exclude selected cells from the protection by highlighting and using the protect cells tab of the format cells dialog

7 Protecting Sheets A line of code to protect the current sheet might look like this. ActiveSheet.Protect "password" True, True, True Where ActiveSheet is the object and Protect the method. Protect has many arguments. The first is the password string, followed by a series of True/False arguments resembling the tickbox list found in Excel. As with the Excel interface, by default most options are set to True (protected) whilst a few are false (unprotected) expression.Protect(Password, DrawingObjects, Contents, Scenarios, UserInterfaceOnly, AllowFormattingCells, AllowFormattingColumns, AllowFormattingRows, AllowInsertingColumns, AllowInsertingRows, AllowInsertingHyperlinks, AllowDeletingColumns, AllowDeletingRows, AllowSorting, AllowFiltering, AllowUsingPivotTables) Turn the macro Recorder on and call the macro sheet_protect Click the Review tab on the ribbon and click the Protect Sheet button In the Protect Sheet dialog, type the password (your first name) … and choose OK You will be asked to re-enter the password – do so and choose OK Stop the macro recording If you now unprotect the worksheet, you will be asked for the password However, run the sheet_protect macro. Then unprotect the sheet. This time you are not asked for the password. When the macro runs, it doesn't set a password! Choose the Macros option, select sheet_protect … and choose Edit

8 User input - Customising the Protect sheets macro
Instead of always protecting the active sheet, you might want the user to choose which sheet to unprotect Sub protect_choose() Dim mySheet As Worksheet Dim sheetName As String sheetName = InputBox("Please type Sheet name", "non-robust sheet selector", "sheet1") Set mySheet = Worksheets(sheetName) mySheet.protect “password" End Sub

9 Protecting all the sheets using for each
Adapt previous macro to protect each sheet in turn Sub ProtectSheets() Dim mySheet As Worksheet mySheet.Protect “password" End Sub Here in fact is the macro: Sub ProtectSheets() Dim mySheet As Worksheet For Each mySheet in Worksheets mySheet.Protect “earlgrey” Next mySheet End Sub

10 Error Handling If you try to run a sub to add a worksheet named “Results” where a worksheet named “Results” already exisits, Sub will stop running A message box containing an error code will appear Error handling seeks to write code that deals with the issue and moves on to the next line

11 Error handling Use On Error Resume Next to allow the macro to continue when an error is encountered. Use Err.Number to find out if there is an error or not. If the number property of the Err object is 0, then no error occurred. For example: If err.number <> 0 Then -- do something to cope with eventuality -- End if On Error Resume Next causes execution to continue with the statement immediately following the statement that caused the run-time error, or with the statement immediately following the most recent call out of the procedure containing the On Error Resume Next statement. This statement allows execution to continue despite a run-time error. You can place the error-handling routine where the error would occur, rather than transferring control to another location within the procedure. An On Error Resume Next statement becomes inactive when another procedure is called, so you should execute an On Error Resume Next statement in each called routine if you want inline error handling within that routine.

12 Testing to see if worksheet exists
Function SheetExists This function uses the Err object to see if an error occurs when a sheet is referenced, i.e. it doesn’t exist. If an error occurs, then the Resume command clears the error and allows the program to continue. Can be used within another sub to check for a sheet name before trying to use the name for another sheet The next program, which you can find module2 in week10.xls, goes one better, and will insert a new worksheet and name it ReportX, where X is an integer such that if there already is a worksheet called Report1, the new worksheet will have the name Report2, and so on. Naturally you can use any prefix other than 'Report' by amending the code The trick the code employs is to generate an automatic name for the new sheet – if the name already exists, there is an error. The code clears the error (by setting the Err.Number property to zero) and tries again until success is achieved.

13 Sub make_report() Dim mysheet As Worksheet Dim myBase As String Dim mySuffix As Integer Set mysheet = Worksheets.Add myBase = "Report" mySuffix = 1 On Error Resume Next mysheet.Name = myBase & mySuffix Do Until Err.Number = Err.Number = mySuffix = mySuffix mysheet.Name = myBase & mySuffix Loop End Sub

14 Charts Record a macro to create a chart (start with a simple column chart) in a new sheet for the exam results on the exams sheet Good example of instance where recorded code and reference to the object map can help

15 Charts Sub MakeChart() Selection.CurrentRegion.Select Charts.Add
Selection.CurrentRegion.Select Charts.Add ActiveChart.ChartType = xlColumnClustered ActiveChart.SetSourceData Source:=Sheets("Exams").Range("A1:B10")_ , PlotBy:= xlColumns ActiveChart.Location Where:=xlLocationAsObject, Name:="Exams" With ActiveChart .HasTitle = True .ChartTitle.Characters.Text = "Exam Marks" .Axes(xlCategory, xlPrimary).HasTitle = False .Axes(xlValue, xlPrimary).HasTitle = False End With ActiveChart.HasLegend = False End Sub

16 Charts Adapt your code to produce a pie chart Rename the chart
Label the axis Allow the user to select the range of the chart data

17 Some final points on using the VBA editor
Module level variables Use module level variables only when two or more subs need access to the same variable; otherwise it’s better practice to use variables local to the procedure they are in. To declare a module level variable, you declare it in the Declarations section (where the Option statements are), before any subs. You can use Dim as previously, but it is recommended you use the keywords Private or Public to determine the scope of the variable. Private variables are accessible only to the subs in the same module, Public variables are accessible to all the subs in the workbook.

18 Boats Example An example of a longer application
Uses Module level variables Has three main Subs which call on combinations or smaller subs Uses Workbook_Open event handler to reset workbook

19 Good Luck in your future VBA endeavors


Download ppt "Visual Basic for Applications in Microsoft Excel (1)"

Similar presentations


Ads by Google