Determining the Address of a Range of Cells

Determining the Address of a Range of Cells

Determining the Address of a Range of Cells

Address: This method returns the address of a range in the form of a character string. If the range A1:B4 is selected, then Selection.Address returns the string "$A$1:$B$4". By means of various parameters one can control the transformation into a string (such as absolute vs. relative address, A1 or R1C1 format, local vs. external reference). AddressLocal functions like Address in that it returns addresses, but it does so in the regional format of the language of the particular country.

If you have an address, whether in A1 or R1C1 format, you can work with the address further with the Application method ConvertFormula, which makes possible, among other things, a conversion between A1 and R1C1 notation and between absolute and relative addressing.

Tip / In the "R1C1 notation" (R for "row," C for "column"), cells are specified by row and column numbers. In "A1 notation" the column letter is followed by the row number. The A1 notation is default in Excel, but you may use the R1C1 notation instead: Tools|Options|General|R1C1 Reference Style.

Named Ranges

Names: This method of the currently active worksheet makes it possible to access named ranges of cells. With Add a new name can be defined or an already existing name changed. What is important is that the range of cells is given absolutely and with a prefixed equal sign, say, Names.Add "rangename", "=$d$5". In what follows, named ranges can be used with Range or in the shorthand form [rangename]. Names("rangename").Delete deletes the definition of a name. With the method Goto you can quickly move the cell pointer into a named cell or region.

Tip / Many short programming examples related to named ranges can be found in the example file Names.xls.

Furthermore, Name objects can be used not only for naming ranges of cells, but also for other tasks. For example, the additional program MS-Query saves its query parameters in a palette of Name objects. Here the Visible property of the objects is set to False, so that these objects do not appear in the form INSERT|NAME|APPLY. The contents of the parameter can be obtained from the Value property.

Caution / Microsoft was apparently not clear as to whether the definition of a new named range should be associated to the workbook or to a special worksheet: On the one hand, it should be possible to use the same name in every worksheet without one instance of the name interfering with another. On the other hand, it is also desirable that a name that has been globally defined be available in all worksheets.
The result is that the first time a name is defined, its definition is valid for the entire workbook. If the same name is used again in another worksheet, then this definition is local for this worksheet. The old definition is valid for all other worksheets. The consequence is that it is sometimes extremely difficult to determine whether a definition of a name must be invoked by ActiveWorkbook.Names(…) or by ActiveSheet.Names(…). In case of doubt, decide in favor of the first variant. There the Names listing contains all local definitions (of the currently active worksheet) as well as all global definitions that are overlaid by the current worksheet.

Notes/Comments

Every cell can have a note stored with it. Setting or retrieving it is accomplished with the method NoteText. Since with Excel methods character strings to be passed as parameters can have a maximum of 255 characters, this method has two parameters by which the start and end position within the note can be given. These parameters make it possible to read or edit notes that are longer than 255 characters.

Starting with Excel 97 notes are also called comments. They are controlled by the new Comment object. (However, NoteText may still be used.) With the method AddComment new comments can be defined. ClearComment deletes existing comments. The listing of Comments for the WorkSheet object helps in tracking down all comments in a worksheet.

Adding and Deleting Ranges of Cells

There are five methods available for deleting cells: ClearContents deletes only the contents of cells, leaving the format intact. ClearFormats has the opposite effect, clearing only the formatting. ClearNotes deletes the notes associated to the cells. Clear deletes both the formatting and the contents. A quite different effect is exhibited by Delete. With it the cells of a worksheet are made to disappear; the cells to the right or below are promoted to the vacated location(s) (this corresponds to the command EDIT|DELETE).

For inserting new cells into the worksheet there exists the method Insert. It is similar to Delete in that with an optional parameter you can determine whether cells should be shifted to the right or downwards. (When no parameter is given, Excel attempts to figure out the more logical choice.)

Content and Format of Cells

