Ravindra BagaleCourses & study guides मराठी Track your progress

12. Macros and VBA

Excel

12.6 Variables and Data Types

Vikram receives an order ID displayed as 000507, a quantity of four and a price of 99.25. If he reads them all as numbers, the ID can lose its leading zeroes. If he reads them all as text, a calculation may use the wrong type. A VBA variable gives each piece of information a name and an expected kind of value. You will use those choices to calculate a real, checkable order average and validate a small input row.

Name the kind of information you are reading

Think about meaning before writing Dim

Imagine GreenField Dairy receiving a daily order list from a storefront like Blinkit. These order numbers, results and operations are fictional practice. The person reading an ID needs to be able to look it up exactly. Someone reading quantity needs a whole number. Someone summing the price needs a numeric amount in one stated currency. These are different needs, even if a worksheet can display them all in similar-looking cells.

A sample order ID keeps leading zeroes as a string, units uses a whole-number Long, and delivered uses a Boolean true value.
The ID, units and delivered field answer different questions. Preserve the data type that lets each field serve its purpose.

A variable is a named place to store information during a run. A declaration such as Dim orders As Long tells VBA the name and type. The name documents the purpose of the value. The type determines which values the variable can hold and which conversions may be needed before assigning input from a worksheet. A simple procedure can keep its variables local so another routine does not reuse the same names by accident.

Choose a type by the story the value tells
TypeFits this exampleCheck
String000507, PuneKeep exact characters and compare consistent labels
LongRows, order counts, whole quantitiesCheck for whole values and an allowed range
DoubleAverages and measurementsApproximate floating-point arithmetic
CurrencyA rupee value with fixed precisionFour fixed decimal places with a finite range
BooleanDelivered or awaiting deliveryActual logical values differ from text labels
DateA report date or timestampInterpret date, time and locale deliberately
VariantAn unvalidated value read from a cellDistinguish Empty, Error, number, Boolean and text
Worksheet or RangeThe report worksheet or a cell regionAssign the object reference using Set
  • Keep identifiers as strings. The text 000507 can refer to a different ID from the text 507. If Excel already stored a number and just formats it with six digits, VBA's Value2 gives the numeric value. Convert the import correctly at the source or explicitly decide the display is what your identifier format requires. Reading a numeric value into a String does not know how many leading zeroes the input originally contained.
  • Use Long for worksheet indices and counts. VBA Integer only fits whole values from minus 32,768 through 32,767. Long fits from minus 2,147,483,648 through 2,147,483,647 and can hold a modern Excel row number. Both are limited. Use input checks to avoid overflow. An order count on row 50,000 should never depend on an Integer counter.
  • Use Double for floating quantities and ratios. A Double can represent a wide range of fractional values, with finite binary precision. Some decimal values such as 0.1 cannot be represented exactly in binary floating point. Apply a documented tolerance when comparing calculated measurements, or choose a suitable fixed precision representation for a business amount whose decimal rules matter.
  • Use Currency for a bounded fixed-precision amount. In VBA this type stores a scaled integer with four decimal places. This can be useful for fixed-place monetary values. It does not automatically choose a currency, exchange rate or two-decimal business rounding policy. A sheet may display two decimals while your calculation uses four. Choose a rounding stage and apply it consciously.
  • Use Date and Boolean for actual dates and flags. Give a report date as a real Date value, such as one produced by DateSerial with explicit components. A true Boolean flag differs from text spelling TRUE. In a worksheet guard, test the actual value type. A fixed English spelling does not establish whether the source has stored numbers, dates or text under its formatting.

Declare each variable explicitly

Read what each As clause covers

Start a fresh standard module with Option Explicit. VBA then requires declared variables and can detect a misspelling such as cntOrders when you meant countOrders. This is a compile check. It cannot by itself detect whether your worksheet holds an order ID in a numeric cell. The type definitions and your runtime checks address those different problems.

