data entry tips

26
Data Entry Tips Daca selectati un range de celule inainte de a introduce datele, puteti apasa Enter pentru a termina de scris intr-o celula si a te muta in urmatoarea celula din range. De asemenea, folositi Shift+Enter ca sa va mutati mai sus, Tab ca sa va mutati spre dreapta si Shift+Tab ca sa va mutati spre stanga. Pentru a introduce aceeasi data in mai multe celule dintr-un range, selectati range-ul, scrieti informatia in celula activa si apoi apasati Ctrl+Enter. Pentru a copia continutul celului active in toate celelalte celule dintr-un range selectat, apasati F2 si apoi Ctrl+Enter. Pentru a completa un range cu increment al unei singure valori apasati CTRL in timp ce trageti de celula. Pentru a completa un range fara incrementare, trageti pur si simplu de celula respectiva sau apasati Ctrl+D pentru a copia in jos sau Ctrl+R pentru a copia la dreapta. Puteti introduce taburi si linii noi intr-o celula pentru a face textul mai usor de citit. Ca sa introduceti un tab, apasati Ctrl+Alt+Tab. Ca sa introduceti o linie noua, apasati Alt+Enter. Pentru a introduce o fractie, apasati 0, apoi un spatiu, apoi fractia folosind “/” (exemplu: 0 ¾). Apasati Ctrl+; pentru a insera data curenta si Ctrl+Shift+; pentru a introduce ora curenta intr-o celula. Pentru a seta o celula sau un range sa accepte numai un anumit tip de data, folositi Data Validation.

Upload: emacamara-1

Post on 14-Jul-2016

235 views

Category:

Documents


5 download

DESCRIPTION

excel

TRANSCRIPT

Page 1: Data Entry Tips

Data Entry Tips

Daca selectati un range de celule inainte de a introduce datele, puteti apasa Enter pentru a termina de scris intr-o celula si a te muta in urmatoarea celula din range. De asemenea, folositi Shift+Enter ca sa va mutati mai sus, Tab ca sa va mutati spre dreapta si Shift+Tab ca sa va mutati spre stanga.

Pentru a introduce aceeasi data in mai multe celule dintr-un range, selectati range-ul, scrieti informatia in celula activa si apoi apasati Ctrl+Enter.

Pentru a copia continutul celului active in toate celelalte celule dintr-un range selectat, apasati F2 si apoi Ctrl+Enter.

Pentru a completa un range cu increment al unei singure valori apasati CTRL in timp ce trageti de celula.

Pentru a completa un range fara incrementare, trageti pur si simplu de celula respectiva sau apasati Ctrl+D pentru a copia in jos sau Ctrl+R pentru a copia la dreapta.

Puteti introduce taburi si linii noi intr-o celula pentru a face textul mai usor de citit. Ca sa introduceti un tab, apasati Ctrl+Alt+Tab. Ca sa introduceti o linie noua, apasati Alt+Enter.

Pentru a introduce o fractie, apasati 0, apoi un spatiu, apoi fractia folosind “/” (exemplu: 0 ¾).

Apasati Ctrl+; pentru a insera data curenta si Ctrl+Shift+; pentru a introduce ora curenta intr-o celula.

Pentru a seta o celula sau un range sa accepte numai un anumit tip de data, folositi Data Validation.

O formula care foloseste o referinta a unei celule din alt worksheet: =Sheet2!A1+1

Page 2: Data Entry Tips

Puteti crea de asemenea si link formulas care se refera la o celula dintr-un workbook diferit =[Budget.xls]Sheet1!A1+1

Daca workbookul de care e legat e inchis, trebuie sa ii completati si calea intreaga, de exemplu: =’C:\MSOffice\Excel\[Budget For 2003]Sheet1’!A1+A1

Folositi Links ca sa recuperati datele dintr-un fisier corupt