The following paragraphs describe the most important properties of the Range object for setting the content and format of cells. Most of the properties listed in what follows will be used in the usual way in single-celled ranges. Reading the properties in multicelled ranges leads to various results (such as an error or setting the first cell of the range). More standard is the reaction in changing the properties of multicelled ranges. Here the settings of all affected cells are changed.

Value: This property contains the value of the cell (in the case of formulas, the result). Empty cells can be determined with IsEmpty(obj.Value). With the definition of the Value property the content of cells can be changed. Formulas are input as character strings that begin with an equal sign: obj.Value= "=A4". The Value property is the default property. This means that the shorthand obj="=A4" is also permissible. Value2 differs from Value in that dates and currency values are not identified in the formats of Date and Currency, but as floating point numbers. In many cases this simplifies further processing.

Text: This property contains the content of a cell as a character string. Text is distinguished from Value by two particular features: With values, Text returns an appropriately formatted string (while Value returns the value directly, as a number or a date); furthermore, Text can only be read (and not changed). References to cells must be handled with Value.

Characters: With this method one can access individual characters of a text constant in a cell (for example, in order to set the type characteristics of a single character).

FormulaLocal and FormulaR1C1Local: These properties return the formula of a cell in the A1 or R1C1 format (see below) in the local language. In the case of empty cells an empty string is returned, while with formulas with constants the values of the constants are returned. For example, if A5 contains the formula =SUM(A1:A4), then in Germany, say, [A1].FormulaLocal returns the string =SUMME(A1:A4), while [A1].FormulaR1C1Local returns =SUMME(Z(-4)S:Z(-1)S).

Formula, FormulaR1C1: These two related properties return formulas in international (that is, English) syntax in the A1 or R1C1 format. [A1].Formula returns the string =SUM(A1:A4), while [A1].FormulaR1C1 returns = SUM(R[-4]C:R[-1]C).

Formula returns or expects the formula in English. The formula is also saved internally in this format and is displayed with the properties of the local language only in the Excel interface. A formula that is displayed in German Excel in a worksheet as =Euroconvert(1, 2; "DEM"; "EUR";WAHR) corresponds to the Formula character string "=Euroconvert(1.2, 'DEM', 'EUR', TRUE)" (period instead of comma for the decimal point, commas instead of semicolons as separators, TRUE instead of WAHR).

HasFormula: This property tells whether a formula exists in a cell (True or False).

Font: This property refers to the Font object, which determines a number of properties of the typeface in a cell, such as Name (of the font), Size, Bold, Italic.

Orientation, HorizontalAlignment, VerticalAlignment, WrapText: These properties determine the orientation of the text (horizontal or vertical), the justification (left/centered/right/justified or top/middle/bottom), and line breaking (true or false). New in Excel 97 was the possibility of using Orientation to give an angle in the range −90° to 90° for the orientation of text. Zero degrees corresponds to normal horizontal text, with the angle being determined from this position in the counterclockwise direction (the standard in mathematics). With 45 the text runs diagonally up from left to right, while −45 yields text running down and to the right.

With IndentLevel one can determine how far to the right the content of a cell should be shifted (the permissible range is 0 to 15).

ColumnWidth, RowHeight: These properties determine the width of the entire column and the height of the entire row.

Borders: This method refers to six Border objects (left/right/above/below and diagonally up and down) whose properties control the appearance of the border: LineStyle, Weight, Color.

BorderAround: With this method the entire border can be set.

Formatting of Numbers (NumberFormat, NumberFormatLocal, and Style)

NumberFormat returns the number format of the cell as a character string. NumberFormatLocal carries out the same task, but the string returned conforms to the conventions of the local language. Finally, Style refers to a formatting template (Style object).

To obtain a fuller understanding of the situation it would be a good idea to begin with styles. As was shown already in the introductory example back in Chapter 1, a style can be used to set a number of format characteristics of a cell, such as the font, text orientation, and color. Most formatting instructions are easily understood, and so in this section we shall limit ourselves to a discussion of number formats.