VBA allows multiple declarations on one line, but a type after the last name applies only to that variable. In Dim firstRow, lastRow As Long, firstRow is a Variant and lastRow is a Long. Write the type on each name, or on separate lines if the declarations describe related but different meanings. This is especially important when you expect an ordered counter or a default starting value.

Option Explicit
Dim firstRow As Long
Dim lastRow As Long
Dim city As String
Dim ordersSheet As Worksheet
Dim rawCell As Variant
  • Assignment: An ordinary assignment such as city = "Pune" stores a text value in a declared variable. VBA can try to convert some other values into the target type. Do not rely on this to clean an import silently. Verify which input is intended first and convert only after checking.
  • Object assignment: Set ordersSheet = ThisWorkbook.Worksheets("Orders") stores a reference to an existing worksheet object. It does not copy the worksheet. Later code can use that reference to read its cells. If you need to copy a cell's value into a number, read a value property and use ordinary assignment.
  • Shared lifetime: A local variable declared with Dim inside a routine belongs to that call. Choose local variables for a small exercise. Module-level declarations and Static variables can have different lifetime or scope. If a test count should begin at zero each time, place and initialize it where the caller can see that behavior.
  • Conversion: VBA offers functions such as CLng and CCur to ask for a specific type. Converting a fraction to Long can round it rather than reject it; CLng uses nearest even for a tie. If your field must contain whole quantities, check whether the number already equals its integer part before converting. Check the range needed by the task too.

Remember: Store what the business field means. Use a Variant when you need to inspect what a cell supplied, then validate and convert it to a meaningful type when appropriate.

Lab one. Use typed variables for a real carry-forward example

Define what a city average means

The order average is money divided by the number of orders included in the same rule. The baseline Formulas and Functions practice data has four Pune orders with amounts 64, 110, 150 and 220. Together those are 544. Divide by four to get 136. One Pune row is Cancelled. If you want the average of just Delivered orders, remove its 220 from the numerator and its one order from the denominator. That gives 324 divided by three or 108. Use the same rule on both sides of the division.

Four Pune orders in all statuses total 544. Three delivered Pune orders total 324. The two different denominators give 136 and 108.
Label the rule before interpreting the average. Counting only delivered orders but including every amount would answer a different question.

Place the subset of the sample used here

In your own TypesPractice.xlsm add a sheet named Orders. The earlier chapter's full dataset is compatible. For this exercise you need only the four columns shown here. Enter the order IDs in A2:A11, the city labels in C2:C11, amounts in G2:G11 and statuses in I2:I11. Use headers in row one. Keep the amounts as numbers, with a single currency. Leave the other fields blank if you are building only the smaller version. The totals here are gross recorded amounts and do not represent actual marketplace sales.

Use the same ten records from chapter 3
Order IDCityAmountStatus
BLK-1001Pune64Delivered
BLK-1002Nashik270Delivered
AMN-1003Pune110Delivered
BLK-1004Nagpur240Cancelled
AMN-1005Kolhapur232Delivered
BLK-1006Pune150Delivered
BLK-1007Solapur1299Delivered
AMN-1008Sambhaji Nagar195Returned
BLK-1009Pune220Cancelled
BLK-1010Nashik90Delivered
Option Explicit

Public Sub ShowCityOrderAverage()
    Dim ws As Worksheet
    Dim city As String
    Dim orderCount As Long
    Dim sales As Double
    Dim averageOrder As Double

    Set ws = ThisWorkbook.Worksheets("Orders")
    city = "Pune"
    orderCount = CLng(Application.WorksheetFunction.CountIf(ws.Range("C2:C11"), city))
    If orderCount = 0 Then
        MsgBox "No matching orders for " & city
        Exit Sub
    End If

    sales = Application.WorksheetFunction.SumIf( _
        ws.Range("C2:C11"), city, ws.Range("G2:G11"))
    averageOrder = sales / orderCount
    MsgBox city & ": " & orderCount & " orders, average Rs " & _
           Format$(averageOrder, "0.00")