Daca nu puteti sa incarcati un fisier Excel corupt, puteti sa scrieti o link formula pentru a recupera toate datele sau o parte din ele (dar nu si formulele). Puteti face asta pentru ca fisierul sursa dintr-un link formula nu trebuie sa fie deschis. Daca fisierul corupt se numeste Badfile.xls, de exemplu, deschideti un workbook nou si introduceti formula urmatoare in celula A1 a sheetului Sheet1 pentru a incerca sa recuperati datele din fisierul corupt:

=[‘C:\Files\[Badfile.xls]Sheet1!A1

unde Badfile.xls este numele workbookului corupt. In noul workbook, copiati formula in jos si in dreapta pentru a recupera informatia.

Adaugati un nou obiect tip comentariu

Range(“A1”).AddComment “Formula developed by JW.”

Metoda genereaza eroare daca celula contine deja un comentariu.

Page 3: Data Entry Tips

Obiecte tip Range

Un obiect tip Range este continut intr-un obiect Worksheet si consta intr-una sau mai multe celule dintr-un singur worksheet.

Exista 3 moduri de a te referi la obiecte tip Range in VBA:◆ Proprietatea Range a unui Worksheet sau Range class object◆ Proprietatea Cells a unui worksheet◆ Proprietatea Offset a unui obiect tip Range

Proprietatea RangeAceasta intoarce un obiect tip Range. Aceasta proprietate are doua sintaxe:object.Range(cell1)object.Range(cell1, cell2)

De asemenea, proprietatea Range recunoaste si numele definite in workbooks.

Proprietatea Cells

Aceasta are 3 sintaxe:object.Cells(rowIndex, columnIndex)object.Cells(rowIndex)object.Cells

Proprietatea Offset

Page 4: Data Entry Tips

Si aceasta intoarce un obiect tip Range, dar se aplica numai unui obiect tip Range si niciunei alte clase. Sintaxa este:

object.Offset(rowOffset, columnOffset)

Proprietatea Offset are 2 argumente care corespund pozitiei relative din celula din stanga sus a range-ului. Argumentele pot fi pozitive (in jos sau in dreapta), negative (in sus sau in stanga), sau zero.

Exemplul urmator introduce valoarea 12 in celula direct sub celula activa:

ActiveCell.Offset(1,0).Value = 12

Page 5: Data Entry Tips

For worksheet calculation, Excel uses the Double data type, so that’s a goodchoice for processing numbers in VBA when you don’t want to lose any precision.For integer calculations, you can use the Integer type if you’re sure that the valueswill not exceed 32,767. Otherwise, use the Long data type. When dealing with Excelworksheet row numbers, you’ll want to use the Long data type because the numberof rows in a worksheet exceeds the maximum value for the Integer data type.

Declaring variables

If you don’t declare the data type for a variable that you use in a VBA routine, VBAuses the default data type, Variant. Data stored as a Variant acts like achameleon: It changes type, depending on what you do with it.

Thanks to VBA, the data type conversion of undeclared variables is automatic.This process might seem like an easy way out, but remember that you sacrificespeed and memory.

It’s an excellent habit to declare each variable in a procedure before you use it.Declaring a variable tells VBA its name and data type. Declaring variables providestwo main benefits:◆ Your programs run faster and use memory more efficiently. The default

Page 6: Data Entry Tips

data type, Variant, causes VBA to repeatedly perform time-consumingchecks and reserve more memory than necessary. If VBA knows the datatype, it doesn’t have to investigate, and it can reserve just enough memoryto store the data.◆ You avoid problems involving misspelled variable names. This assumesthat you use Option Explict to force yourself to declare all variables(see the next section). Say that you use an undeclared variable namedCurrentRate. At some point in your routine, however, you insert thestatement CurentRate = .075. This misspelled variable name, which isvery difficult to spot, will likely cause your routine to give incorrectresults.

FORCING YOURSELF TO DECLARE ALL VARIABLESTo force yourself to declare all the variables that you use, include the following asthe first instruction in your VBA module:Option ExplicitThis statement causes your program to stop whenever VBA encounters a variablename that has not been declared. VBA issues an error message, and you mustdeclare the variable before you can proceed.

Scoping variables

LOCAL VARIABLESA local variable is a variable declared within a procedure. Local variables can beused only in the procedure in which they are declared. When the procedure ends,the variable no longer exists, and Excel frees up its memory. The most common way to declare a local variable is to place a Dim statementbetween a Sub statement and an End Sub statement.

Page 7: Data Entry Tips

MODULEWIDE VARIABLESSometimes, you’ll want a variable to be available to all procedures in a module. Ifso, just declare the variable before the module’s first procedure (outside of any proceduresor functions).

The value of a module-wide variable does not change when a procedure ends.An exception to this occurs if the procedure is halted with an End statement. WhenVBA encounters an End statement, all module-wide variables lose their values.

PUBLIC VARIABLESTo make a variable available to all the procedures in all the VBA modules in a project,declare the variable at the module level by using the Public keyword ratherthan Dim.

Page 8: Data Entry Tips

STATIC VARIABLESStatic variables are a special case. They are declared at the procedure level, andthey retain their value when the procedure ends (unless the procedure is halted withan End statement).You declare static variables by using the Static keyword

CONSTANTE

DECLARAREA CONSTANTELOR

Declararea constantelor se face folosind “Const”.

Ca si variabilele, si constantele au un scop. Daca vreti ca o constanta sa fie disponibila intr-o singura procedura, declarati-o dupa Sub sau Function pentru a o face o constanta locala. Pentru a face o constanta disponibila in toate procedurile dintr-un modul, declarati-o inainte de prima procedura din modul. Pentru a face o constanta vizibila in toate modulele dintr-un workbook, folositi Public si declarati constanta inainte de prima procedura dintr-un modul.

Lucrul cu variabile / constante tip string

In VBA exista 2 tipuri de siruri: Siruri cu lungime fixa sunt declarate cu un anumit numar de

caractere. Lungimea maxima este de 65,535 caractere. Siruri cu lungime variabila teoretic pot pastra pana la 2 billion

caractere.

Fiecare caracter dintr-un sir necesita 1 byte de stocare, si inca o mica valoare pentru headerul fiecarui sir. Cand declarati o variabila tip string cu “Dim”, puteti specifica si dimensiunea, daca o stiti (acesta va fi un sir cu lungime fixa) sau puteti sa lasati VBA-ul sa lucreze cu ea dinamic (acesta va fi un sir cu lungime variabila).

Dim MyString As String * 50 - sir cu lungime fixa de 50 caractereDim YourString As String - sir cu lungime variabila

Lucrul cu variabile / constante tip data

Exemple de declarare a variabilelor si constantelor ca tip Date:

Dim Today As DateDim StartTime As DateConst FirstDay As Date = #1/1/2001#Const Noon = #12:00:00#

Constantele tip Date sunt definite intotdeauna folosind formatul month/day/year, chiar daca sistemul e setat sa afiseze datele in alt format, de exemplu zi/luna/an. Daca folositi un MsgBox pentru a afisa o data va fi afisata conform cu setarile sistemului.

Page 9: Data Entry Tips

Matrici

O matrice este un grup de elemente de acelasi tip, care au acelasi nume; puteti sa va referiti la un anumit element din matrice folosind numele matricei si un index. De exemplu, puteti defini o matrice de 12 variabile tip string astfel incat fiecare sa ii corespunda unei luni. Daca numiti matricea MonthNames, puteti sa va referiti la primul element din matrice ca MonthNames(0), al doilea element ca MonthNames(1), si asa mai departe pana la MonthNames(11).

Declararea matricilor

Matricile se declara cu Dim sau Public, la fel ca si celelalte variabile. De asemenea, puteti specifica si numarul de elemente din matrice, specificand primul index, apoi “To” apoi al 2-lea index, intre paranteze. De exemplu:

Dim MyArray(1 To 100) As Integer

Cand declarati o matrice trebuie sa specificati numai indexul superior, caz in care VBA presupune ca 0 este indexul inferior. Cele de mai jos au exact acelasi efect:

Dim MyArray(0 to 100) As IntegerDim MyArray(100) As Integer

In ambele cazuri, matricea consta in 101 elemente.

Daca vreti ca VBA sa presupuna ca 1 este indexul inferior, trebuie sa includeti urmatorul statement inainte de orice procedura din modul:

Option Base 1

Declararea matricilor multidimensionale

Matricile din exemplele anterioare erau uni-dimensionale. Matricile in VBA pot avea pana la 60 de dimensiuni, desi rareori e nevoie de mai mult de 3 dimensiuni (3-D array). Cum se declara o matrice de 100 elemente integer cu 2 dimensiuni (2-D):

Dim MyArray(1 To 10, 1 To 10) As Integer

Pentru a va referi la un anumit element dintr-o matrice bi-dimensionala, trebuie sa specificati indexul pentru rand si coloana. De exemplu, ca sa asignati o valoare pentru un element din matricea de mai sus:

MyArray(3, 4) = 125

O matrice dinamica nu are un numar prestabilit de elemente. Declarati o matrice dinamica cu un set de paranteze:

Dim MyArray() As Integer

Page 10: Data Entry Tips

Inainte sa puteti folosi o matrice dinamica in codul vostru, trebuie sa o redimensionati folosind ReDim, pentru a-I spune cate elemente se afla in matrice. Puteti folosi ReDim ori de cate ori doriti.

VARIABILE OBIECT

O variabila tip obiect este o variabila care reprezinta un intreg obiect, cum ar fi un range sau un worksheet.

Variabilele tip obiect sunt declarate ca si celelalte variabile, cu Dim sau Public. De exemplu, declaram InputArea ca obiect de tip Range:

Public InputArea As Range

Ca sa vedeti cum se simplifica codul folosind variabile tip obiect, vedeti procedura urmatoare, care a fost scrisa fara a folosi variabile tip obiect:

Sub NoObjVar()Worksheets(“Sheet1”).Range(“A1”).Value = 124Worksheets(“Sheet1”).Range(“A1”).Font.Bold = TrueWorksheets(“Sheet1”).Range(“A1”).Font.Italic = TrueEnd Sub

Aceasta rutina introduce o valoare in celula A1 a Sheet1 din workbookul activ si apoi bolduieste si face italic continutul celulei.

Puteti condensa rutina de mai sus cu o variabila tip obiect:

Sub ObjVar()Dim MyCell As RangeSet MyCell = Worksheets(“Sheet1”).Range(“A1”)MyCell.Value = 124MyCell.Font.Bold = TrueMyCell.Font.Italic = TrueEnd Sub

Dupa ce variabila MyCell este declarata ca obiect tip Range, cu Set I se asigneaza un obiect. Ulterior se poate folosi direct MyCell in loc de Worksheets(“Sheet1”).Range(“A1”).

Dupa ce un obiect este asignat unei variabile, VBA o poate accesa mai rapid. Deci, atunci cand viteza este critica, folositi obiecte.

Un alt mod de a imbunatati viteza codului este folosirea With-End With

Tipuri de date User-Defined

VBA permite sa creati tipuri de date user-defined. De exemplu, daca aplicatia lucreaza cu informatii despre clienti, ati putea dori sa creati un tip de data user-defined numit CustomerInfo, astfel:

Type CustomerInfo

Page 11: Data Entry Tips

Company As String * 25Contact As String * 15RegionCode As IntegerSales As LongEnd Type

Aceste tipuri de date se definesc la inceputul modulului, inainte de orice procedura.

Dupa ce ati creat un tip de data user-defined, puteti folosi Dim pentru a o declara. De obicei definiti o matrice. De exemplu:

Dim Customers(1 To 100) As CustomerInfo

Fiecare din cele 100 elemente din aceasta matrice in this array consists of four components (as specifiedby the user-defined data type, CustomerInfo). You can refer to a particular componentof the record as follows:Customers(1).Company = “Acme Tools”Customers(1).Contact = “Tim Robertson”Customers(1).RegionCode = 3Customers(1).Sales = 150677You can also work with an element in the array as a whole. For example, to copythe information from Customers(1) to Customers(2), use this instruction:Customers(2) = Customers(1)The preceding example is equivalent to the following instruction block:Customers(2).Company = Customers(1).CompanyCustomers(2).Contact = Customers(1).ContactCustomers(2).RegionCode = Customers(1).RegionCodeCustomers(2).Sales = Customers(1).Sales

To get a list of VBA functions while you’re writing your code, type VBA followedby a period ( . ). The VBE displays a list of all its members, includingfunctions (see Figure 8-1).The functions are preceded by a green icon. If thistechnique doesn’t work for you, make sure that the Auto List Membersoption is selected.Choose Tools→Options and then click the Editor tab.

The MsgBox Function

The official syntax of the MsgBox function has five arguments (those in squarebrackets are optional):MsgBox(prompt[, buttons][, title][, helpfile][, context])◆prompt: (Required) The message displayed in the pop-up display.◆buttons: (Optional) A value that specifies which buttons and which icons, ifany, appear in the message box. Use built-in constants—for example,vbYesNo.◆title: (Optional) The text that appears in the message box’s title bar. The

Page 12: Data Entry Tips

default is Microsoft Excel.◆helpfile: (Optional) The name of the help file associated with the messagebox.◆context: (Optional) The context ID of the help topic. This represents a specifichelp topic to display.

Manipulating Objects and Collections

VBA offers two important constructsthat can simplify working with objects and collections:◆With-End With constructs◆For Each-Next constructs

With-End With constructsThe With-End With instruction construct enables you to perform multiple operationson a single object. To start understanding how the With-End With constructworks, examine the following procedure, which modifies five properties of a selection’sformatting (the selection is assumed to be a Range object):Sub ChangeFont1()Selection.Font.Name = “Times New Roman”Selection.Font.FontStyle = “Bold Italic”Selection.Font.Size = 12Selection.Font.Underline = xlUnderlineStyleSingleSelection.Font.ColorIndex = 5End SubThis procedure can be rewritten using the With-End With construct. The followingprocedure performs exactly like the preceding one:Sub ChangeFont2()With Selection.Font.Name = “Times New Roman”.FontStyle = “Bold Italic”.Size = 12.Underline = xlUnderlineStyleSingle.ColorIndex = 5End WithEnd SubSome people think that the second incarnation of the procedure is actually moredifficult to read. Remember, though, that the objective is increased speed. Althoughthe first version may be more straightforward and easier to understand, a procedurethat uses the With-End With construct when changing several properties of anobject can be significantly faster than the equivalent procedure that explicitly referencesthe object in each statement.

Page 13: Data Entry Tips

For Each-Next constructsRecall from the preceding chapter that a collection is a group of related objects. Forexample, the Workbooks collection is a collection of all open Workbook objects.There are many other collections that you can work with. You don’t have to knowhow many elements are in a collection to use the For Each-Next construct.Suppose that you want to perform some action on all objects in a collection. Orsuppose that you want to evaluate all objects in a collection and take action undercertain conditions. These are perfect occasions for the For Each-Next construct.The syntax of the For Each-Next construct isFor Each element In group[instructions][Exit For][instructions]Next [element]The following procedure uses the For Each-Next construct to refer to each ofthe six members of a fixed-length array one at a time:Sub Macro1()Dim MyArray(5) As DoubleFor i = 0 To 5MyArray(i) = RndNext iFor Each n In MyArrayDebug.Print nNext nEnd SubThe next procedure uses the For Each-Next construct with the Sheets collectionin the active workbook. When you execute the procedure, the MsgBox functiondisplays each worksheet’s Name property. (If there are five worksheets in the activeworkbook, the MsgBox function is called five times.)Sub CountSheets()Dim Item as WorkSheetFor Each Item In ActiveWorkbook.WorkSheetsMsgBox Item.NameNext ItemEnd Sub218 Part III: Understanding Visual Basic for ApplicationsIn the preceding example, Item is an object variable (more specifically, aWorksheet object). There’s nothing special about the name Item; you canuse any valid variable name in its place.The next example uses For Each-Next to cycle through all objects in theWindows collection:Sub HiddenWindows()Dim AllVisible As BooleanDim Item As Window

Page 14: Data Entry Tips

AllVisible = TrueFor Each Item In WindowsIf Item.Visible = False ThenAllVisible = FalseExit ForEnd IfNext ItemMsgBox AllVisibleEnd SubIf a window is hidden, the value of AllVisible is changed to False, and the ForEach-Next loop is exited. The message box displays True if all windows are visibleand False if at least one window is hidden. The Exit For statement is optional. Itprovides a way to exit the For Each-Next loop early. This is generally used in conjunctionwith an If-Then statement (which I describe later in this chapter).Here’s an example that closes all workbooks except the active workbook. Thisprocedure uses the If-Then construct to evaluate each workbook in the Workbookscollection.Sub CloseInActive()Dim Book as WorkbookFor Each Book In WorkbooksIf Book.Name <> ActiveWorkbook.Name Then Book.CloseNext BookEnd SubMy final example of For Each-Next is designed to be executed after the userselects a range of cells. Here, the Selection object acts as a collection that consistsof Range objects because each cell in the selection is a Range object. The procedureevaluates each cell and uses the VBA UCase function to convert its contents touppercase. (Numeric cells are not affected.)Chapter 8: VBA Programming Fundamentals 219Sub MakeUpperCase()Dim Cell as RangeFor Each Cell In SelectionCell.Value = UCase(Cell.Value)Next CellEnd Sub

Controlling ExecutionThis section discusses the additional ways of controlling the execution ofyour VBA procedures:◆GoTo statements◆If-Then constructs◆Select Case constructs◆For-Next loops◆Do While loops

Page 15: Data Entry Tips

◆Do Until loops

GoTo statementsThe most straightforward way to change the flow of a program is to use a GoTostatement. This statement simply transfers program execution to a new instruction,which must be preceded by a label (a text string followed by a colon, or a numberwith no colon). VBA procedures can contain any number of labels, and a GoTostatement cannot branch outside of a procedure.The following procedure uses the VBA InputBox function to get the user’s name.If the name is not Howard, the procedure branches to the WrongName label andends. Otherwise, the procedure executes some additional code. The Exit Sub statementcauses the procedure to end.Sub GoToDemo()UserName = InputBox(“Enter Your Name:”)If UserName <> “Howard” Then GoTo WrongNameMsgBox (“Welcome Howard...”)‘ -[More code here] -220 Part III: Understanding Visual Basic for ApplicationsExit SubWrongName:MsgBox “Sorry. Only Howard can run this.”End SubThis simple procedure works, but in general you should use the GoTo statementonly when there is no other way to perform an action.

If-Then constructs

The basic syntax of the If-Then construct isIf condition Then true_instructions [Else false_instructions]The If-Then construct is used to execute one or more statements conditionally.The Else clause is optional. If included, it lets you execute one or more instructionswhen the condition that you’re testing is not True.

If condition Then[true_instructions][ElseIf condition-n Then[alternate_instructions]][Else[default_instructions]]End If

When you need to chooseamong three or more alternatives, the Select Case structure is often a better construct

Page 16: Data Entry Tips

to use.

Select Case constructsThe Select Case construct is useful for choosing among three or more options.This construct also works with two options and is a good alternative to If-Then-Else. The syntax for Select Case is as follows:Select Case testexpression[Case expressionlist-n[instructions-n]][Case Else[default_instructions]]End Select

VBA offers an alternative to the If-Then construct: the IIf function. This functiontakes three arguments and works much like Excel’s IF worksheet function. The syntax isIIf(expr, truepart, falsepart)expr: (Required) Expression you want to evaluate.truepart: (Required) Value or expression returned if expr is True.falsepart: (Required) Value or expression returned if expr is False.

If you use only one instruction percase, as in the preceding example, you might want to put the instruction on thesame line as the Case keyword (but don’t forget the VBA statement-separator character,the colon). This technique makes the code more compact. For example:Sub Discount3()Dim Quantity As VariantDim Discount As DoubleQuantity = InputBox(“Enter Quantity: “)Select Case QuantityCase “”: Exit SubCase 0 To 24: Discount = 0.1Case 25 To 49: Discount = 0.15Case 50 To 74: Discount = 0.2Case Is >= 75: Discount = 0.25End SelectMsgBox “Discount: “ & DiscountEnd Sub

Looping blocks of instructions

FOR-NEXT LOOPSThe simplest type of a good loop is a For-Next loop. Its syntax isFor counter = start To end [Step stepval][instructions][Exit For][instructions]Next [counter]

Page 17: Data Entry Tips

Following is an example of a For-Next loop that doesn’t use the optional Stepvalue or the optional Exit For statement. This routine executes the Sum = Sum +Sqr(Count) statement 100 times and displays the result—that is, the sum of thesquare roots of the first 100 integers.Sub SumSquareRoots()Dim Sum As DoubleDim Count As IntegerSum = 0For Count = 1 To 100Sum = Sum + Sqr(Count)Next CountMsgBox SumEnd SubIn this example, Count (the loop counter variable) started out as 1 and increasedby 1 each time the loop repeated. The Sum variable simply accumulates the squareroots of each value of Count.

For-Next loops can also include one or more Exit For statements within theloop. When this statement is encountered, the loop terminates immediately andcontrol passes to the statement following the Next statement of the current For-Next loop. The following example demonstrates use of the Exit For statement.This procedure determines which cell has the largest value in column A of theactive worksheet:Sub ExitForDemo()Dim MaxVal As DoubleDim Row As LongDim TheCell As RangeMaxVal = Application.WorksheetFunction.Max(Range(“A:A”))For Row = 1 To 65536Set TheCell = Range(“A1”).Offset(Row - 1, 0)If TheCell.Value = MaxVal ThenMsgBox “Max value is in Row “ & RowTheCell.ActivateExit ForEnd IfNext RowEnd Sub

DO WHILE LOOPSA Do While loop is another type of looping structure available in VBA. Unlike aFor-Next loop, a Do While loop executes while a specified condition is met. A DoWhile loop can have either of two syntaxes:

Page 18: Data Entry Tips

Do [While condition][instructions][Exit Do][instructions]LooporDo[instructions][Exit Do][instructions]Loop [While condition]

Do While loops can also contain one or more Exit Do statements. When anExit Do statement is encountered, the loop ends immediately and control passes tothe statement following the Loop statement.

DO UNTIL LOOPSThe Do Until loop structure is very similar to the Do While structure. The differenceis evident only when the condition is tested. In a Do While loop, the loop executeswhile the condition is True. In a Do Until loop, the loop executes until thecondition is True.Do Until also has two syntaxes:Do [Until condition][instructions][Exit Do][instructions]LooporDo[instructions][Exit Do][instructions]Loop [Until condition]

Working with VBASub Procedures

A procedure is a series of VBA statements that resides in a VBA module, whichyou access in the Visual Basic Editor (VBE). A module can hold any number ofprocedures.You have a number of ways to call, or execute, procedures. A procedure is executedfrom beginning to end, but it can also be ended prematurely.

Some procedures are written to receive arguments. An argument is simply informationthat is used by the procedure that is passed to the procedure when it is executed.

Page 19: Data Entry Tips

Procedure arguments work much like the arguments that you use in Excelworksheet functions.

Declaring a Sub procedureA procedure declared with the Sub keyword must adhere to the following syntax:[Private | Public][Static] Sub name ([arglist])[instructions][Exit Sub][instructions]End Sub◆Private: (Optional) Indicates that the procedure is accessible only toother procedures in the same module.◆Public: (Optional) Indicates that the procedure is accessible to all otherprocedures in all other modules in the workbook. If used in a module thatcontains an Option Private Module statement, the procedure is notavailable outside the project.◆Static: (Optional) Indicates that the procedure’s variables are preservedwhen the procedure ends.◆Sub: (Required) The keyword that indicates the beginning of a procedure.◆name: (Required) Any valid procedure name.◆arglist: (Optional) Represents a list of variables, enclosed in parentheses,that receive arguments passed to the procedure. Use a comma to separatearguments. If the procedure uses no arguments, a set of empty parenthesesis required.◆instructions: (Optional) Represents valid VBA instructions.

◆Exit Sub: (Optional) A statement that forces an immediate exit from theprocedure prior to its formal completion.◆End Sub: (Required) Indicates the end of the procedure.

PUBLIC PROCEDURESBy default, procedures are public—that is, they can be called by other procedures inany module in the workbook. It’s not necessary to use the Public keyword, but programmersoften include it for clarity. The following two procedures are both public:Sub First()‘ ... [code goes here] ...End SubPublic Sub Second()‘ ... [code goes here] ...End Sub

Every procedure must have a name. The rules governing procedure names are generallythe same as for variable names. Ideally, a procedure’s name should describe what itscontained processes do. A good rule is to use a name that includes a verb and a noun

Page 20: Data Entry Tips

(for example, ProcessDate, PrintReport, Sort_Array, or CheckFilename).Avoid meaningless names such as DoIt, Update, and Fix.

PRIVATE PROCEDURESPrivate procedures can be called by other procedures in the same module but not byprocedures in other modules.

You can force all procedures in a module to be private—even thosedeclared with the Public keyword—by including the following statementbefore your first Sub statement:Option Private ModuleIf you write this statement in a module, you can omit the Private keywordfrom your Sub declarations

CALLING A PROCEDURE IN A DIFFERENT MODULEIf VBA can’t locate a called procedure in the current module, it looks for public proceduresin other modules in the same project.If you need to call a private procedure from another procedure, both proceduresmust reside in the same module.You can’t have two procedures with the same name in the same module, but youcan have identically named procedures in different modules. You can force VBA toexecute an ambiguously named procedure—that is, another procedure in a differentmodule that has the same name. To do so, precede the procedure name with themodule name and a dot. For example, say that you define procedures named MySubin Module1 and Module2. If you want a procedure in Module2 to call the MySub inModule1, you can use either of the following statements:Module1.MySubCall Module1.MySubIf you do not differentiate between procedures that have the same name, you getan Ambiguous name detected error message.

Trapping errorsYou can use the On Error statement to specify what happens when an error occurs.Basically, you have two choices:◆ Ignore the error and let VBA continue. You can later examine the Errobject to determine what the error was and then take action if necessary.258 Part III: Understanding Visual Basic for Applications◆ Jump to a special error-handling section of your code to take action. Thissection is placed at the end of the procedure and is also marked by a label.To cause your VBA code to continue when an error occurs, insert the followingstatement in your code:

Page 21: Data Entry Tips

On Error Resume NextSome errors are inconsequential and can simply be ignored. But you may wantto determine what the error was. When an error occurs, you can use the Err objectto determine the error number. The VBA Error function can be used to display thetext for Err.ValueNumber, which defaults to just Err. For example, the followingstatement displays the same information as the normal Visual Basic error dialogbox (the error number and the error description):MsgBox “Error “ & Err & “: “ & Error(Err)

Error-handling examples

Using the OnError Resume Next statement simply prevents the error message from appearing.Sub SelectFormulas()On Error Resume NextSelection.SpecialCells(xlFormulas, xlNumbers).SelectOn Error GoTo 0‘ ...[more code goes here]End SubNotice that the On Error GoTo 0 statement restores normal error handling forthe remaining statements in the procedure.The following procedure uses an additional statement to determine whether anerror did occur:Sub SelectFormulas2()On Error Resume NextSelection.SpecialCells(xlFormulas, xlNumbers).SelectIf Err <> 0 Then MsgBox “No formula cells were found.”On Error GoTo 0‘ ...[more code goes here]End Sub

I inserted the following instructionat the beginning of SortSheets to turn off screen updating:Application.ScreenUpdating = False

Creating FunctionProcedures

Function procedures, on the other hand, usuallyreturn a single value (or an array), just like Excel worksheet functions and VBAbuilt-in functions do. Like with built-in functions, your Function procedures canuse arguments.

Page 22: Data Entry Tips