In VBA, styles are invoked as Style objects. Every Excel file (Workbook object) can use Styles to access available styles in the file. Some format templates are predefined (Builtin=True) and are thus always available for use. The following loop returns a table of all such styles.

Dim s As Style

For Each s In ThisWorkbook.Styles

If s.BuiltIn = True Then

Debug.Print s.Name, s.NumberFormat

End If

Next

Predefined Styles

NAME / NUMBERFORMAT
Comma / _(* #,##0.00_);_(* (#,##0.00);_(* "-"_);_(*@_)
Comma [0] / _(* #,##0_);_(* (#,##0);_(* "-"_);_(*@_)
Currency / _($* #,##0.00_);_($* (#,##0.00);_($* "-"_);_(*@_)
Currency [0] / _($* #,##0_);_($* (#,##0);_($* "-"_);_(*@_)
Normal / General
Percent / 0%
Tip / In the English version of Excel the properties Name and NameLocal as well as NumberFormat and NumberFormatLocal contain identical character strings. However, in international versions this is not the case. There the Local properties contain the region-specific settings, which take precedence over the international settings. For example, in the German version NameLocal contains "Währung" instead of "Currency". The connection between basic properties and their Local variants is unfortunately extremely poorly documented.

The difference between Comma and Comma [0] and between Currency and Currency [0] is that in each case the first variant displays two places to the right of the decimal point, while the [0] variant displays none.

All cells that are not otherwise explicitly formatted are automatically formatted with the style Styles("normal"). It is not possible to define the Style property of a cell to be Nothing. Every cell must be formatted with one style or another.

When you format a cell directly, this format takes precedence over the settings of the overall style. However, the style remains valid for all formatting that is not directly altered.

With the currency, percent, and comma style buttons in the formatting toolbar the style in the affected cell can be changed to Comma, Currency, or Percent.

Tip / If you use the euro add-in, then a further style is defined. Euro is used for Name and NameLocal. The NumberFormat[Local] character strings look as follows:
_-* #.##0, 00 [$€ -1]_-;-* #.##0, 00 [$€ -1]_-;_-* "-"?? [$€ -1]_-

Let us proceed to the property NumberFormat, which is used for styles (Style object) as well as for direct cell formatting (Range object). In the case of an unformatted cell, NumberFormat contains the character string "General", which is based on the style Normal. However, "General" is an exception. As a rule, NumberFormat is set by a rather horrifying string.

Here is some brief information on constructing this string. It normally consists of four parts, separated by semicolons:

positive;negative;zero;strings

The first part is concerned with positive numbers, the second with negative numbers, the third with the value zero, and the fourth with character strings. If you provide only the first part, then all numbers will be formatted according to this format. Strings will be formatted in the standard way (flush left, without indentation).

The following list describes the meaning of the most important symbols in NumberFormat:

; / separates the four parts of the string
# / placeholder for a digit or for all significant digits
0 / placeholder for a digit; if the place is not significant, then instead a 0 is shown. For example, 123.00 or 0.12 is obtained from #0.00
? / placeholder for a digit; if the place is not significant, then a space character is displayed
. / decimal point (displayed according to the local format. In Germany, for example, a comma is displayed; in any case, in NumberFormat a period must be given)
, / thousands separator
% / placeholder for a number in percent format (0.1 is transformed to 10%)
_x / leaves blank space in the size of the following character x; this character itself is not shown; _( means, for example, that a space the size of a parenthesis is left
_ / is often inserted to ensure that numbers are displayed aligned and in fact, independently of whether they are positive or negative (enclosed in parentheses) or whether they are displayed with or without the currency symbol
"x" / indicates a character string between the quotation marks
*x / fills the remaining space with the symbol x; *x can be used only once in each part of the NumberFormat character string
*-# / means that before the number enough hyphens are inserted so that the cell is completely filled, for example, "———— 123"
"DM"* / # means that the symbol DM (the symbol for German marks) appears flush left and the number flush right, with the necessary number of blank characters in between
$ / placeholder for the currency symbol defined in the system settings; this placeholder $ is unfortunately not documented
*@ / placeholder for a character string (for the fourth part of NumberFormat)
Tip / In addition to the symbols defined here there are numerous additional symbols for formatting of dates, times, fractions, exponentials, and so on. Further information about these symbols can be found in the Excel on-line help under "Create a custom number format." (If you have opened the VBA on-line help, then you have to close it, switch to Excel, and summon the Excel on-line help. This is the only way to open the correct help file! The on-line help for NumberFormat is useless.)
In most cases the easiest way to achieve a correct NumberFormat character string is to set a format with FORMAT|CELLS and view the resulting string in the immediate window with Debug.Print ActiveCell.NumberFormat.

The last property left to be explained is NumberFormatLocal. This property's documentation is practically nonexistent. Experiments with the German version of Excel has shown that there is no simple one-to-one translation of code into the local format. For example, the position of the currency symbol is shifted. With the format Currency positive numbers are formatted, according to NumberFormat_($* #,##0.00_) (that is, with the currency symbol before the number). However, according to NumberFormatLocal they are formatted with _−* #.##0,00 € _−(that is, with the currency symbol at the end). NumberFormatLocal has precedence over NumberFormat.

For this reason an attempt to change NumberFormat with program code can lead to curious results. Let us suppose that we have formatted the number 1234 as currency (1.234,00 € ). If the instruction

ActiveCell.NumberFormat = _

Replace(ActiveCell.NumberFormat, "$", """DEM""")

is carried out, to replace the system-setting currency symbol with the string "DEM", then 1.234,00 € is suddenly turned into DEM 1.234,00, that is, the currency sign has been moved from the back to the front. To achieve the desired result you have to execute the following instruction instead:

ActiveCell.NumberFormatLocal = _

Replace(ActiveCell.NumberFormatLocal, "∊", """DEM""")

However, the direct editing of NumberFormatLocal is not an optimal solution, because your program code becomes country-specific, which leads to unexpected (and seldom correct) results with Excel versions in other languages.

Let us consider one more example. You set NumberFormatLocal="T.M.JJJJ" (which returns, for example, 1.12.1999, which is a date in German format; T, M, and J are abbreviations for Tag (day), Monat (month), and Jahr (year)). If you now select NumberFormat, then you get "d/m/yyyy", which is more or less in one-to-one correspondence, even if written with slashes instead of periods.

On the other hand, if you set NumberFormatLocal="TT.MM.JJJJ" (which returns 01.12.1999), then you get NumberFormat="m/d/yy"! The order of month and day has been switched! (The reason is perhaps that Excel recognizes "TT.MM.JJJJ" as a predefined German format and has a table of international correspondences. Perhaps "T.M.JJJJ" does not appear in this table, and the transformation for NumberFormat is accomplished by some other mechanism. All in all, there are many open questions in connection to NumberFormatLocal, questions that could be answered only by Microsoft, which for some reason known perhaps only to its chairman has neglected to provide adequate on-line documentation.)

Find and Replace

With the method rng.Find "character string" you can search for text within a range of cells. The method returns a Range object with the first cell that contains the search text. If Find doesn't find anything, then the method returns Nothing as result.

To replace one character string by another within a range of cells, use rng.Replace "abc", "efg". The method always returns True as result, regardless of whether or how often the first character string is replaced by the second.

Pointer / Extensive information on the numerous optional parameters associated with the Find method, as well as an example of the use of the method, can be found in Chapter 11. These same parameters can be used with Replace.
Please note that you cannot rely on the default settings of the two methods! If any parameter is not specified, the previously used setting is employed. If the search result or replacement is to be independent of previous settings, then you must always specify all parameters!

Extended Search Functions in Excel 2002