End Sub
  • Text choice: city is stored as an exact sample string. For this named value CountIf tests the matching city range. In spreadsheet criteria functions wildcard characters have special meaning, so there is a difference between a known label and arbitrary user text entered into a future program.
  • Count choice: CountIf returns a numeric count, which you can explicitly convert to Long here. The calculation covers ten cells, so the result is a small whole number. Zero means there is no denominator. Use a clear message and stop before division.
  • Sum choice: A Double represents the numeric amount from SumIf. The two ranges have the same height so each city lines up with its row amount. The amount values are numeric in this fixture. A wrong or blank amount could still produce a result if ignored by the aggregation, so the fixture's numeric assumption matters.
  • Average choice: A Double can retain a fraction rather than round it to a whole count. Format dollar sign is the VBA string-returning version used to render two displayed decimal places in the message. It does not change the average variable. Your desktop might display a different decimal mark.

Check the result and then change only the city

  1. Add the code to your own standard module. Use the title and expected scope to select the macro in the approved desktop. The first message should report Pune, four orders and an average of 136.00 in the desktop's numeric display. Compare the message with the four row values and your manual division.
  2. In a spare area verify the same result with independent COUNTIF and SUMIF formulas referencing C2:C11 and G2:G11. Compare the count and amount separately before comparing the average. Adding a formula to the end result alone would not reveal an incorrectly filtered numerator when the denominator also changed.
  3. In your training code copy set city to Nashik. Expect two orders worth 270 and 90, an amount of 360 and an average of 180. Set city to a name absent from the ten rows, such as Mumbai. Expect the missing-order message and no numerical average. Restore Pune in the learning copy after testing the branches.
  4. As a separate worksheet practice, use COUNTIFS and SUMIFS to add a Delivered rule on I2:I11. The three Pune rows of 64, 110 and 150 give 108. Keep the macro's first label and scope clear. Status-specific averages belong in different columns or reports from all-order averages.
=COUNTIF(C2:C11,"Pune")
=SUMIF(C2:C11,"Pune",G2:G11)
=COUNTIFS(C2:C11,"Pune",I2:I11,"Delivered")
=SUMIFS(G2:G11,C2:C11,"Pune",I2:I11,"Delivered")

Lab two. Validate a mixed-type order before storing a line amount

Prepare one small entry row

Add a worksheet named Entry to your TypesPractice workbook. Set up A1:E1 with the labels Order ID, Units, Unit Price, Delivered, and Checked Amount. In A2 enter the string 000507; either set that cell to the Text format before typing the ID, or enter it with an initial apostrophe as Excel's text marker. The apostrophe is used by Excel to mark text and is not part of the ID when read by the code. Enter a numeric 4 in B2, the number 99.25 in C2, and a real logical value TRUE in D2. You can use the formula below for the logical value. Enter your decimal separator as appropriate for a number on your system. Leave E2 empty.

D2: =TRUE()
G2: =B2*C2

Use G2 as the independent calculation. When the sample is valid the checked amount E2 and G2 should both read three hundred ninety-seven. In G4 put a marker such as “Keep this note.” The code will write one value in E2. It reads the four inputs and validates them as values returned by the workbook. A variable holding a Worksheet must be assigned with Set.

