Michael Alexander - Excel 2019 Power Programming with VBA

Здесь есть возможность читать онлайн «Michael Alexander - Excel 2019 Power Programming with VBA» — ознакомительный отрывок электронной книги совершенно бесплатно, а после прочтения отрывка купить полную версию. В некоторых случаях можно слушать аудио, скачать через торрент в формате fb2 и присутствует краткое содержание. Жанр: unrecognised, на английском языке. Описание произведения, (предисловие) а так же отзывы посетителей доступны на портале библиотеки ЛибКат.

Excel 2019 Power Programming with VBA: краткое содержание, описание и аннотация

Предлагаем к чтению аннотацию, описание, краткое содержание или предисловие (зависит от того, что написал сам автор книги «Excel 2019 Power Programming with VBA»). Если вы не нашли необходимую информацию о книге — напишите в комментариях, мы постараемся отыскать её.

Maximize your Excel experience with VBA
Excel 2019 Power Programming with VBA Understanding how to leverage VBA to improve your Excel programming skills can enhance the quality of deliverables that you produce—and can help you take your career to the next level.
Explore fully updated content that offers comprehensive coverage through over 900 pages of tips, tricks, and techniques Leverage templates and worksheets that put your new knowledge in action, and reinforce the skills introduced in the text Improve your capabilities regarding Excel programming with VBA, unlocking more of your potential in the office
 is a fundamental resource for intermediate to advanced users who want to polish their skills regarding spreadsheet applications using VBA.

Excel 2019 Power Programming with VBA — читать онлайн ознакомительный отрывок

Ниже представлен текст книги, разбитый по страницам. Система сохранения места последней прочитанной страницы, позволяет с удобством читать онлайн бесплатно книгу «Excel 2019 Power Programming with VBA», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

ActiveWindow.DisplayGridlines = Not ActiveWindow.DisplayGridlines

The following expression performs a logical Andoperation. The MsgBoxstatement displays Trueonly when Sheet1is the active sheet and the active cell is in Row 1. If either or both of these conditions aren't true, the MsgBoxstatement displays False.

MsgBox ActiveSheet.Name = "Sheet1" And ActiveCell.Row = 1

The following expression performs a logical Oroperation. The MsgBoxstatement displays Truewhen either Sheet1 or Sheet2is the active sheet.

MsgBox ActiveSheet.Name = "Sheet1" Or ActiveSheet.Name = "Sheet2"

Arrays

An array is a group of elements of the same type that have a common name. You refer to a specific element in the array by using the array name and an index number. For example, you can define an array of 12 string variables so that each variable corresponds to the name of a month. If you name the array MonthNames, you can refer to the first element of the array as MonthNames(0), the second element as MonthNames(1), and so on, up to MonthNames(11).

Declaring arrays

You declare an array with a Dimor Publicstatement, just as you declare a regular variable. You can also specify the number of elements in the array. You do so by specifying the first index number, the keyword To, and the last index number—all inside parentheses. For example, here's how to declare an array comprising exactly 100 integers:

Dim MyArray(1 To 100) As Integer

TIP

When you declare an array, you need to specify only the upper index, in which case VBA assumes that 0 is the lower index. Therefore, the two statements that follow have the same effect:

Dim MyArray(0 To 100) As Integer Dim MyArray(100) As Integer

In both cases, the array consists of 101 elements.

By default, VBA assumes zero-based arrays. If you would like VBA to assume that 1 is the lower index for all arrays that declare only the upper index, include the following statement before any procedures in your module:

Option Base 1

Declaring multidimensional arrays

The array examples in the preceding section are one-dimensional arrays. VBA arrays can have up to 60 dimensions, although you'll rarely need more than three dimensions (a 3D array). The following statement declares a 100-integer array with two dimensions (2D):

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

You can think of the preceding array as occupying a 10 × 10 matrix. To refer to a specific element in a 2D array, you need to specify two index numbers. For example, here's how you can assign a value to an element in the preceding array:

MyArray(3, 4) = 125

The following is a declaration for a 3D array that contains 1,000 elements (visualize this array as a cube):

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

Reference an item in the array by supplying three index numbers.

MyArray(4, 8, 2) = 0

Declaring dynamic arrays

A dynamic array doesn't have a preset number of elements. You declare a dynamic array with a blank set of parentheses.

Dim MyArray() As Integer

Before you can use a dynamic array in your code, however, you must use the ReDimstatement to tell VBA how many elements are in the array. You can use a variable to assign the number of elements in an array. Often the value of the variable isn't known until the procedure is executing. For example, if the variable xcontains a number, you can define the array's size by using this statement:

