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», без необходимости каждый раз заново искать на чём Вы остановились. Поставьте закладку, и сможете в любой момент перейти на страницу, на которой закончили чтение.

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

Интервал:

Закладка:

Сделать

The following procedure demonstrates an If- Thenstructure without an Elseclause. The example deals with time, and VBA uses a date-and-time serial number system similar to Excel's. The time of day is expressed as a fractional value—for example, noon is represented as .5. The VBA Timefunction returns a value that represents the time of day, as reported by the system clock.

In the following example, a message is displayed if the time is before noon. If the current system time is greater than or equal to .5, the procedure ends, and nothing happens.

Sub GreetMe1() If Time < 0.5 Then MsgBox "Good Morning" End Sub

Another way to code this routine is to use multiple statements, as follows:

Sub GreetMe1a() If Time < 0.5 Then MsgBox "Good Morning" End If End Sub

Note that the Ifstatement has a corresponding End Ifstatement. In this example, only one statement is executed if the condition is True. You can, however, place any number of statements between the Ifand End Ifstatements.

If you want to display a different greeting when the time of day is after noon, add another If- Thenstatement, as follows:

Sub GreetMe2() If Time < 0.5 Then MsgBox "Good Morning" If Time >= 0.5 Then MsgBox "Good Afternoon" End Sub

Notice that we used >= (greater than or equal to) for the second If- Thenstatement. This covers the remote chance that the time is precisely 12 p.m.

Another approach is to use the Elseclause of the If- Thenconstruct. Here's an example:

Sub GreetMe3() If Time < 0.5 Then MsgBox "Good Morning" Else _MsgBox "Good Afternoon" End Sub

Notice that we used the line continuation sequence; If- Then- Elseis actually a single statement.

If you need to execute multiple statements based on the condition, use this form:

Sub GreetMe3a() If Time < 0.5 Then MsgBox "Good Morning" ' Other statements go here Else MsgBox "Good Afternoon" ' Other statements go here End If End Sub

If you need to expand a routine to handle three conditions (for example, morning, afternoon, and evening), you can use either three If- Thenstatements or a form that uses ElseIf. The first approach is simpler.

Sub GreetMe4() If Time < 0.5 Then MsgBox "Good Morning" If Time >= 0.5 And Time < 0.75 Then MsgBox "Good Afternoon" If Time >= 0.75 Then MsgBox "Good Evening" End Sub

The value 0.75 represents 6 p.m.—three-quarters of the way through the day and a good point at which to call it an evening.

In the preceding examples, every instruction in the procedure gets executed, even if the first condition is satisfied (that is, it's morning). A more efficient procedure would include a structure that ends the routine when a condition is found to be True. For example, it might display the “Good Morning” message in the morning and then exit without evaluating the other, superfluous conditions. True, the difference in speed is inconsequential when you design a procedure as small as this routine. For more complex applications, however, you need another syntax.

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

Here's how you can use this syntax to rewrite the GreetMeprocedure:

Sub GreetMe5() If Time < 0.5 Then MsgBox "Good Morning" ElseIf Time >= 0.5 And Time < 0.75 Then MsgBox "Good Afternoon" Else MsgBox "Good Evening" End If End Sub

With this syntax, when a condition is True, the conditional statements are executed, and the If- Thenconstruct ends. In other words, the extraneous conditions aren't evaluated. Although this syntax makes for greater efficiency, some find the code to be more difficult to understand.

The following procedure demonstrates yet another way to code this example. It uses nested If- Then- Elseconstructs (without using ElseIf). This procedure is efficient and also easy to understand. Note that each Ifstatement has a corresponding End Ifstatement.

Sub GreetMe6() If Time < 0.5 Then MsgBox "Good Morning" Else If Time >= 0.5 And Time < 0.75 Then MsgBox "Good Afternoon" Else If Time >= 0.75 Then MsgBox "Good Evening" End If End If End If End Sub

The following is another example that uses the simple form of the If- Thenconstruct. This procedure prompts the user for a value for Quantityand then displays the appropriate discount based on that value. Note that Quantityis declared as a Variantdata type. This is because Quantitycontains an empty string (not a numeric value) if InputBoxis cancelled. To keep the procedure simple, it doesn't perform any other error checking. For example, it doesn't ensure that the quantity entered is a non-negative numeric value.

Sub Discount1() Dim Quantity As Variant Dim Discount As Double Quantity = InputBox("Enter Quantity: ") If Quantity = "" Then Exit Sub If Quantity >= 0 Then Discount = 0.1 If Quantity >= 25 Then Discount = 0.15 If Quantity >= 50 Then Discount = 0.2 If Quantity >= 75 Then Discount = 0.25 MsgBox "Discount: " & Discount End Sub

Notice that every If- Thenstatement in this procedure is always executed, and the value for Discountcan change. The final value, however, is the desired value.

The following procedure is the previous one rewritten to use the alternate syntax. In this alternate version, only the If- Thenstatement that evaluates to Trueis actually executed.

Sub Discount2() Dim Quantity As Variant Dim Discount As Double Quantity = InputBox("Enter Quantity: ") If Quantity = "" Then Exit Sub If Quantity >= 0 And Quantity < 25 Then Discount = 0.1 ElseIf Quantity < 50 Then Discount = 0.15 ElseIf Quantity < 75 Then Discount = 0.2 Else Discount = 0.25 End If MsgBox "Discount: " & Discount End Sub

VBA's IIf function

VBA offers an alternative to the If- Thenconstruct: the IIffunction. This function takes three arguments and works much like Excel's IFworksheet function. The syntax is as follows:

IIf(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

The following instruction demonstrates the use of the IIffunction. The message box displays Zeroif cell A1 contains a 0or is empty and displays Nonzeroif cell A1 contains anything else.

MsgBox IIf(Range("A1") = 0, "Zero", "Nonzero")

It's important to understand that the third argument ( falsepart) is always evaluated, even if the first argument ( expr) is True. Therefore, the following statement generates a division-by-zero error if the value of nis 0(zero):

MsgBox IIf(n = 0, 0, 1 / n)

Select Case constructs

The Select Caseconstruct is useful for choosing among three or more options. This construct also works with two options, and it is a good alternative to If- Then- Else. The syntax for Select Caseis as follows:

Select Case testexpression [Case expressionlist-n [instructions-n]] [Case Else [default_instructions]] End Select

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

Интервал:

Закладка:

Сделать

Похожие книги на «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