Public Sub CheckEntryTypes()
    Dim ws As Worksheet
    Dim rawId As Variant, rawUnits As Variant
    Dim rawPrice As Variant, rawDelivered As Variant
    Dim orderId As String, units As Long
    Dim price As Currency, amount As Currency
    Dim delivered As Boolean, reportDay As Date

    Set ws = ThisWorkbook.Worksheets("Entry")
    rawId = ws.Range("A2").Value2
    rawUnits = ws.Range("B2").Value2
    rawPrice = ws.Range("C2").Value2
    rawDelivered = ws.Range("D2").Value2

    If VarType(rawId) <> vbString Or VarType(rawDelivered) <> vbBoolean Then
        MsgBox "Use a text ID and an actual TRUE/FALSE value."
        Exit Sub
    End If

    orderId = CStr(rawId)
    If Not (orderId Like "######") Then
        MsgBox "The exercise expects an ID with six digits."
        Exit Sub
    End If

    If VarType(rawUnits) <> vbDouble Or VarType(rawPrice) <> vbDouble Then
        MsgBox "Enter numeric units and price."
        Exit Sub
    End If
    If rawUnits < 0 Or rawUnits > 10000 Or rawUnits <> Fix(rawUnits) Then
        MsgBox "Units must be a whole number from 0 to 10000."
        Exit Sub
    End If
    If rawPrice < 0 Or rawPrice > 1000000 Then
        MsgBox "Unit price is outside the practice range."
        Exit Sub
    End If

    units = CLng(rawUnits)
    price = CCur(rawPrice)
    delivered = CBool(rawDelivered)
    reportDay = DateSerial(2026, 11, 24)
    amount = CCur(units * price)

    ws.Range("E2").Value = amount
    MsgBox orderId & " | Delivered: " & CStr(delivered) & _
           " | Report day: " & Format$(reportDay, "dd-mm-yyyy")
End Sub

Check each branch one change at a time

  1. Run CheckEntryTypes from the practice workbook. Read E2 as 397, verify G2 independently and confirm the ID preserves both zeroes. The message identifies the delivered state and the fixed practice date. This lesson does not use that state to filter revenue. It displays it as separate data and calculates a line amount for both values.
  2. Replace the text ID with a numeric 507, optionally applying a six-digit custom format to make it look like 000507. Expect the first guard to reject it as a numeric value. The text display and the actual value type disagree. Restore the proper string rather than relying on formatting to fix it.
  3. Replace the actual logical value with the text TRUE using the text marker. The message should report an invalid input type. Then restore the actual logical value and try a quantity of 4.5. Its type is numeric but the whole-number guard rejects it before CLng can round it.
  4. Restore the quantity to four and test zero price. It is a valid numeric zero for this exercise and leads to a zero result. Clear the price afterwards. A blank now fails the numeric guard instead of repeating the zero write. A prior output remains stale. Restore the price to 99.25 and check 397 again. Confirm the G4 note never changes.
  5. For an error check in the practice copy put a calculation error such as a division by zero in B2. VarType can identify its value as an Error. It cannot meet the numeric check. Restore the original numeric entry before comparing your outputs. If you cannot run code, use the state diagram and manual arithmetic for the same tests.

Use the numeric and Currency example only within the stated bounds. CCur rounds inputs to its own fixed precision when needed. For the tested price 99.25, the input fits that precision without a rounded change. If you test a more precise decimal, compare the rounded unit price that the macro actually multiplies with the unrounded worksheet formula. If the quantity is large enough the results can diverge. Decide how to handle greater precision according to the business before adapting the exercise. Keep G2 as an independent check for the specified input.

Trace one accepted value and two rejections

  1. Read the actual values

    Raw ID is text with six digits, quantity and price are numbers, and the delivered value is logical.

  2. Check type and bounds

    Four is a permitted whole number. The price is 99.25. Convert them to Long and Currency once the structure fits.

  3. Write one result

    E2 receives 397. Display the exact ID and delivered flag independently of the calculation.

  4. Try a mistaken value

    A numeric ID that displays zeroes or a textual TRUE is rejected. E2 keeps its prior value until an accepted run.

Choose a conversion stage for each kind of value

Five values that look harmless on a worksheet

