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

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

Интервал:

Закладка:

Сделать

Each of the 100 elements in this array consists of four components (as specified by the user-defined data type, CustomerInfo). You can refer to a particular component of the record as follows:

Customers(1).Company = "Acme Tools" Customers(1).Contact = "Tim Robertson" Customers(1).RegionCode = 3 Customers(1).Sales = 150674.98

You can also work with an element in the array as a whole. For example, to copy the 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).Company Customers(2).Contact = Customers(1).Contact Customers(2).RegionCode = Customers(1).RegionCode Customers(2).Sales = Customers(1).Sales

Built-in Functions

Like most programming languages, VBA has a variety of built-in functions that simplify calculations and operations. Many VBA functions are similar (or identical) to Excel worksheet functions. For example, the VBA function UCase, which converts a string argument to uppercase, is equivalent to the Excel worksheet function UPPER.

Excel 2019 Power Programming with VBA - изображение 28Appendix A contains a complete list of VBA functions, with a brief description of each. All are thoroughly described in the VBA Help system.

TIP

To get a list of VBA functions while you're writing your code, type VBAfollowed by a period ( .).V BE displays a list of all its members, including functions (see Figure 3.3). The functions are preceded by a green icon. If this technique doesn't work for you, make sure that the Auto List Members option is selected. Choose Tools ➪ Options and then click the Editor tab.

FIGURE 33 Displaying a list of VBA functions in VBE You use functions in VBA - фото 29

FIGURE 3.3 Displaying a list of VBA functions in VBE

You use functions in VBA expressions in much the same way that you use functions in worksheet formulas. Here's a simple procedure that calculates the square root of a variable (using the VBA Sqrfunction), stores the result in another variable, and then displays the result:

Sub ShowRoot() Dim MyValue As Double Dim SquareRoot As Double MyValue = 25 SquareRoot = Sqr(MyValue) MsgBox SquareRoot End Sub

The VBA Sqrfunction is equivalent to the Excel SQRTworksheet function.

You can use many (but not all) of Excel's worksheet functions in your VBA code. The WorksheetFunctionobject, which is contained in the Applicationobject, holds all the worksheet functions that you can call from your VBA procedures.

To use a worksheet function in a VBA statement, just precede the function name with this:

Application.WorksheetFunction

The following example demonstrates how to use an Excel worksheet function in a VBA procedure. Excel's infrequently used ROMANfunction converts a decimal number into a Roman numeral.

Sub ShowRoman() Dim DecValue As Long Dim RomanValue As String DecValue = 1939 RomanValue = Application.WorksheetFunction.Roman(DecValue) MsgBox RomanValue End Sub

When you execute this procedure, the MsgBoxfunction displays the string MCMXXXIX.

Keep in mind that you can't use worksheet functions that have an equivalent VBA function. For example, VBA can't access the Excel SQRTworksheet function because VBA has its own version of that function, Sqr. Therefore, the following statement generates an error:

MsgBox Application.WorksheetFunction.Sqrt(123) 'error

Excel 2019 Power Programming with VBA - изображение 30In Chapter 5, you will discover that you can use VBA to create custom worksheet functions that work just like Excel's built-in worksheet functions.

The MsgBox function

The MsgBoxfunction is one of the most useful VBA functions. Many of the examples in this chapter use this function to display the value of a variable.

This function often is a good substitute for a simple custom dialog box. It's also a useful debugging tool because you can insert MsgBoxfunctions at any time to pause your code and display the result of a calculation or an assignment.

Most functions return a single value, which you assign to a variable. The MsgBoxfunction not only returns a value but also displays a dialog box to which the user can respond. The value returned by the MsgBoxfunction represents the user's response to the dialog box. You can use the MsgBoxfunction even when you have no interest in the user's response but want to take advantage of the message display.

The official syntax of the MsgBoxfunction has five arguments (those in square brackets 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, if any, 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 default is Microsoft Excel.

helpfile: Optional. The name of the Help file associated with the message box.

context: Optional. The context ID of the Help topic, which represents a specific Help topic to display. If you use the context argument, you must also use the helpfile argument.

You can assign the value returned to a variable, or you can use the function by itself without an assignment statement. This example assigns the result to the variable Ans:

Dim Ans As Long Ans = MsgBox("Continue?", vbYesNo + vbQuestion, "Tell me") If Ans = vbNo Then Exit Sub Note that we used the sum of two builtin constants vbYesNo vbQuestion for - фото 31

Note that we used the sum of two built-in constants ( vbYesNo + vbQuestion) for the buttonsargument. Using vbYesNodisplays two buttons in the message box: one labeled Yes and one labeled No. Adding vbQuestionto the argument also displays a question mark icon. When the first statement is executed, Anscontains one of two values, represented by the constant vbYesor vbNo. In this example, if the user clicks the No button, the procedure ends.

See Chapter 12, “Leveraging Custom Dialog Boxes,” for more information about the MsgBoxfunction.

Manipulating Objects and Collections

As an Excel programmer, you'll spend a lot of time working with objects and collections. Therefore, you want to know the most efficient ways to write your code to manipulate these objects and collections. VBA offers two important constructs that can simplify working with objects and collections.

With-End With constructs

For Each-Next constructs

With-End With constructs

The With- End Withconstruct enables you to perform multiple operations on a single object. To start understanding how the With- End Withconstruct works, examine the following procedure, which modifies six properties of a selection's formatting. (The selection is assumed to be a Rangeobject.)

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

Интервал:

Закладка:

Сделать

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