1. Trang chủ
  2. » Giáo án - Bài giảng

Excel vba step by step guide to learn excel vba programming with screenshots and example code by mel

99 30 1

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Nội dung

EXCEL VBA Legal Notice Copyright (c) 2020 Anton Melnyk All rights are reserved No portion of this book may be reproduced or duplicated using any form whether mechanical, electronic, or otherwise No portion of this book may be transmitted, stored in a retrieval database, or otherwise made available in any manner whether public or private unless specific permission is granted by the publisher This book does not offer advice, but merely provides information The author offers no advice whether medical, financial, legal, or otherwise, nor does the author encourage any person to pursue any specific course of action discussed in this book This book is not a substitute for professional advice The reader accepts complete and sole responsibility for the manner in which this book and its contents are used The publisher and the author will not be held liable for any damages caused Excel VBA Step by Step Guide to Learn Excel VBA Programming with Screenshots and Example Code Anton Melnyk Contents Working with the Visual Basic Editor Objects in Visual Basic for Application Subs and Functions in Visual Basic for Application Macro Recorder tool in Visual Basic for Application Important Language Elements in Visual Basic for Application Range objects in Visual Basic for Application Workbook objects in Visual Basic for Application Worksheet objects in Visual Basic for Application OLEObject objects in Visual Basic for Application Worksheet Functions in Visual Basic for Application Control Program Flow and Making Decisions in Visual Basic for Application Events in Visual Basic for Application Error Handling in Visual Basic for Application Communication with users in Visual Basic for Application Add-ins in Visual Basic for Application Tips and Tricks used in Visual Basic for Application Code examples used in Visual Basic for Application Excel VBA VBA stands for Visual Basic for Applications and is the programming language used in all office programs (Excel, Word, Outlook, etc.) This programming language can be used to create all kinds of automation tools and to create relationships between Office programs move data from one tool to another This book will show you how you can harness some of the power of Excel VBA for yourself Working with the Visual Basic Editor Visual Basic Editor is the interface where the code can be written To open Visual Basic Editor, you need to follow this steps: Click on the Developer tab from the top ribbon menu of any Outlook program If the Developer tab is not visible you have to right click on Home button and click on Customize Quick Access Toolbar Select Customize Ribbon option on the left pane and check Developer checkbox in the right pane Click on the Visual Basic button OR Press Alt + F11 buttons from the keyboard on Windows configuration or Opt + F11 buttons from the keyboard on MAC configuration After the Visual Basic Editor is open there can be found multiple sections described below: Menu Bar Menu Bar is the main menu of the Visual Basic Editor From the Menu Bar you can save your project use functions as find or replace select what windows to be visible (Immediate Window, Immediate Window, Watches Window, etc.) insert modules, procedures or user forms format your code (align, horizontal or vertical spacing, arrange buttons, etc.) debug your code by: step into (run the code line by line), step over (skip some lines of code when running), add a variable to the watch window (check the variable value while running the code) run the code, break the code or stop the code add some references References are very important when the code uses some other applications For example, if you want to include some Word references you need to add Microsoft Word as a reference include some Add-ins change Window view get some help if is needed All the commands described above have also keyboard shortcuts Tool Bar Tool Bar contains most of the useful commands that are used while codding This toolbar can be customized with most needed commands Edit Toolbar Buttons: List Properties / Methods (CTRL + J) – When something from the code (Sub, Function, Variable, Method, etc.) is clicked and .DisplayAlerts = False AskToUpdateLinks = False End With ‘Rest of the code here 'Improving speed code With Application Calculation = xlCalculationAutomatic ScreenUpdating = True DisplayStatusBar = True EnableEvents = True DisplayAlerts = True AskToUpdateLinks = True End With -this helps a lot in some bigger macros which loops through arrays or sheets, copy paste values, opens another Office tool, etc ➢ Remove unnecessary redundant lines of code from the macro (example multiple select statements when using ranges of cells) Reduce the number of steps that can be done in the code to execute the same functionality Replace this : ThisWorkbook.Sheets(1).Select Columns(“A:B”).Select Selection.ClearContents With this: ThisWorkbook.Sheets(1).Columns(“A:B”).ClearContents ➢ Use With statements when using the same object for multiple actions (example changing some properties for a range of cells, value, font, color, etc.) Replace this: Range(“A1”).Value = “Text Is Here” Range(“A1”).BackgroundColor = RGB (255,0,0) Range(“A1”).Font.Bold = True Range(“A1”).Font.Name = “Calibri” With this: With Range(“A1”) Value = “Text Is Here” BackgroundColor = RGB (255,0,0) With Font Bold = True Name = “Calibri” End With End With ➢ Try to use arrays in the code instead of range of cells When looping through range of cells is much better to loop through array of values that contains values from the range Assign all the values from a sheet tot an array and use that array for operations and copy values back into the excel cells at the end Dim sheetValues as Variant Dim i, j as Long sheetValues = Sheet(1).Range(“A1:W1000”) For i = LBound(sheetValues, 1) To UBound(sheetValues, 1) For j = LBound(sheetValues, 2) To UBound(sheetValues, 2) ‘Make operations that are needed on the cells on the array Next j Next i Sheet(1).Range(“A1:W1000”)= sheetValues ➢ Use Value2 instead of Value and Text when obtaining values from one or multiple cells Check the difference between them below: Text is commonly used to retrieve the value of a cell – it returns the formatted value of a cell Getting the formatting of a cell is more complex than just retrieving a value, and makes this option quite slow .Value is an improvement over Text, as this mostly gets the value from the cell, without formatting However, for cells formatted as a date or currency, Value will return a VBA date or VBA currency (which may truncate decimal places) Value2 returns the underlying value of the cell As it involves no formatting, Value2 is faster than Value This is faster than Value when processing numbers (there is no significant difference with text) and is much faster using a variant array ➢ Clean up the clipboard after each copy – paste operation or/and bypass the clipboard and use the internal operations Range(“A1”).Copy Range(“B1”).Paste Application.CutCopyMode = False Or use: Range(“B1”).Value2 = Range(“A1”).Value2 ➢ ➢ Use Option Explicit as a first line in the code to catch all the undeclared variables in the code This helps because all undeclared variables will be assigned to Variant type (16 bytes of memory) instead of using Byte (1 byte of memory), Long (4 bytes of memory) or String (10 bytes of memory) Display only one sub or procedure at a time Usually the Code window in the Visual Basic Editor shows all the procedures in the module, one after another This can be edited by set things up so that only one procedure is visible at a time: Activate the VBE and choose Tools Options Click the Editor tab in the Options dialog box Remove the check mark from the Default to Full Module View check box From the drop-down lists at the top of the module window it can be selected the procedure to view or edit ➢ Reduce the size of an existing workbook In many cases the size of existing workbook can be reduced (ex the workbooks with modules that were edited multiple times) Save the workbook Select a module or a UserForm in the Project Window Right-click and choose Remove from the shortcut menu A pop-up will be displayed Press Yes to export the module Repeat Steps and for each module and UserForm, keeping track of the modules and forms that were removed Choose File -> Import File to import all the modules and forms that were previously deleted Save the workbook again This solution reduces the size of the specified workbook and keep the entire functionality untouched Another way of reducing the size of a workbook file is: Activate the workbook Choose File -> Save As From the type dropdown select Web Page (*.htm, *.html) option Close the workbook Use File -> Open to open the HTML file that was saved in Step Use File -> Save As and resave the workbook as a standard XLS file In most cases the size of the workbook will be reduced ➢ Break the big code into some smaller pieces When developing a big piece of code try to break the code into smaller pieces (subs and functions) which can also be used multiple times in different places When breaking into smaller pieces there are three main benefits : Reusability of the code (use the same function in different places by using good parameter definition), Testability (it will be easier to test smaller pieces of the code and debugging it if there are errors) and Maintainability (it will be easier to maintain the code and improve it if there are smaller pieces and it should be enough to modify a function only once and will be applied for each call) Code examples used in Visual Basic for Application In this section are some examples of commented code that can be used in VBA for some general tasks ➢ Copy – Paste a range of cells from one sheet to another (including formatting) Sub CopyPasteRange() 'Copy and Paste a range of cells Sheets("Sheet2").Range("L9:N16").Copy Sheets("Sheet3").Range("L9:N16") 'Clean up the clipboard content Application.CutCopyMode = False End Sub ➢ Unhide all worksheets from the workbook Sub UnhideWorksheets() Dim sht As Worksheet For Each sht In ActiveWorkbook.Worksheets sht.Visible = xlSheetVisible Next sht End Sub ➢ Hide all worksheets from the workbook excepting the active sheet Sub HideAllSheetsExceptActive() Dim sht As Worksheet For Each sht In ThisWorkbook.Worksheets If sht.Name ActiveSheet.Name Then sht.Visible = xlSheetHidden End If Next sht End Sub ➢ Display all worksheets names in a message Sub DisplayWorksheetsName() Dim sht As Worksheet Dim shtNames As String 'initialize the shtName variable with a predifined text 'good looking purpose shtNames = "Name of all worksheets : " For Each sht In Worksheets 'Keep the existing value of shtNames variable 'and add the new sheet name to it shtNames = shtNames & " " & sht.Name Next sht 'Display all sheets names MsgBox shtNames End Sub ➢ Create a draft email and attach a file to it Sub PrepareOutlookEmail() Dim OutApp As Object 'Declare outlook application object Dim OutMail As Object 'Declare outlook mail object Set OutApp = CreateObject("Outlook.Application") Set OutMail = OutApp.CreateItem(0) 'Using OutMail it can be accessed mail properties With OutMail to = "mail_address@domain.com" CC = "mail_addressCC@domain.com" Subject = "This text will be the Subject of the mail" Body = "This text will be the Body of the mail" '.Attachments.Add 'Add here the location of the file that needs to be attached .Display 'Use display to only display the mail '.Send 'Use send to send the mail without displaying it End With Set OutMail = Nothing 'Clean up the memory by clearing the variables Set OutApp = Nothing 'Clean up the memory by clearing the variables End Sub ➢ Delete all blank rows from a worksheet Sub DeleteAllBlankRows() Dim sht As Worksheet Dim i As Long Dim lastRow As Long 'Set sht as the active sheet Set sht = ActiveSheet 'Get the last used row from the sheet 'same as Ctrl + Shift + End keyboard commands lastRow = sht.Cells(sht.Rows.Count, "A").End(xlUp).Row With sht 'Loop through rows from the last one to the first one 'This is the only way because when a row is deleted 'the last row sill also be modified For i = lastRow To Step -1 'Use worksheet function to check if the row is empty If WorksheetFunction.CountA(.Rows(i)) = Then sht.Rows(i).Delete End If Next End With End Sub ➢ Set Auto Fit for all columns and rows from a worksheet Sub AutoFitColumnsAndRows() Dim sht As Worksheet 'Set sht as the active s Set sht = ActiveSheet With sht.Cells Select EntireColumn.AutoFit EntireRow.AutoFit End With End Sub ➢ Highlight duplicate cells in a worksheet Sub HighlightDuplicateCellValues() Dim myRange As Range Dim myCell As Range Dim sht As Worksheet 'Set sht as the active s Set sht = ActiveSheet 'Select only the used range from the sheet sht.UsedRange.Select Set myRange = Selection 'Loop through all cells from the For Each myCell In myRange If WorksheetFunction.CountIf(myRange, myCell.Value) > Then 'Set the background color for the cell to yellow 'The index can be changed to another color myCell.Interior.ColorIndex = 36 End If Next myCell End Sub ➢ Check all cells for misspelled words and highlight them Sub HighlightMisspelledCells() Dim rng As Range Dim sht As Worksheet 'Set sht as the active s Set sht = ActiveSheet For Each rng In sht.UsedRange 'Use checkspelling function to check the text If Not Application.CheckSpelling(word:=rng.Text) Then 'If there is a misspelling error the cell will be highlighted with red rng.Style = "Bad" End If Next rng End Sub ➢ Delete all blank worksheets from the specified workbook Sub ClearAllBlankSheets() Dim sht As Worksheet On Error Resume Next 'Disable screen updating and display of alerts With Application ScreenUpdating = False DisplayAlerts = False End With 'Loop through each sheet of the workbook For Each sht In Application.Worksheets 'check if there is no used range in the sheet - blank sheet If Application.WorksheetFunction.CountA(sht.UsedRange) = Then sht.Delete End If Next 'Enable screen updating and display of alerts With Application ScreenUpdating = True DisplayAlerts = True End With End Sub ➢ Save all the existing worksheets to PDF format in a specified location Sub SaveAllSheetsAsPDF() Dim sht As Worksheet Dim location As String 'get the workbook location 'this location can be changed to any folder location location = ThisWorkbook.Path For Each sht In Worksheets sht.ExportAsFixedFormat xlTypePDF, location & "\" & sht.Name & ".pdf" Next sht End Sub ➢ Code to convert all cells value to lower/upper case Sub ConvertTextUpperLowerCase() Dim Rng As Range Dim sht As Worksheet 'Set sht as the active s Set sht = ActiveSheet 'Select only the used range from the sheet sht.UsedRange.Select 'Loop through each cell in the specified range For Each Rng In Selection 'If the cell contains text then convert If Application.WorksheetFunction.IsText(Rng) Then 'Use this line to convert text to Upper Case Rng.Value = UCase(Rng) 'Use this line to convert text to Lower Case 'Rng.Value = LCase(Rng) End If Next End Sub ➢ Code to be added to calculate the execution of your macro Sub CalculateHowManySeconds() Dim StartTime As Double Dim SecondsElapsed As Double Dim i As Long 'Remember time when macro starts StartTime = Timer 'Add here your code For i = To 10000000 Next i 'Determine how many seconds code took to run SecondsElapsed = Round(Timer - StartTime, 2) 'Notify user in seconds MsgBox "This code ran successfully in " & SecondsElapsed & " seconds", _ vbInformation End Sub ➢ Hello World sub ☺ Sub HelloWorld() MsgBox "Hello World ! I know Basic VBA stuff" End Sub EXCEL VBA Legal Notice Copyright (c) 2020 Anton Melnyk All rights are reserved No portion of this book may be reproduced or duplicated using any form whether mechanical, electronic, or otherwise No portion of this book may be transmitted, stored in a retrieval database, or otherwise made available in any manner whether public or private unless specific permission is granted by the publisher This book does not offer advice, but merely provides information The author offers no advice whether medical, financial, legal, or otherwise, nor does the author encourage any person to pursue any specific course of action discussed in this book This book is not a substitute for professional advice The reader accepts complete and sole responsibility for the manner in which this book and its contents are used The publisher and the author will not be held liable for any damages caused Excel VBA Step by Step Guide to Learn Excel VBA Programming with Screenshots and Example Code Anton Melnyk Excel VBA Thank you for reading I encourage you to share your thoughts with me on Amazon by writing an honest review I personally read each one, and your feedback is helpful and encouraging to me as I continue my mission to make programming understandable and accessible to everyone Anton Melnyk

Ngày đăng: 17/11/2023, 16:55

TÀI LIỆU CÙNG NGƯỜI DÙNG

TÀI LIỆU LIÊN QUAN