Excel can format numbers, dates and identifiers to look nearly indistinguishable. An imported 4 might be stored as the text “4.” An unused cell can be truly empty. A formula can return an empty string and leave the cell looking empty. A cancelled order can use the text “Cancelled,” while a separate indicator may be the logical value False. Before converting, decide which of these should be accepted and which need human review. Otherwise a routine may silently create a number because VBA can convert the input, even when that number does not mean what the workbook owner thinks.

  • Blank versus zero: For the checked amount demonstration an empty price is missing information, but zero is a known accepted price in the sample. A formula returning an empty string is a String rather than an Empty value. The numeric guard rejects both. If your import uses special placeholder text for prices, include that case in the test instead of saying a nearby empty-looking row always means no orders.
  • Numeric text versus amount: IsNumeric can recognize some string expressions as convertible numbers. The exercise uses a strict actual numeric cell check instead. If the workflow must accept imported numeric text, state the expected decimal and thousands separators and note which currencies are allowed. Test those exact examples under the intended locale before converting them to a numeric type.
  • Cell error versus label: A formula error can have a displayed label such as a division error. Its stored error result needs a guard before ordinary arithmetic. A Variant can hold that value. Check with IsError or VarType before you do a comparison or conversion that requires a number. If a type check uses VBA's And or Or, make sure both expressions are safe to compute, because they do not provide a guaranteed short-circuit guard for the right side.
  • Six-digit ID versus styled number: Decide whether a numeric 507 formatted to look like 000507 is the canonical stored representation. In the example it is not; known order IDs are six text digits. Take care when copying the cell from a CSV source, which can lead Excel to detect a numeric field. Setting a Text display after losing the zeroes will not reconstruct the original text.
  • Date versus serial: Value2 does not use the VBA Currency and Date types to represent such cells. A date field can come back as a Double. In the exercise that expects a quantity, a numeric type check alone would not identify a date. Use fixture bounds and agreed field meaning. Read values representing calendar dates deliberately with a known date system and locale, rather than blindly converting each numeric amount to a date.

Trace whole-number conversion without altering data

Suppose an order quantity occasionally arrives as 2.5. The entry procedure does not round it; it rejects it because the example's quantity represents a whole count. By contrast CLng would round half-way values to the nearest even whole number. If you deliberately apply CLng to 2.5 and to 3.5 in a permitted Immediate window, the expected results are 2 and 4. This is not the same rule as throwing away fractional digits. The Fix function removes the fractional part toward zero, so for these positive values it gives 2 and 3. Negative inputs are outside the order range, but the distinction matters when reading adjustments or refunds in other workbooks.

? CLng(2.5)
? CLng(3.5)
? Fix(2.5)
? Fix(3.5)
? Fix(-3.5)

Read the expressions without changing the workbook. The last result is minus three, because Fix moves toward zero. This little trace makes it clear why the guard compares the original quantity to Fix of the quantity before CLng is called. With four exactly, the two values agree. With four and a half, the two values differ. The code tests the condition once and exits before writing. The workbook still needs a different approach if quantities can be measured by weight and fractions are legitimate.

Test type capability separately from precision

Now consider quantities of 2 and a unit price of 1.23456 in a practice calculation. A Currency value can hold four decimal places, so a conversion of that price makes a small precision change. The amounts you derive by multiplying the fixed-precision unit price or the unrounded source can differ. That distinction becomes larger when more units are sold. The workbook may display both as the same number of decimal places if it is formatted to two, making the disagreement easy to miss. Compare the unformatted values or convert to the common business rounding stage before comparing.

Calculate both paths before editing the exercise. Converting 1.23456 to four decimal places gives 1.2346. Two units then give 2.4692, while an unrounded unit price gives 2.46912. Both may display 2.47 at two decimals, and neither display proves their stored values are identical. At one thousand units, the two calculations give 1,234.60 and 1,234.56. The cost of choosing the rounding stage increases or decreases with the number of units and the size of the individual rounding difference. Put the required stage explicitly in a specification before someone compares totals from two systems.