ReDim MyArray (1 To x)

You can use the ReDimstatement any number of times, changing the array's size as often as you need. When you change an array's dimensions, the existing values are destroyed. If you want to preserve the existing values, use ReDim Preserve. Here's an example:

ReDim Preserve MyArray (1 To y)

Arrays crop up later in this chapter when we discuss looping (see the section “Looping blocks of instructions”).

Object Variables

An object variable is one that represents an entire object, such as a range or a worksheet. Object variables are important for two reasons.

They can simplify your code significantly.

They can make your code execute more quickly.

Object variables, like normal variables, are declared with the Dimor Privateor Publicstatement. For example, the following statement declares InputAreaas a Rangeobject variable:

Dim InputArea As Range

Use the Setkeyword to assign an object to the variable. Here's an example:

Set InputArea = Range("C16:E16")

To see how object variables simplify your code, examine the following procedure, which doesn't use an object variable:

Sub NoObjVar() Worksheets("Sheet1").Range("A1").Value = 124 Worksheets("Sheet1").Range("A1").Font.Bold = True Worksheets("Sheet1").Range("A1").Font.Italic = True Worksheets("Sheet1").Range("A1").Font.Size = 14 Worksheets("Sheet1").Range("A1").Font.Name = "Cambria" End Sub

This routine enters a value into cell A1 of Sheet1 on the active workbook, applies some formatting, and changes the fonts and size. That's a lot of typing. To reduce wear and tear on your fingers (and make your code more efficient), you can condense the routine with an object variable.

Sub ObjVar() Dim MyCell As Range Set MyCell = Worksheets("Sheet1").Range("A1") MyCell.Value = 124 MyCell.Font.Bold = True MyCell.Font.Italic = True MyCell.Font.Size = 14 MyCell.Font.Name = "Cambria" End Sub

After the variable MyCellis declared as a Rangeobject, the Setstatement assigns an object to it. Subsequent statements can then use the simpler MyCellreference in place of the lengthy Worksheets("Sheet1").Range("A1")reference.

TIP

After an object is assigned to a variable, VBA can access it more quickly than it can a normal, lengthy reference that has to be resolved. So, when speed is critical, use object variables. One way to think about code efficiency is in terms of dot processing . Every time VBA encounters a dot, as in Sheets(1).Range("A1"), it takes time to resolve the reference. Using an object variable reduces the number of dots to be processed. The fewer the dots, the faster the processing time. Another way to improve the speed of your code is by using the With- End Withconstruct, which also reduces the number of dots to be processed. We discuss this construct later in this chapter.

The true value of object variables will become apparent when we discuss looping later in this chapter.

User-Defined Data Types

VBA lets you create custom, or user-defined , data types. A user-defined data type can ease your work with some types of data. For example, if your application deals with customer information, you may want to create a user-defined data type named CustomerInfo.

Type CustomerInfo Company As String Contact As String RegionCode As Long Sales As Double End Type

NOTE

You define custom data types at the top of your module, before any procedures.

After you create a user-defined data type, you use a Dimstatement to declare a variable as that type. Usually, you define an array. Here's an example:

Dim Customers(1 To 100) As CustomerInfo

Читать дальше
Тёмная тема
Сбросить

Интервал:

Закладка:

Сделать

Похожие книги на «Excel 2019 Power Programming with VBA»

Представляем Вашему вниманию похожие книги на «Excel 2019 Power Programming with VBA» списком для выбора. Мы отобрали схожую по названию и смыслу литературу в надежде предоставить читателям больше вариантов отыскать новые, интересные, ещё непрочитанные произведения.


Michael Alexander - Confessions of a Male Nurse
Michael Alexander
Michael Savage - Abuse of Power
Michael Savage
Michael C. Hyter - The Power of Choice
Michael C. Hyter
Elizabeth Power - A Clash with Cannavaro
Elizabeth Power
Michael Alexander Müller - Ein Tropfen in der Zeit
Michael Alexander Müller
Michael Alexander Müller - Aufbruch / Inqilab
Michael Alexander Müller
Michael Alexander Müller - Prinzenpack
Michael Alexander Müller
Michael Carroll - Absolute Power
Michael Carroll
Michael Grant - The Power
Michael Grant
Отзывы о книге «Excel 2019 Power Programming with VBA»

Обсуждение, отзывы о книге «Excel 2019 Power Programming with VBA» и просто собственные мнения читателей. Оставьте ваши комментарии, напишите, что Вы думаете о произведении, его смысле или главных героях. Укажите что конкретно понравилось, а что нет, и почему Вы так считаете.

x