Test a Boolean separately from the price. Change the actual delivered flag from true to false while leaving the amount inputs at four and 99.25. The message should change because the flag changed. E2 should still be 397 because this procedure reports an amount for the entry and does not calculate delivered revenue. If another person expects it to zero out a pending row, review the business request, change the formula or procedure deliberately and write a corresponding test. A Boolean type defines the two values a flag can hold. It does not decide which business calculation uses the flag.

The good numeric input in the lesson is simpler: 4 × 99.25 is 397.00 and 99.25 fits within four places. A workbook may hold measurements in Double while a downstream fee calculation needs a fixed-place Currency value. Document whether you round each unit price, each line amount or only the final total. Choosing a variable type does not write that business policy for you. Do not claim that formatting a Double result as two decimals makes all underlying comparisons exact.

Recognize a symptom before changing the declaration

Read where a conversion or calculation went wrong

  1. Type mismatch: Identify the two places where the code first reads and then converts a value. Inspect the actual worksheet cell with the value property or a worksheet test for number or text. A string contains characters even if the cell looks numeric. Instead of relaxing the check until the message disappears, first decide whether the string is an input state the workbook should accept.
  2. Overflow: A variable may be too small for its assigned value, or an arithmetic expression can overflow before it is assigned to a larger variable. Start with types suitable for the inputs and intermediate results. For a loop count reaching 50,000, Long is suitable while Integer is too small. A large price multiplied by many units needs an explicit amount range in an operational design.
  3. No matching orders: The city average uses an early exit. Label the missing data case without showing an average of zero. A valid group with nonempty qualifying rows of zero-priced items would have its own count and actual zero average. On the delivery exercise, show the source count beside the average so a reviewer can distinguish those records.
  4. Unexpected rounded value: Look for a conversion such as CLng or CCur before the result. Compare the typed values to the underlying source value, and check if the code only formats the output string with Format dollar sign. The first kind of operation can alter the stored number. A string display can hide additional precision while leaving the variable unchanged.
  5. Object variable not set: Read the workbook lookup and check whether the worksheet variable has been assigned using Set. Unlike a Long variable initialized to zero, a new object variable needs a valid reference before you access properties like Range. Do not move a worksheet or rename it just to guess how a code reference should resolve.

Document a data contract in ordinary language

For the practice order entry, write “A2 is a six-digit string as stored, B2 is whole units from zero to ten thousand, C2 is numeric price from zero to one million, D2 is a logical flag.” Explain the difference between the data rule and its representation. The destination is E2, and the formula in G2 uses the two current numeric cells independently. The marker in G4 should stay put. Somebody who repeats the test can now see why 507 formatted to six digits is wrong for one field while a plain 4 is correct for the other.

Likewise, a city report definition needs the input grouping columns and a description of the rows included. If a report planner requests a Delivered average, do not simply change the message label for the existing routine. The calculation itself needs the status criterion in both the count and sum. Check 4, 544 and 136 for all statuses, then 3, 324 and 108 for Delivered. A wrong count can look plausible when rounded, so give the two components to the person verifying the report.

Finally, test a new row in an isolated copy without taking the code outside its lesson context. Suppose it has one additional valid Pune order worth 100. If the original range stops at row eleven, the procedure still gets four orders and 544, while a workbook report that includes all eleven records would give five and 644. This is a boundary problem, not a variable type problem. Later in this chapter you will find the last row and choose a bounded source range. Documenting the current ten-row contract lets you tell which change you need.

Say it aloud: “My source variable keeps the actual value type. My checked variable holds what the business requires. My output check proves I wrote the expected number.” Identify one cell for each part of the statement.

Quick checks

Predict the variable state before calculating

What type preserves 000507 as the value of an order ID?

Use a String value with all six characters. When you first enter or import the field, ensure Excel also stores it as text. If it is first stored as the number 507 and only styled with leading zeroes, Value2 returns the numeric value. Converting that value to a String later cannot guess the original six-digit representation.

What type fits a worksheet row number greater than 32,767?

Use Long for the modern Excel row numbers in this course. Integer runs out of positive values at 32,767. A row number of 50,000 fits in Long. Declare the types individually when you put two names on one line, since an As clause after only the second name does not apply to the first.

Four Pune orders total 544. Three delivered orders total 324. Which average is 136?

All statuses gives 544 divided by four, which is 136. Delivered only gives 324 divided by three, which is 108. Keep the same criterion in the count and the sum. An average labeled Delivered needs the actual criterion in both pieces, not just a new label on an all-status average.

What changes when a price is zero, and when it is blank?

Zero is an actual numeric value. It passes the rule in the lesson and can make E2 zero. A blank is missing and causes the guard to exit before assigning a new amount. If the guard leaves E2 at zero because that was the last successful result, read the message to distinguish the two cases.

Why reject a quantity of 4.5 even though CLng can convert it?

The business rule here asks for whole units. Converting a fraction to Long may round it, which would hide invalid input. Check whether the actual number agrees with Fix of that number. Reject the fraction before converting. If fractional units represent real weights, adopt a different stated rule for that data.

What happens if you store worksheet reference like an ordinary number?

A worksheet variable needs Set to assign its object reference. Simple assignment is used for values, such as the result read from Range Value2. Choosing a worksheet variable tells VBA you plan to use the worksheet object itself. Check that the workbook contains the named sheet before expecting the reference to have valid data.

Interview and discussion

Use the workbook examples to defend your choices

When is a Variant useful even though you intend to use explicit types?

A cell can return numeric data, text, an error, a logical value or Empty. Holding the raw result in a Variant lets you inspect it before conversion. After validation, convert a known quantity to Long or a controlled amount to Currency. That approach keeps the flexibility at the input boundary and expresses intent in the calculation variables.

How do Currency and Double differ for a price calculation?

Currency uses fixed precision at four decimal places within its range. Double supports a wider range of approximate floating-point values. For a specified short decimal price and bounded quantity, Currency can be a useful representation. The choice of when and how to round a fee still comes from business policy, and the final Excel cell can have its own storage and display behavior.

How would you interpret a report with a valid count but a surprisingly small average?

Check whether every matching row has a numeric amount. A city count can include a row whose amount is blank or text, while a conditional sum may ignore its amount. Separately list the matching IDs, check each observed value and compare the pieces of the average. A plausible-looking ratio does not establish that all records met their data contract.

How can you distinguish Date values from the numbers returned by Value2?

Value2 can expose the underlying numeric value of a date cell instead of a VBA Date. Check the field definition, workbook context and date system before interpreting a numeric serial. For a fixed test date create a Date directly with known components using DateSerial. A cell's display can help explain its intended meaning but cannot enforce the rule on imports.

Where should you check for an empty group when writing an order average?

Check the order count before dividing. If a chosen city has no matches, report that there is no average for the requested group. If a valid group has orders all valued at zero, the count is positive and zero is meaningful. Keeping the count and the value separate lets the report viewer interpret them together.

Six recall cards

  • Use text for identity

    Keep the actual six digits of 000507 as a String. Number formatting does not create text in the underlying cell.

  • Declare separately

    Specify As Long for each row variable. Option Explicit requires declarations but does not supply the desired type for you.

  • Validate raw types

    Read into a Variant, then check text, logical, numeric, blank or error before converting to the needed calculation type.

  • Retain precision deliberately

    Currency has four fixed decimal places. Double is approximate. Decide the allowed scale and rounding for the actual job.

  • Count then divide

    Four orders and 544 gives 136; three delivered and 324 gives 108. A missing group has no defined average here.

  • Use Set for objects

    Set assigns a worksheet or range reference. Use ordinary assignment when you read or calculate a number or text value.

Microsoft references

Continue practising: explore the existing Excel Task Hub for additional exercises.