Excel vba страница с текстом

Текст — это функция рабочего листа в Excel, но ее также можно использовать в VBA при использовании свойства диапазона. Эта функция похожа на функцию Worksheet и принимает такое же количество аргументов, которые представляют собой значения, которые необходимо преобразовать, и указанный числовой формат.

Оглавление

  • Текстовая функция Excel VBA
    • Примеры текстовой функции VBA в Excel
      • Пример №1
      • Пример #2
    • Применить форматирование к ячейкам
    • Рекомендуемые статьи

Текстовая функция Excel VBA

ТЕКСТ — это функция, доступная на рабочем листе, но, к сожалению, это не встроенная функция в Excel VBA. Вместо этого нам нужно использовать объект класса функции рабочего листа в VBA для доступа к этой функции. Текст функция в экселе преобразует значение в указанный числовой формат.

Одна из проблем с этой функцией — аргументы. Всякий раз, когда мы используем функцию рабочего листа VBAФункция рабочего листа VBAФункция рабочего листа в VBA используется, когда нам нужно сослаться на конкретный рабочий лист. Когда мы создаем модуль, код запускается на текущем активном листе рабочей книги, но мы можем использовать функцию рабочего листа для запуска кода в определенном классе рабочего листа.Читать далее, мы не видим четкого синтаксиса. как в нашем рабочем листе. Вместо этого он просто говорит «Arg1» и «Arg2».

текстовая функция vba

Примеры текстовой функции VBA в Excel

Ниже приведены примеры функций Excel VBA TEXT.

.free_excel_div{фон:#d9d9d9;размер шрифта:16px;радиус границы:7px;позиция:относительная;margin:30px;padding:25px 25px 25px 45px}.free_excel_div:before{content:»»;фон:url(центр центр без повтора #207245;ширина:70px;высота:70px;позиция:абсолютная;верх:50%;margin-top:-35px;слева:-35px;граница:5px сплошная #fff;граница-радиус:50%} Вы можете скачать этот текстовый шаблон VBA Excel здесь — Текстовый шаблон VBA Excel

Пример №1

Позвольте мне показать вам простой пример TEXT в VBA Excel. Но сначала взгляните на приведенный ниже код в Visual BasicCode. В Visual Basic код VBA относится к набору инструкций, написанных пользователем на языке программирования приложений Visual Basic в редакторе Visual Basic (VBE) для выполнения определенной задачи. Подробнее.

Код:

Sub Text_Example1() Dim FormattingValue As String Dim FormattingResult As String FormattingValue = 0,564 FormattingResult = WorksheetFunction.Text(FormattingValue, «hh:mm:ss AM/PM») MsgBox FormattingResult End Sub

пример текста vba 1.1

Во-первых, мы объявили две переменные в виде строки в VBA.

Dim FormattingValue As String Dim FormattingResult As String

Для первой переменной мы присвоили номер форматирования, который нам нужно отформатировать.

Значение форматирования = 0,564

Теперь для другой переменной мы назначили функцию ТЕКСТ.

FormattingResult = WorksheetFunction.Text(FormattingValue, «чч:мм:сс AM/PM»)

Если вы заметили, мы применили форматирование времени, то есть «чч:мм:сс AM/PM».

Затем, наконец, мы применили окно сообщения VBA. Функция VBA MsgBox — это функция вывода, которая отображает обобщенное сообщение, предоставленное разработчиком. Этот оператор не имеет аргументов, и персонализированные сообщения в этой функции записываются в двойных кавычках, а для значений предоставляется ссылка на переменную. Подробнее, чтобы показать результат.

MsgBox ФорматированиеРезультат

Когда мы запустим функцию кода ТЕКСТ, мы применим формат времени к числу 0,564 и отобразим результат ниже.

пример текста vba 1.3

Итак, мы получили время как «13:32:10».

Пример #2

Как и в примере с форматом даты, в этом примере мы внесли небольшие изменения. Ниже приведен код.

Код:

Sub Text_Example2() Dim FormattingValue As String Dim FormattingResult As String FormattingValue = 43585 FormattingResult = WorksheetFunction.Text(FormattingValue, «DD-MMM-YYYY») MsgBox FormattingResult End Sub

пример текста vba 2.1

Из предыдущего кода мы изменили значение форматирования с 0,565 на 43585 и изменили стиль форматирования на «ДД-МММ-ГГГГ».

Он применит форматирование к числу 43585 в качестве даты, и результат будет следующим.

пример 2.2

Применить форматирование к ячейкам

Мы видели простые примеры. Теперь посмотрим, как работать с ячейками на листе. Для этого примера посмотрите на данные ниже.

пример 3.1

Для всех этих чисел нам нужно применить формат времени. Этот код применит форматирование.

Код:

Sub Text_Example3() Dim k As Integer For k = 1 To 10 Cells(k, 2).Value = WorksheetFunction.Text(Cells(k, 1).Value, «hh:mm:ss AM/PM») Next k End Саб

пример 3.2

Этот код будет проходить через 10 ячеек и применять форматирование ниже.

пример 3.3

Используя функцию VBA TEXT, мы можем применить форматирование чисел к ячейкам.

Рекомендуемые статьи

Эта статья была руководством по текстовой функции VBA. Мы обсудили использование функции «Текст» в Excel VBA и несколько практических примеров. Кроме того, вы можете узнать больше о VBA из следующих статей:

  • Объект коллекции VBA
  • Текстовое поле в VBA
  • Функция InStr в VBA

Работа с текстом в коде VBA Excel. Функции, оператор & и другие ключевые слова для работы с текстом. Примеры использования некоторых функций и ключевых слов.

Функции для работы с текстом

Основные функции для работы с текстом в VBA Excel:

Функция Описание
Asc(строка) Возвращает числовой код символа, соответствующий первому символу строки. Например: MsgBox Asc(«/Stop»). Ответ: 47, что соответствует символу «/».
Chr(код символа) Возвращает строковый символ по указанному коду. Например: MsgBox Chr(47). Ответ: «/».
Format(Expression, [FormatExpression], [FirstDayOfWeek], [FirstWeekOfYear]) Преобразует число, дату, время в строку (тип данных Variant (String)), отформатированную в соответствии с инструкциями, включенными в выражение формата. Подробнее…
InStr([начало], строка1, строка2, [сравнение]) Возвращает порядковый номер символа, соответствующий первому вхождению одной строки (строка2) в другую (строка1) с начала строки. Подробнее…
InstrRev(строка1, строка2, [начало, [сравнение]]) Возвращает порядковый номер символа, соответствующий первому вхождению одной строки (строка2) в другую (строка1) с конца строки. Подробнее…
Join(SourceArray,[Delimiter]) Возвращает строку, созданную путем объединения нескольких подстрок из массива. Подробнее…
LCase(строка) Преобразует буквенные символы строки в нижний регистр.
Left(строка, длина) Возвращает левую часть строки с заданным количеством символов. Подробнее…
Len(строка) Возвращает число символов, содержащихся в строке.
LTrim(строка) Возвращает строку без начальных пробелов (слева). Подробнее…
Mid(строка, начало, [длина]) Возвращает часть строки с заданным количеством символов, начиная с указанного символа (по номеру). Подробнее…
Replace(expression, find, replace, [start], [count], [compare]) Возвращает строку, полученную в результате замены одной подстроки в исходном строковом выражении другой подстрокой указанное количество раз. Подробнее…
Right(строка, длина) Возвращает правую часть строки с заданным количеством символов. Подробнее…
RTrim(строка) Возвращает строку без конечных пробелов (справа). Подробнее…
Space(число) Возвращает строку, состоящую из указанного числа пробелов. Подробнее…
Split(Expression,[Delimiter],[Limit],[Compare]) Возвращает одномерный массив подстрок, извлеченных из указанной строки с разделителями. Подробнее…
StrComp(строка1, строка2, [сравнение]) Возвращает числовое значение Variant (Integer), показывающее результат сравнения двух строк. Подробнее…
StrConv(string, conversion) Изменяет регистр символов исходной строки в соответствии с заданным параметром «conversion». Подробнее…
String(число, символ) Возвращает строку, состоящую из указанного числа символов. В выражении «символ» может быть указан кодом символа или строкой, первый символ которой будет использован в качестве параметра «символ». Подробнее…
StrReverse(строка) Возвращает строку с обратным порядком следования знаков по сравнению с исходной строкой. Подробнее…
Trim(строка) Возвращает строку без начальных (слева) и конечных (справа) пробелов. Подробнее…
UCase(строка) Преобразует буквенные символы строки в верхний регистр.
Val(строка) Возвращает символы, распознанные как цифры с начала строки и до первого нецифрового символа, в виде числового значения соответствующего типа. Подробнее…
WorksheetFunction.Trim(строка) Функция рабочего листа, которая удаляет все лишние пробелы (начальные, конечные и внутренние), оставляя внутри строки одиночные пробелы.

В таблице перечислены основные функции VBA Excel для работы с текстом. С полным списком всевозможных функций вы можете ознакомиться на сайте разработчика.

Ключевые слова для работы с текстом

Ключевое слово Описание
& Оператор & объединяет два выражения (результат = выражение1 & выражение2). Если выражение не является строкой, оно преобразуется в Variant (String), и результат возвращает значение Variant (String). Если оба выражения возвращают строку, результат возвращает значение String.
vbCrLf Константа vbCrLf сочетает в себе возврат каретки и перевод строки (Chr(13) + Chr(10)) и переносит последующий текст на новую строку (результат = строка1 & vbCrLf & строка2).
vbNewLine Константа vbNewLine в VBA Excel аналогична константе vbCrLf, также сочетает в себе возврат каретки и перевод строки (Chr(13) + Chr(10)) и переносит текст на новую строку (результат = строка1 & vbNewLine & строка2).

Примеры

Вывод прямых парных кавычек

Прямые парные кавычки в VBA Excel являются спецсимволами и вывести их, заключив в самих себя или в одинарные кавычки (апострофы), невозможно. Для этого подойдет функция Chr:

Sub Primer1()

    ‘Вывод одной прямой парной кавычки

MsgBox Chr(34)

    ‘Отображение текста в прямых кавычках

MsgBox Chr(34) & «Волга» & Chr(34)

    ‘Вывод 10 прямых парных кавычек подряд

MsgBox String(10, Chr(34))

End Sub

Смотрите интересное решение по выводу прямых кавычек с помощью прямых кавычек в первом комментарии.

Отображение слов наоборот

Преобразование слова «налим» в «Милан»:

Sub Primer2()

Dim stroka

    stroka = «налим»

    stroka = StrReverse(stroka) ‘милан

    stroka = StrConv(stroka, 3) ‘Милан

MsgBox stroka

End Sub

или одной строкой:

Sub Primer3()

MsgBox StrConv(StrReverse(«налим»), 3)

End Sub

Преобразование слова «лето» в «отель»:

Sub Primer4()

Dim stroka

    stroka = «лето»

    stroka = StrReverse(stroka) ‘отел

    stroka = stroka & «ь» ‘отель

MsgBox stroka

End Sub

или одной строкой:

Sub Primer5()

MsgBox StrReverse(«лето») & «ь»

End Sub

Печатная машинка

Следующий код VBA Excel в замедленном режиме посимвольно печатает указанную строку на пользовательской форме, имитируя печатную машинку.

Для реализации этого примера понадобится пользовательская форма (UserForm1) с надписью (Label1) и кнопкой (CommandButton1):

Пользовательская форма с элементами управления Label и CommandButton

Код имитации печатной машинки состоит из двух процедур, первая из которых замедляет выполнение второй, создавая паузу перед отображением очередного символа, что и создает эффект печатающей машинки:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

Sub StopSub(Pause As Single)

Dim Start As Single

Start = Timer

    Do While Timer < Start + Pause

       DoEvents

    Loop

End Sub

Private Sub CommandButton1_Click()

Dim stroka As String, i As Byte

stroka = «Печатная машинка!»

Label1.Caption = «»

    For i = 1 To Len(stroka)

        Call StopSub(0.25) ‘пауза в секундах

        ‘следующая строка кода добавляет очередную букву

        Label1.Caption = Label1.Caption & Mid(stroka, i, 1)

    Next

End Sub

Обе процедуры размещаются в модуле формы. Нажатие кнопки CommandButton1 запустит замедленную печать символов в поле надписи, имитируя печатную машинку.


При помощи этого макроса вы можете скачать текст с выбранной страницы веб-сайта:

Sub ЗагрузкаТекстаВебСтраницы()
    Set IE = CreateObject("InternetExplorer.Application"):    ' загружаем браузер Internet Explorer
    On Error Resume Next
    addr$ = "http://excelvba.ru/services"    ' указываем адрес сайта (веб-страницы), текст которой загружаем

    IE.Navigate addr$    ' загружаем сайт
     While IE.busy Or (IE.readyState <> 4): DoEvents: Wend    ' ждем, пока загрузится страница
    ' Set ieDoc = IE.Document    ' ссылка на открытый документ

    txt$ = IE.Document.body.innerText    ' считываем текст веб-страницы в текстовую переменную
    
    '[a1] = txt$ ' помещаем текст веб-страницы на лист Excel
    IE.Quit: Set IE = Nothing    ' закрываем браузер
    
    MsgBox txt$, vbInformation, "Текст веб-страницы " & addr$ ' выводим сообщение с текстом с сайта
End Sub

То же самое — но в виде функции:

Function WebPageText(ByVal sURL As String) As String
    On Error Resume Next
    Set IE = CreateObject("InternetExplorer.Application"):    ' загружаем браузер Internet Explorer
    IE.Navigate sURL    ' загружаем сайт
    While IE.busy Or (IE.readyState <> 4): DoEvents: Wend    ' ждем, пока загрузится страница
    WebPageText = IE.Document.body.innerText    ' считываем текст веб-страницы
    IE.Quit: Set IE = Nothing    ' закрываем браузер
End Function

Если же нужен HTML код страницы, то используйте такой вариант

' создаём объект IE
Set IE = CreateObject("InternetExplorer.Application")
 
' переходим по ссылке в браузере
IE.Navigate URL
 
' ждём, пока страница загрузиться
While IE.Busy Or (IE.ReadyState <> 4): DoEvents: Wend
 
' считываем HTML код веб-страницы в текстовую переменную
Code$ = IE.Document.body.innerHtml  

Пример использования этой функции для загрузки текста страниц из интернета:

Sub ПримерИспользованияФункции_WebPageText()
    ' считываем текст страницы <a href="http://excelvba.ru/services" title="http://excelvba.ru/services">http://excelvba.ru/services</a> в переменную txt
    txt = WebPageText("http://excelvba.ru/services")
    ' получаем путь к папке "Рабочий стол"
    ПутьКРабочемуСтолу = CreateObject("WScript.Shell").SpecialFolders("Desktop")
    ' сохраняем текст из переменной txt в файл PageText.txt на рабочем столе
    SaveTXTfile ПутьКРабочемуСтолу & "PageText.txt", txt
    ' открываем созданный текстовый файл в Excel
    Workbooks.OpenText ПутьКРабочемуСтолу & "PageText.txt", , , xlDelimited
End Sub
 
Function SaveTXTfile(ByVal filename As String, ByVal txt As String) As Boolean
    On Error Resume Next: Err.Clear
    Set fso = CreateObject("scripting.filesystemobject")
    Set ts = fso.CreateTextFile(filename, True)
    ts.Write txt: ts.Close
    SaveTXTfile = Err = 0
    Set ts = Nothing: Set fso = Nothing
End Function

PS: Если вас интересует ИСХОДНЫЙ КОД страницы — используйте эту функцию: http://excelvba.ru/code/GetHTTPResponse

  • 70152 просмотра

Не получается применить макрос? Не удаётся изменить код под свои нужды?

Оформите заказ у нас на сайте, не забыв прикрепить примеры файлов, и описать, что и как должно работать.

Excel VBA Tutorial about how to setup pages, print and print previewIf you’re anything like me, you probably spend a substantial amount of time working in Excel. The results of your efforts are probably beautiful and useful Excel worksheets.

From time-to-time, you probably share the results of your work in Excel with others. 2 of the most common ways of achieving this are:

  • Printing your worksheets.
  • Saving your files as PDF.

Printing an Excel file may be the last step you take prior to distributing your work. Knowing how to appropriately set up and print your files is, therefore, very important. You probably don’t want to cause a bad impression simply because your file doesn’t print properly.

Correctly setting up and printing your Excel files takes some time. The good news is that you can easily automate most of these activities using VBA. And if that’s your purpose, then this VBA Tutorial is likely to be of help.

My purpose with this blog post is to provide you with the most relevant information you need to appropriately set up your Excel files for printing and, as required, print or display a print preview.

  • The first section of this Tutorial introduces and explains several VBA constructs that are commonly used when printing Excel files.
  • In the second section, I go through 2 detailed VBA code examples that you can easily adjust and start using today.

This Excel VBA Print Tutorial is accompanied by an example workbook. This workbook contains the example VBA Sub procedures I explain below. It also has the data and worksheets that appear in the screenshots throughout this post. You can get immediate free access to this example workbook by clicking the button below.

Get immediate free access to the Excel VBA Print Tutorial workbook example

The following Table of Contents lists the main topics I cover in this blog post:

Let’s start by taking a very basic look at the process your VBA code usually follows when printing from Excel or displaying a print preview:

How To Print Or Display Print Preview In Excel With VBA

Generally, you can print or display a print preview with VBA in the following 2 easy steps:

  1. Specify the page and print setup.
  2. Print or display the print preview.

This VBA Tutorial covers these 2 steps in detail. Let’s start by looking at the VBA construct you use to print Excel worksheets, the…

PrintOut Method

The PrintOut method allows you to print the referenced object. However, you can’t generally print hidden sheets.

Backstage View and Print

You can work with the PrintOut method at several different levels. In other words, you can refer to different objects. The object you refer to determines what Excel prints.

Because of the above, the Microsoft Dev Center lists different versions of the PrintOut method. The following are the most relevant:

  • Workbook.PrintOut.
  • Window.PrintOut.
  • Sheets.PrintOut.
  • Worksheets.PrintOut.
  • Worksheet.PrintOut.
  • Range.PrintOut.
  • Charts.PrintOut.
  • Chart.PrintOut.

Generally, the syntax and parameters are always the same. That is regardless of the object you’re printing.

The basic syntax of the PrintOut method is as follows:

expression.PrintOut(From, To, Copies, Preview, ActivePrinter, PrintToFile, Collate, PrToFileName, IgnorePrintAreas)

“expression” is the object you want to print.

As shown above, PrintOut has the following 9 parameters. These arguments are optional.

  1. From.
  2. To.
  3. Copies.
  4. Preview.
  5. ActivePrinter.
  6. PrintToFile.
  7. Collate.
  8. PrToFileName.
  9. IgnorePrintAreas.

In some cases, the IgnorePrintAreas parameter isn’t applicable. This is the case when you apply the PrintOut method to the Window (Window.PrintOut), Range (Range.PrintOut) and Chart (Chart.PrintOut) objects. In such cases, the basic syntax looks roughly as follows:

expression.PrintOut(From, To, Copies, Preview, ActivePrinter, PrintToFile, Collate, PrToFileName)

Let’s take a closer look at the 9 parameters I list above:

Parameters #1 And #2: From And To

You can use the From and To parameters to specify the pages that Excel prints. More precisely, you can specify the following:

  • From:
    • The page at which Excel starts printing.
    • If you omit the From parameter, Excel starts printing at the beginning.
  • To:
    • The last page Excel prints.
    • If you don’t specify the To argument, Excel prints stops printing after the last page.

Backstage View and Print and Pages From To

Parameter #3: Copies

The Copies parameter allows you to specify how many copies Excel prints. The default, which Excel uses if you fail to specify Copies, is printing 1 copy.

Backstage View and Print and Copies

Parameter #4: Preview

Generally, when you print with VBA, Excel doesn’t display the print preview prior to printing. This means that Visual Basic for Applications generally prints the relevant object immediately.

In other words, Preview is set to False by default.

If you want to invoke the print preview prior to Excel printing, set Preview to True.

Full screen print preview

Parameter #5: ActivePrinter

You use the ActivePrinter parameter to set the name of the active printer.

Backstage View and Printer

Parameters #6 And #8: PrintToFile And PrToFileName

By default, Excel doesn’t print to a file. In other words, PrintToFile is set to False.

If you want to print to a file, you must set the PrintToFile parameter to True.

Backstage View and Print and Printer and Print to File

The PrToFileName is relevant if you set PrintToFile to True. In such a case:

  • You can use PrToFileName to specify the name of the output file.
  • If you don’t specify a filename with the PrToFileName parameter, Excel prompts the user to enter the name of the file it should print to.

Parameter #7: Collate

Collating is useful if you’re printing multiple copies. If you use Excel’s collation feature, Excel automatically organizes the printed sheets into logically organized sets. Since the sets of printouts are logically organized, you generally don’t have to rearrange or reorganize them into separate packages.

Backstage View and Print and Collated

Let’s assume that you’re printing 3 copies of a worksheet that has 3 pages. Excel organizes the printed sheets differently depending on whether you choose to collate or not. More specifically:

The Collate argument allows you to control this setting, as follows:

  • True: Collate.
  • False: Don’t collate.

Parameter #9: IgnorePrintAreas

By default, Excel considers any print areas set for the relevant object.

When applicable, you can use the IgnorePrintAreas parameter to determine whether Excel ignores (or not) these print areas. The values that IgnorePrintAreas can take are as follows:

  • True: Ignore print areas.
  • False: Don’t ignore print areas.

Backstage View and Print and Ignore Print Areas

PrintPreview Method

Parameter #4 of the PrintOut method I explain in the previous section allows you to display the print preview prior to printing.

You can, however, get Excel to display the print preview without having to invoke the PrintOut method. The following methods show a preview of the applicable object printout:

  • Workbook.PrintPreview.
  • Window.PrintPreview.
  • Sheets.PrintPreview.
  • Worksheets.PrintPreview.
  • Worksheet.PrintPreview.
  • Range.PrintPreview.
  • Charts.PrintPreview.
  • Chart.PrintPreview.

The basic syntax of the PrintPreview method is as follows:

expression.PrintPreview(EnableChanges)

The following definitions apply:

  • expression: Object whose printout you want to preview.
  • EnableChanges: Optional parameter. allows you to specify whether the user can change page setup options that are available within the print preview screen. You specify this setting as one of the Boolean values True or False. This looks roughly as follows:
    expression.PrintPreview EnableChanges:=True
    expression.PrintPreview EnableChanges:=False
    

PageSetup Object

The PageSetup object holds the description of the page setup.

Ribbon and Page Layout and Page Setup

You generally access the PageSetup object through the PageSetup property. Choose 1 of the following 2 properties depending on which object (worksheet vs. chart) you’re working with:

  • Worksheet.PageSetup property.
  • Chart.PageSetup property.

Therefore, you generally access most page setup attributes through the properties of PageSetup. The PageSetup object has the following 48 properties:

  1. AlignMarginsHeaderFooter.
  2. Application.
  3. BlackAndWhite.
  4. BottomMargin.
  5. CenterFooter.
  6. CenterFooterPicture.
  7. CenterHeader.
  8. CenterHeaderPicture.
  9. CenterHorizontally.
  10. CenterVertically.
  11. Creator.
  12. DifferentFirstPageHeaderFooter.
  13. Draft.
  14. EvenPage.
  15. FirstPage.
  16. FirstPageNumber.
  17. FitToPagesTall.
  18. FitToPagesWide.
  19. FooterMargin.
  20. HeaderMargin.
  21. LeftFooter.
  22. LeftFooterPicture.
  23. LeftHeader.
  24. LeftHeaderPicture.
  25. LeftMargin.
  26. OddAndEvenPagesHeaderFooter.
  27. Order.
  28. Orientation.
  29. Pages.
  30. PaperSize.
  31. Parent.
  32. PrintArea.
  33. PrintComments.
  34. PrintErrors.
  35. PrintGridlines.
  36. PrintHeadings.
  37. PrintNotes.
  38. PrintQuality.
  39. PrintTitleColumns.
  40. PrintTitleRows.
  41. RightFooter.
  42. RightFooterPicture.
  43. RightHeader.
  44. RightHeaderPicture.
  45. RightMargin.
  46. ScaleWithDocHeaderFooter.
  47. TopMargin.
  48. Zoom.

Let’s take a closer look at some (most) of the 48 properties I list above.

The explanations below don’t follow the alphabetical order above. Rather, I categorize the properties per my criteria. Certain properties may, strictly speaking, fall in more than 1 category.

PageSetup Properties Dealing With Print Area, Paper Size, Orientation And Scaling

The following 5 properties allow you to specify paper size, orientation and scaling:

  • #17: PageSetup.FitToPagesTall.
  • #18: PageSetup.FitToPagesWide.
  • #28: PageSetup.Orientation.
  • #30: PageSetup.PaperSize.
  • #32: PageSetup.PrintArea.
  • #48: PageSetup.Zoom.

Let’s take a closer look at each of these properties:

Property #32: PageSetup.PrintArea

Use the PrintArea property to specify the range you want to print. This property is only applicable to worksheets.

Page Setup and Sheet and Print area

The basic syntax you can use to specify the print area is as follows:

PageSetup.PrintArea = rangeA1String

The following definitions apply:

  • PageSetup: PageSetup object.
  • rangeA1String: Range you want to set as print area. You express the print area as a string using A1-style in the language of the macro.

You can set the print area to the entire worksheet by setting the PrintArea property to False or an empty string. In this case, the basic statement structure you use looks roughly as follows:

PageSetup.PrintArea = False
PageSetup.PrintArea = ""

Property #30: PageSetup.PaperSize

The PaperSize property allows you to determine the size of the paper.

Page Setup and Page and Paper size

You do this by setting this property to one of the following 42 XlPaperSize constants.

Name Value Description
xlPaperLetter 1 Letter (8-1/2 in. x 11 in.)
xlPaperLetterSmall 2 Letter Small (8-1/2 in. x 11 in.)
xlPaperTabloid 3 Tabloid (11 in. x 17 in.)
xlPaperLedger 4 Ledger (17 in. x 11 in.)
xlPaperLegal 5 Legal (8-1/2 in. x 14 in.)
xlPaperStatement 6 Statement (5-1/2 in. x 8-1/2 in.)
xlPaperExecutive 7 Executive (7-1/2 in. x 10-1/2 in.)
xlPaperA3 8 A3 (297 mm x 420 mm)
xlPaperA4 9 A4 (210 mm x 297 mm)
xlPaperA4Small 10 A4 Small (210 mm x 297 mm)
xlPaperA5 11 A5 (148 mm x 210 mm)
xlPaperB4 12 B4 (250 mm x 354 mm)
xlPaperB5 13 A5 (148 mm x 210 mm)
xlPaperFolio 14 Folio (8-1/2 in. x 13 in.)
xlPaperQuarto 15 Quarto (215 mm x 275 mm)
xlPaper10x14 16 10 in. x 14 in.
xlPaper11x17 17 11 in. x 17 in.
xlPaperNote 18 Note (8-1/2 in. x 11 in.)
xlPaperEnvelope9 19 Envelope #9 (3-7/8 in. x 8-7/8 in.)
xlPaperEnvelope10 20 Envelope #10 (4-1/8 in. x 9-1/2 in.)
xlPaperEnvelope11 21 Envelope #11 (4-1/2 in. x 10-3/8 in.)
xlPaperEnvelope12 22 Envelope #12 (4-1/2 in. x 11 in.)
xlPaperEnvelope14 23 Envelope #14 (5 in. x 11-1/2 in.)
xlPaperCsheet 24 C size sheet
xlPaperDsheet 25 D size sheet
xlPaperEsheet 26 E size sheet
xlPaperEnvelopeDL 27 Envelope DL (110 mm x 220 mm)
xlPaperEnvelopeC5 28 Envelope C5 (162 mm x 229 mm)
xlPaperEnvelopeC3 29 Envelope C3 (324 mm x 458 mm)
xlPaperEnvelopeC4 30 Envelope C4 (229 mm x 324 mm)
xlPaperEnvelopeC6 31 Envelope C6 (114 mm x 162 mm)
xlPaperEnvelopeC65 32 Envelope C65 (114 mm x 229 mm)
xlPaperEnvelopeB4 33 Envelope B4 (250 mm x 353 mm)
xlPaperEnvelopeB5 34 Envelope B5 (176 mm x 250 mm)
xlPaperEnvelopeB6 35 Envelope B6 (176 mm x 125 mm)
xlPaperEnvelopeItaly 36 Envelope (110 mm x 230 mm)
xlPaperEnvelopeMonarch 37 Envelope Monarch (3-7/8 in. x 7-1/2 in.)
xlPaperEnvelopePersonal 38 Envelope (3-5/8 in. x 6-1/2 in.)
xlPaperFanfoldUS 39 U.S. Standard Fanfold (14-7/8 in. x 11 in.)
xlPaperFanfoldStdGerman 40 German Legal Fanfold (8-1/2 in. x 13 in.)
xlPaperFanfoldLegalGerman 41 German Legal Fanfold (8-1/2 in. x 13 in.)
xlPaperUser 256 User-defined

When setting the PaperSize property, make sure to confirm that the relevant printers support the paper size you want to specify.

The basic syntax of the PaperSize property looks as follows:

PageSetup.PaperSize = xlPaperSizeConstant

The following definitions are applicable:

  • PageSetup: PageSetup object.
  • xlPaperSizeConstant: One of the XlPaperSize constants in the table above.

Property #28: PageSetup.Orientation

You can use the Orientation property to determine the page orientation. PageSetup.Orientation can take either of the following XlPageOrientation constants:

  • xlPortrait (1): Portrait mode.
  • xlLandscape (2): Landscape mode.

Page Setup and Orientation and Portrait or Landscape

The statement structure you can use to set the page orientation to portrait or landscape mode are roughly as follows:

PageSetup.Orientation = xlPortrait
PageSetup.Orientation = xlLandscape

“PageSetup” is a PageSetup object.

Property #48: PageSetup.Zoom

The Zoom property allows you to specify the value by which Excel scales a worksheet for printing. When scaling, Excel retains the aspect ratio of the worksheet.

Page Setup and Page and Scaling and Adjust to % of normal size

You can only apply this property to worksheets. To scale a worksheet with the Zoom property, use the following statement structure:

PageSetup.Zoom = zoom%

The following definitions apply:

  • PageSetup: PageSetup object.
  • zoom%: Percentage by which you want to scale the worksheet. It generally must be between 10% and 400%.

As an alternative to the Zoom property, you can scale a worksheet by using the FitToPagesTall and FitToPagesWide properties I explain below. However, any scaling settings you specify with Zoom prevail over those 2 properties.

Therefore, if you want to scale a worksheet with the FitToPagesTall or FitToPagesWide properties, set Zoom to False with the following statement:

PageSetup.Zoom = False

Properties #17 And #18: PageSetup.FitToPagesTall And PageSetup.FitToPagesWide

Use the FitToPagesTall and FitToPagesWide properties to specify the number of pages tall or wide the worksheet is scaled to.

Page Setup and Page and Scaling and Fit to pages wide by tall

The following 2 restrictions apply to the FitToPagesTall and FitToPagesWide properties:

  • You can generally only apply them to worksheets.
  • If you assign a value to the PageSetup.Zoom property (other than False), they’re ignored. In other words, Zoom prevails over FitToPagesTall and FitToPagesWide.

The basic syntax you can use to work with these properties is as follows:

PageSetup.FitToPagesTall = pages#
PageSetup.FitToPagesWide = pages#

The following definitions are applicable:

  • PageSetup: PageSetup object.
  • pages#: Number of pages you want the worksheet scaled to.

You can generally set values for both the FitToPagesTall and FitToPagesWide properties. You can, however, allow the scaling to be determined by a single of these properties. To do this, set the other property (representing the scaling you don’t want) to False. This looks as follows:

  • Determine the scaling per the FitToPagesWide property only:
    PageSetup.FitToPagesTall = False
    PageSetup.FitToPagesWide = pages#
    
  • Determine the scaling per the FitToPagesTall property only:
    PageSetup.FitToPagesTall = pages#
    PageSetup.FitToPagesWide = False
    

PageSetup Properties Dealing With Printing Order And Basic Page Numbering

In this section, I introduce the following 2 properties:

  • #16: PageSetup.FirstPageNumber.
  • #27: PageSetup.Order.

Let’s look at each of them:

Property #27: PageSetup.Order

The Order property allows you to specify the order in which Excel organizes the pages of a large worksheet. You have 2 ordering options, represented by the following XlOrder constants:

  • xlDownThenOver: First, go down the rows of the worksheet. Then, move over to the right.
  • xlOverThenDown: First, go across the columns. Then, move down the rows.

Page Setup and Sheet and Page order and Down, then over or Over, then down

The following is the basic statement structure you can use to specify either of the values above:

PageSetup.Order = xlDownThenOver
PageSetup.Order = xlOverThenDown

“PageSetup” is a PageSetup object.

Property #16: PageSetup.FirstPageNumber

Use the FirstPageNumber to set the first page number that Excel uses when printing.

Page Setup and Page and First page number

The following is the basic syntax you can use to work with FirstPageNumber:

PageSetup.FirstPageNumber = number#

The following definitions apply:

  • PageSetup: PageSetup object.
  • number#: Number you want to assign. The default value of the FirstPageNumber property is xlAutomatic. You can also set FirstPageNumber to this default value, roughly as follows:
    PageSetup.FirstPageNumber = xlAutomatic
    

PageSetup Properties Dealing With The Printing Of Certain Items

When printing, you can specify the way in which certain items are printed, and if they’re printed at all. The following are the main PageSetup properties you can use for these purposes:

  • #33: PageSetup.PrintComments.
  • #34: PageSetup.PrintErrors.
  • #35: PageSetup.PrintGridlines.
  • #36: PageSetup.PrintHeadings.
  • #37: PageSetup.PrintNotes.
  • #39: PageSetup.PrintTitleColumns.
  • #40: PageSetup.PrintTitleRows.

Let’s take a closer look at each of them:

Properties #33 And #37: PageSetup.PrintComments And PageSetup.PrintNotes

Use the PrintComments property to determine if, and how, comments are printed. You can set PrintComments to any of the following xlPrintLocation constants:

  • xlPrintNoComments (-4142): Don’t print comments.
  • xlPrintSheetEnd (1): Print comments at the end of the sheet.
  • xlPrintInPlace (16): Print comments as displayed on the sheet.

Page Setup and Sheet and Comments

The basic statement structure you can use to specify how comments are printed is as follows:

PageSetup.PrintComments = xlPrintLocationConstant

The following definitions apply:

  • PageSetup: PageSetup object.
  • xlPrintLocationConstant: 1 of the 3 xlPrintLocation constants above.

An alternative, although more restricted, way of handling the printing of comments is by using the PrintNotes property. PrintNotes accepts either of the Boolean Values True and False, as follows:

  • True: Print comments at the end of the sheet.
  • False: Don’t print comments.

The basic statement structure you can use when working with the PrintNotes property is as follows:

PageSetup.PrintNotes = True
PageSetup.PrintNotes = False

“PageSetup” represents a PageSetup object.

Property #34: PageSetup.PrintErrors

The PrintErrors property allows you determine the way in which error values are displayed when printing. You determine how print errors are displayed by setting PrintErrors to any of the following xlPrintErrors constants:

  • xlPrintErrorsDisplayed (0): Display print errors.
  • xlPrintErrorsBlank (1): Display blanks instead of print errors.
  • xlPrintErrorsDash (2): Display print errors as dashes (–).
  • xlPrintErrorsNA (3): Display print errors as not available (#N/A).

Page Setup and Sheet and Cells errors as

Use the following statement structure to assign a value to PageSetup.PrintErrors:

PageSetup.PrintErrors = xlPrintErrorsConstant

The following definitions are applicable:

  • PageSetup: PageSetup object.
  • xlPrintErrorsConstant: Any of the xlPrintErrors constants above.

Property #35: PageSetup.PrintGridlines

You can use the PrintGridlines property to specify whether gridlines are printed. You do this by setting PrintGridlines to one of the Boolean values True or False, as follows:

  • True: Print gridlines.
  • False: Don’t print gridlines.

Page Setup and Sheet and Gridlines

The PrintGridlines property is only applicable to worksheets.

You can use the following rough statement structure for purposes of setting PrintGridlines:

PageSetup.PrintGridlines = True
PageSetup.PrintGridlines = False

“PageSetup” represents a PageSetup object.

Property #36: PageSetup.PrintHeadings

The PrintHeadings property allows you to specify whether row and column headings are printed. To specify the setting you want, set the PrintHeadings to one of the Boolean values True or False, as follows:

  • True: Print headings.
  • False: Don’t print headings.

Page Setup and Sheet and Row and column headings

Considering the above, you can use the following basic statement structure to specify whether headings are printed or not:

PageSetup.PrintHeadings = True
PageSetup.PrintHeadings = False

“PageSetup” is a PageSetup object.

Properties #39 And #40: PageSetup.PrintTitleColumns And PageSetup.PrintTitleRows

The PrintTitleColumns and PrintTitleRows properties allow you to repeat certain rows or columns on each page of a worksheet. More precisely, you can specify the following:

  • PrintTitleColumns: Certain columns appear on the left side of each page.
  • PrintTitleRows: Certain rows appear at the top of each page.

Page Setup and Sheet and Print titles and Rows to repeat at top and Columns to repeat at left

You can only apply these 2 properties to worksheets.

You can use the following basic syntax as guidance when working with the PrintTitleColumns or PrintTitleRows properties:

PageSetup.PrintTitleColumns = columnsA1String
PageSetup.PrintTitleRows = rowsA1String

The following definitions apply:

  • PageSetup: PageSetup object.
  • columnsA1String and rowsA1String: Columns or rows you want to specify as title columns or rows. Express the title rows or columns as a string in A1-style notation in the language of the macro.

Generally, you should specify full rows or columns as title rows or columns. If you specify incomplete rows or columns, Excel automatically expands the range to cover the full row or column.

You can also “turn off” either of these 2 properties by setting them to False or an empty string. This looks roughly as follows:

PageSetup.PrintTitleColumns = False
PageSetup.PrintTitleColumns = ""
PageSetup.PrintTitleRows = False
PageSetup.PrintTitleRows = ""

PageSetup Properties Dealing With Print Quality

The following 3 properties of the PageSetup object deal with print quality matters:

  • #3: PageSetup.BlackAndWhite.
  • #13: PageSetup.Draft.
  • #38: PageSetup.PrintQuality.

These PageSetup settings (usually) differ among printers. As I explain below (for PageSetup.PrintQuality), the macro recorder may help you find what is the appropriate syntax for a certain printer.

Executing the same macro on a different computer/printer may (still) result in an error. In some cases, you may want to consider working with error handler constructs (for ex., wrap the statements with the On Error Resume Next statement) to handle the potential errors caused by these printer setting differences.

When working with PageSetup, the macro recorder usually generates several unnecessary statements that you can delete. You can use the information within this Tutorial to decide which statements are useful to achieve your purposes.

Let’s take a closer look at them:

Property #38: PageSetup.PrintQuality

Use the PrintQuality property to determine the print quality.

Page Setup and Page and Print quality

The PrintQuality property has a single optional parameter: Index. You use index to specify to which of the following you’re referring to:

  • 1: Horizontal print quality.
  • 2: Vertical print quality.

If you don’t use the Index argument, you can set the property to an array with 2 elements. The first element contains the horizontal print quality. The second element contains the vertical print quality.

The basic statement structure you can use to specify the PrintQuality property looks roughly as follows:

PageSetup.PrintQuality(Index) = quality#

The following definitions apply:

  • PageSetup: PageSetup object.
  • quality#: Print quality you want to specify.

In practice, working with the PageSetup.PrintQuality property is trickier than it may seem at first glance. The main reason for this is that the precise specification depends on the printer driver.

In other words, the precise VBA statement you should use usually varies from case to case. You can usually get a good idea of the exact syntax you work with by using the macro recorder.

Property #13: PageSetup.Draft

The Draft property allows you to print as draft. The main consequence of printing as draft is that Excel doesn’t print graphics. This makes the printing process faster and usually requires less ink.

The Draft property takes one of the Boolean values True or False, as follows:

  • True: Print as draft.
  • False: Don’t print as draft.

Page Setup and Sheet and Draft quality

The following statements show the basic structure you can generally use to work with the Draft property:

PageSetup.Draft = True
PageSetup.Draft = False

“PageSetup” represents a PageSetup object.

Property #38: PageSetup.BlackAndWhite

You can use the BlackAndWhite property to print in black and white. This property, however, only applies to worksheets.

BlackAndWhite takes either of the Boolean values, as follows:

  • True: Print in black and white.
  • False: Don’t print in black and white.

Page Setup and Sheet and Black and white

The following statements display the basic structure you can usually work with:

PageSetup.BlackAndWhite = True
PageSetup.BlackAndWhite = False

“PageSetup” is a PageSetup object.

PageSetup Properties Dealing With Margins

The following 7 properties of the PageSetup object refer to margins:

  • #1: PageSetup.AlignMarginsHeaderFooter.
  • #4: PageSetup.BottomMargin.
  • #19: PageSetup.FooterMargin.
  • #20: PageSetup.HeaderMargin.
  • #25: PageSetup.LeftMargin.
  • #45: PageSetup.RightMargin.
  • #47: PageSetup.TopMargin.

I cover each of them in the following sections.

Properties #19 And #20: PageSetup.FooterMargin And PageSetup.HeaderMargin

The PageSetup.HeaderMargin and PageSetup.FooterMargin properties allow you to specify the margin or the header or footer (as appropriate).

You express margins as points measuring the following distances:

  • HeaderMargin: Distance between the top of the page and the header.
  • FooterMargin: Distance between the bottom of the page and footer.

Page Setup and Margins and Header and Footer

The syntax of the HeaderMargin and FooterMargin properties is substantially the same. To specify these margins, use the following statement structure:

PageSetup.HeaderMargin = margin#
PageSetup.FooterMargin = margin#

The following definitions apply:

  • PageSetup: PageSetup object.
  • margin#:
    • Margin, expressed in points.
    • You can use the Application.InchesToPoints or Application.CentimetersToPoints methods to convert a measurement from (i) inches or centimeters, to (ii) points. I explain both methods below.

Property #1: PageSetup.AlignMarginsHeaderFooter

When working with headers and footers, you generally don’t set left and right margins.

However, you can choose whether Excel aligns the header and the footer with the general right and left page margins by using the PageSetup.AlignMarginsHeaderFooter property. AlignMarginsHeaderFooter can take either of the following values:

  • True: Header and footer are aligned with margins.
  • False: Excel doesn’t align the header and footer with the margins.

Page Setup and Header/Footer and Align with page margins

Because of the above, you can use the following statements to determine whether Excel carries out the header and footer alignment:

PageSetup.AlignMarginsHeaderFooter = True
PageSetup.AlignMarginsHeaderFooter = False

“PageSetup” is a PageSetup object.

The setting you choose for this property influences all headers and footers: left, right and center. The following comparison shows how Excel aligns headers and footers when they’re aligned with page margins vs. when they’re not:

AlignMarginsHeaderFooter True False
Left Aligned with left margin. On left side of page, regardless of left margin.
Center Centered between left and right margin. Centered in page, regardless of the margins.
Right Aligned with right margin. On right side of page, regardless of left margin.

Properties #4, #25, #45 And #47: PageSetup.BottomMargin, PageSetup.LeftMargin, PageSetup.RightMargin And PageSetup.TopMargin

The TopMargin, RightMargin, BottomMargin and LeftMargin properties allow you to set margins.

Page Setup and Margins and Top, Right, Bottom, Left

The syntax of these properties is substantially the same. In other words, to set a margin, use the following basic statement structure:

PageSetup.TopMargin = margin#
PageSetup.RightMargin = margin#
PageSetup.BottomMargin = margin#
PageSetup.LeftMargin = margin#

The following definitions apply:

  • PageSetup: PageSetup object.
  • margin#:
    • Margin you’re specifying. When working with these properties, you must express margins in points.
    • If you want to express margins in inches or centimeters, use the Application.InchesToPoints or Application.CentimetersToPoints methods. I cover both methods in their own section below.

PageSetup Properties That Center The Sheet On The Page

Most of the settings within the Margins tab of Excel’s Page Setup dialog box deal directly with margins. I explain the most relevant margin-related VBA properties above.

At the bottom of the Margins tab, there are 2 settings that allow you to specify whether Excel centers the sheet horizontally or vertically when printing.

Page Setup and Margins and Center in page and Horizontally or Vertically

The 2 properties that allow you to specify these settings are as follows:

  • PageSetup.CenterHorizontally.
  • PageSetup.CenterVertically.

Let’s look at each of them:

Property #9: PageSetup.CenterHorizontally

The CenterHorizontally property allows you to determine whether Excel centers the content horizontally on the printed page. You specify this by setting the property to one of the Boolean values True or False, as follows:

  • True: Center.
  • False: Don’t center.

The basic structure of the statements that allow you to do this is as follows:

PageSetup.CenterHorizontally = True
PageSetup.CenterHorizontally = False

“PageSetup” is a PageSetup object.

Property #10: PageSetup.CenterVertically

The CenterVertically property is like the CenterHorizontally property above. By using CenterVertically, you can specify whether the content is centered vertically on the printed page.

CenterVertically takes the Boolean values True and False, as follows:

  • True: Center.
  • False: Don’t center.

The syntax you use to specify your vertical-centering setting is roughly as follows:

PageSetup.CenterVertically = True
PageSetup.CenterVertically = False

“PageSetup” represents a PageSetup object.

PageSetup Properties Dealing With Headers Or Footers

The following 18 properties of the PageSetup object are related to headers or footers:

  • #1: PageSetup.AlignMarginsHeaderFooter.
  • #5: PageSetup.CenterFooter.
  • #6: PageSetup.CenterFooterPicture.
  • #7: PageSetup.CenterHeader.
  • #8: PageSetup.CenterHeaderPicture.
  • #12: PageSetup.DifferentFirstPageHeaderFooter.
  • #19: PageSetup.FooterMargin.
  • #20: PageSetup.HeaderMargin.
  • #21: PageSetup.LeftFooter.
  • #22: PageSetup.LeftFooterPicture.
  • #23: PageSetup.LeftHeader.
  • #24: PageSetup.LeftHeaderPicture.
  • #26: PageSetup.OddAndEvenPagesHeaderFooter.
  • #41: PageSetup.RightFooter.
  • #42: PageSetup.RightFooterPicture.
  • #43: PageSetup.RightHeader.
  • #44: PageSetup.RightHeaderPicture.
  • #46: PageSetup.ScaleWithDocHeaderFooter.

I explain properties #1 (PageSetup.AlignMarginsHeaderFooter), #19 (PageSetup.FooterMargin) and #20 (PageSetup.HeaderMargin) above. Please refer to the appropriate section for their explanation.

In addition to a description of all these properties, I include a list of the VBA codes you can use to format headers and footers, or add certain items to them.

In the following sections, I look at the other 15 properties I list above:

Properties #5, #7, #21, #23, #41 And #43: PageSetup.CenterFooter, PageSetup.CenterHeader, PageSetup.LeftFooter, PageSetup.LeftHeader, PageSetup.RightFooter And PageSetup.RightHeader

If you want to set a header or footer, use the following properties of the PageSetup object:

  • PageSetup.LeftHeader: Left header.
  • PageSetup.CenterHeader: Center header.
  • PageSetup.RightHeader: Right header.
  • PageSetup.RightFooter: Right footer.
  • PageSetup.CenterFooter: Center footer.
  • PageSetup.LeftFooter: Left footer.

Page Setup and Header/Footer and Header or Footer

If you want to work with any of these properties, use the following syntax:

PageSetup.LeftHeader = string
PageSetup.CenterHeader = string
PageSetup.RightHeader = string
PageSetup.RightFooter = string
PageSetup.CenterFooter = string
PageSetup.LeftFooter = string

The following definitions apply:

  • PageSetup: PageSetup object.
  • string: Header or footer you specify. You normally specify this as a string.

Header and Left, Center and Right section

Properties #6, #8, #22, #24, #42 And #44: PageSetup.CenterFooterPicture, PageSetup.CenterHeaderPicture, PageSetup.LeftFooterPicture, PageSetup.LeftHeaderPicture, PageSetup.RightFooterPicture And PageSetup.RightHeaderPicture

In the previous section, I introduce the properties that allow you to specify a header or footer. Those properties deal with strings.

The properties I cover in this section also allow you to specify headers or footers. However, in this case, the properties deal with graphic images.

In other words, you work with the following properties to specify a header or footer picture:

  • LeftHeaderPicture: Left header.
  • CenterHeaderPicture: Center header.
  • RightHeaderPicture: Right header.
  • RightFooterPicture: Right footer.
  • CenterFooterPicture: Center footer.
  • LeftFooterPicture: Left footer.

Footer and Left, Center and Right section

The syntax you use to work with these properties is more complex than the one you use to set a string header/footer. The reason for this is that the properties I cover in this section return a Graphic object. The Graphic object holds the properties of the header and footer pictures.

In other words, you set a header or footer picture in the following 3 steps:

  1. Set the equivalent non-picture footer or header property to be equal to the string “&G”. &G is one of the special VBA codes you can use when working with headers and footers (I cover this topic in its own section below). &G initializes the picture and shows it in the location of the relevant footer or header.

    The statements, depending on which of the properties above you use, are as follows. In all cases, “PageSetup” represents a PageSetup object.

    • LeftHeaderPicture:
      PageSetup.LeftHeader = "&G"
      
    • CenterHeaderPicture:
      PageSetup.CenterHeader = "&G"
      
    • RightHeaderPicture:
      PageSetup.RightHeader = "&G"
      
    • RightFooterPicture:
      PageSetup.RightFooter = "&G"
      
    • CenterFooterPicture:
      PageSetup.CenterFooter = "&G"
      
    • LeftFooterPicture:
      PageSetup.LeftFooter = "&G"
      
  2. Refer to the appropriate Graphic object using the properties I list above.
  3. Work with the properties of the Graphic object to specify the characteristics of the header or footer picture.

    Page Setup and Format Picture

The Graphic object has the following 14 properties:

  1. Graphic.Application.
  2. Graphic.Brightness.
  3. Graphic.ColorType.
  4. Graphic.Contrast.
  5. Graphic.Creator.
  6. Graphic.CropBottom.
  7. Graphic.CropLeft.
  8. Graphic.CropRight.
  9. Graphic.CropTop.
  10. Graphic.Filename.
  11. Graphic.Height.
  12. Graphic.LockAspectRatio.
  13. Graphic.Parent.
  14. Graphic.Width.

In the following sections, I provide more details about the most relevant of these properties. Property #10 (Graphic.Filename) is particularly important.

Property #2: Graphic.Brightness

Use the Graphic.Brightness property to specify the brightness of a footer or header picture.

Format Picture and Picture and Brightness

The following lines show the basic statement structure you can use for these purposes:

PageSetup.LeftHeaderPicture.Brightness = brightness#
PageSetup.CenterHeaderPicture.Brightness = brightness#
PageSetup.RightHeaderPicture.Brigthness = brightness#
PageSetup.RightFooterPicture.Brightness = brightness#
PageSetup.CenterFooterPicture.Brightness = brightness#
PageSetup.LeftFooterPicture.Brightness = brightness#

The following definitions apply:

  • PageSetup: PageSetup object reference.
  • brightness#: is the property value you specify. This value can range between 0.0 (dimmest) and 1.0 (brightest).
Property #3: Graphic.ColorType

You can use the Graphic.ColorType property to apply certain color transformations to a header or footer picture. You specify the appropriate transformation by using one of the following MsoPictureColorType constants:

  • msoPictureMixed (-2): Mixed.
  • msoPictureAutomatic (1): Default.
  • msoPictureGrayscale (2): Grayscale.
  • msoPictureBlackAndWhite (3): Black and white.
  • msoPictureWatermark (4): Watermark.

Format Picture and Picture and Color

The syntax of this property looks as follows:

PageSetup.LeftHeaderPicture.ColorType = msoPictureColorTypeConstant
PageSetup.CenterHeaderPicture.ColorType = msoPictureColorTypeConstant
PageSetup.RightHeaderPicture.ColorType = msoPictureColorTypeConstant
PageSetup.RightFooterPicture.ColorType = msoPictureColorTypeConstant
PageSetup.CenterFooterPicture.ColorType = msoPictureColorTypeConstant
PageSetup.LeftFooterPicture.ColorType = msoPictureColorTypeConstant

The following definitions are applicable:

  • PageSetup: PageSetup object reference.
  • msoPictureColorTypeConstant: MsoPictureColorType constant. I list these constants above.
Property #4: Graphic.Contrast

The Graphic.Contrast property allows you to specify the contrast of a header or footer picture.

Format Picture and Picture and Contrast

The basic syntax for specifying the picture contrast is as follows:

PageSetup.LeftHeaderPicture.Contrast = contrast#
PageSetup.CenterHeaderPicture.Contrast = contrast#
PageSetup.RightHeaderPicture.Contrast = contrast#
PageSetup.RightFooterPicture.Contrast = contrast#
PageSetup.CenterFooterPicture.Contrast = contrast#
PageSetup.LeftFooterPicture.Contrast = contrast#

The following definitions are applicable:

  • PageSetup: PageSetup object reference.
  • contrast#: Value you set for the Contrast property. This value must be between 0.0 (least contrast) and 1.0 (greatest contrast).
Properties #6, #7, #8 And #9: Graphic.CropBottom, Graphic.CropLeft, Graphic.CropRight And Graphic.CropTop

You can use the following properties to crop a header or footer picture:

  • Graphic.CropTop: Crop off the top.
  • Graphic.CropRight: Crop off the right side.
  • Graphic.CropBottom: Crop off the bottom.
  • Graphic.CropLeft: Crop off the left side.

Format Picture and Picture and Crop from and Left, Top, Right and Bottom

The following list shows the basic syntax you use to work with the properties above:

  • Graphic.CropTop:
    PageSetup.LeftHeaderPicture.CropTop = cropPoints#
    PageSetup.CenterHeaderPicture.CropTop = cropPoints#
    PageSetup.RightHeaderPicture.CropTop = cropPoints#
    PageSetup.RightFooterPicture.CropTop = cropPoints#
    PageSetup.CenterFooterPicture.CropTop = cropPoints#
    PageSetup.LeftFooterPicture.CropTop = cropPoints#
    
  • Graphic.CropRight:
    PageSetup.LeftHeaderPicture.CropRight = cropPoints#
    PageSetup.CenterHeaderPicture.CropRight = cropPoints#
    PageSetup.RightHeaderPicture.CropRight = cropPoints#
    PageSetup.RightFooterPicture.CropRight = cropPoints#
    PageSetup.CenterFooterPicture.CropRight = cropPoints#
    PageSetup.LeftFooterPicture.CropRight = cropPoints#
    
  • Graphic.CropBottom:
    PageSetup.LeftHeaderPicture.CropBottom = cropPoints#
    PageSetup.CenterHeaderPicture.CropBottom = cropPoints#
    PageSetup.RightHeaderPicture.CropBottom = cropPoints#
    PageSetup.RightFooterPicture.CropBottom = cropPoints#
    PageSetup.CenterFooterPicture.CropBottom = cropPoints#
    PageSetup.LeftFooterPicture.CropBottom = cropPoints#
    
  • Graphic.CropLeft:
    PageSetup.LeftHeaderPicture.CropLeft = cropPoints#
    PageSetup.CenterHeaderPicture.CropLeft = cropPoints#
    PageSetup.RightHeaderPicture.CropLeft = cropPoints#
    PageSetup.RightFooterPicture.CropLeft = cropPoints#
    PageSetup.CenterFooterPicture.CropLeft = cropPoints#
    PageSetup.LeftFooterPicture.CropLeft = cropPoints#
    

The following definitions apply:

  • PageSetup: PageSetup object reference.
  • cropPoints#: Number of points you want to crop off the picture. Generally, Excel calculates the size of the cropped section with respect to the original size of the header or footer picture.
Property #10: Graphic.Filename

If you’re specifying a header or footer image, you’ll need to deal with this property. Graphic.Filename allows you to specify the location of the file you use as header or footer picture.

Insert Pictures and From a file, Bing Image Search, or OneDrive Personal

You can generally specify any of the following locations:

  • An URL.
  • A file path, including both local and network paths.

The statement structure you use to specify Filename is as follows:

PageSetup.LeftHeaderPicture.Filename = locationString
PageSetup.CenterHeaderPicture.Filename = locationString
PageSetup.RightHeaderPicture.Filename = locationString
PageSetup.RightFooterPicture.Filename = locationString
PageSetup.CenterFooterPicture.Filename = locationString
PageSetup.LeftFooterPicture.Filename = locationString

The following are the applicable definitions:

  • PageSetup: PageSetup object reference.
  • locationString: Location of your header or footer image. You generally specify Filename as a string.
Properties #11, #13 And #14: Graphic.Height, Graphic.LockAspectRatio And Graphic.Width

The 3 properties I cover in this section (Height, LockAspectRatio and Width) allow you to specify the size of a header or footer image.

Format Picture and Size

You can set the height and width of the header or footer picture with the Height and Width properties (respectively). The statements you can use for these purposes look as follows:

  • Height:
    PageSetup.LeftHeaderPicture.Height = height#
    PageSetup.CenterHeaderPicture.Height = height#
    PageSetup.RightHeaderPicture.Height = height#
    PageSetup.RightFooterPicture.Height = height#
    PageSetup.CenterFooterPicture.Height = height#
    PageSetup.LeftFooterPicture.Height = height#
    
  • Width:
    PageSetup.LeftHeaderPicture.Width = width#
    PageSetup.CenterHeaderPicture.Width = width#
    PageSetup.RightHeaderPicture.Width = width#
    PageSetup.RightFooterPicture.Width = width#
    PageSetup.CenterFooterPicture.Width = width#
    PageSetup.LeftFooterPicture.Width = width#
    

The following definitions apply:

  • PageSetup: PageSetup object reference.
  • height# and width#:
    • Height and width of the header or footer picture. You specify both Height and Width in points.
    • If you want to work with inches or centimeters, you can use the Application.InchesToPoints or Application.CentimetersToPoints methods I describe further below.

The LockAspectRatio property allows you to choose which of the following ways Excel behaves when you resize a picture:

  • The original proportions of the picture are maintained. In other words, height and width maintain a dependency relation.
  • The original proportions of the picture aren’t necessarily maintained. You can change the width or height of the picture independently.

To specify an option, use the following MsoTriState constants:

  • msoTrue (-1): Retain original proportions of picture.
  • msoFalse (0): Modify width or height of picture independently.

Format Picture and Lock aspect ratio

The statement structure you can use to set the value of the LockAspectRatio property is as follows:

PageSetup.LeftHeaderPicture.LockAspectRatio = msoTriStateConstant
PageSetup.CenterHeaderPicture.LockAspectRatio = msoTriStateConstant
PageSetup.RightHeaderPicture.LockAspectRatio = msoTriStateConstant
PageSetup.RightFooterPicture.LockAspectRatio = msoTriStateConstant
PageSetup.CenterFooterPicture.LockAspectRatio = msoTriStateConstant
PageSetup.LeftFooterPicture.LockAspectRatio = msoTriStateConstant

The following definitions apply:

  • PageSetup: PageSetup object reference.
  • msoTriStateConstant: msoTrue or msoFalse, as I explain above.

Properties #12 And #26: PageSetup.DifferentFirstPageHeaderFooter And PageSetup.OddAndEvenPagesHeaderFooter

The DifferentFirstPageHeaderFooter and OddAndEvenPagesHeaderFooter allow you to specify whether headers and footers are:

  • Different in the first page, in the case of DifferentFirstPageHeaderFooter.
  • Different for odd and even numbers, in the case of the OddAndEvenPagesHeaderFooter.

Page Setup and Header/Footer and Different odd and even pages, Different first page

You specify whether any of the differences above applies by setting the relevant property to True. The following basic statements do this:

PageSetup.DifferentFirstPageHeaderFooter = True
PageSetup.OddAndEvenPagesHeaderFooter = True

“PageSetup” is a reference to a PageSetup object.

The DifferentFirstPageHeaderFooter and OddAndEvenPagesHeaderFooter properties only specify whether there are different headers/footers for certain pages. These properties don’t specify the characteristics or content of the headers/footers of those pages. You specify those characteristics/content by accessing the appropriate HeaderFooter object. I explain how you do this in the sections covering the PageSetup.FirstPage and PageSetup.EvenPage properties below.

Property #46: PageSetup.ScaleWithDocHeaderFooter

Use the ScaleWithDocHeaderFooter property to determine whether Excel scales the header and footer (with the rest of the document) when you change the size of the document.

The ScaleWithDocHeaderFooter property can take the Boolean values True and False, as follows:

  • True: Scale header and footer.
  • False: Don’t scale.

Page Setup and Header/Footer and Scale with document

The corresponding statement structure you can use is as follows:

PageSetup.ScaleWithDocHeaderFooter = True
PageSetup.ScaleWithDocHeaderFooter = False

“PageSetup” is a PageSetup object.

VBA Codes For Formatting Or Adding Items To Headers And Footers

The table below displays the special codes you can use as part of header or footer properties. These codes allow you to do the following:

  • Format the header/footer.
  • Insert certain items/information in the header/footer.

Some of these codes can be very useful. You can check out an example of what you can do with them in macro example #2 below. In that case, I use codes to:

  • Insert a picture header.
  • Insert the number of each page expresses as “Page # of #”.
Code Description
&L Align characters that follow to the left.
&C Center the characters that follow.
&R Align characters that follow to the right.
&E Toggle double-underline printing on/off.
&X Toggle superscript printing on/off.
&Y Toggle subscript printing on/off.
&B Toggle bold printing on/off.
&I Toggle italic printing on/off.
&U Toggle underline printing on/off.
&S Toggle strikethrough printing on/off.
&”fontFaceName”

Print characters that follow in specified font (fontFaceName).

Include double quotations (“”).

&fontSize#

Print characters that follow in specified font size (fontSize#).

Express fontSize# in points and as a 2-digit number.

&colorHex

Print characters that follow in specified color (colorHex).

Express colorHex as a hexadecimal color value.

&”+”

Print characters that follow in Heading font of current theme.

Include double quotations (“”).

&”-“

Print characters that follow in Body font of current theme.

Include double quotations (“”).

&Kxx.Syyy

Print characters that follow in specified color from current theme.

The following definitions apply:

  • xx: Theme color to use. Express as a 2-digit number between 01 and 12.
  • S: + or -. + creates a lighter shade. – creates a darker shade.
  • yyyPercentage of change in shade of theme color. Express as a 3-digit number between 0 (0%) and 100 (100%).

If the values you specify aren’t within applicable limits, Excel uses nearest valid value.

&D

Print current date.

&T

Print current time.

&F

Print filename.

&A

Print tab name.

&P

Print page number.

&P+#

Print page number plus specified number (#).

&P-#

Print page number minus specified number (#).

&&

Print an ampersand (&).

&N

Print total number of pages.

&Z

Print file path.

&G

Insert picture.

If you’re dealing with codes where you must include numbers at the end (for example, fontSize#), be careful with how you structure the string you assign to the header or footer property. In these cases, you generally want to avoid structuring your string in such a way that you have numbers in the following places:

  1. At the end of your special code; and
  2. At the beginning of the actual string you want Excel to display as header/footer.

Such a structure may result in Excel interpreting the whole digit combination (both #1 and #2 above) as a single number. This generally results in inappropriate formatting (for example, a very large fontSize#) and incomplete header/footer text (without the number you intended to include at the beginning).

A possible solution to this issue is including a space after the special code. For example, if you want to specify a center header that states “200 Customers” and whose font size is 15 points:

  • Instead of using a statement with the following structure:
    PageSetup.CenterHeader = "15200 Customers"
    
  • Try the statement below:
    PageSetup.CenterHeader = "15 200 Customers"
    

PageSetup Properties Dealing With Differences Between Pages

As I explain in the section about the DifferentFirstPageHeaderFooter and OddAndEvenPagesHeaderFooter properties above, you can specify that certain pages have different headers or footers. You do this by setting the applicable property to True.

Those 2 properties of the PageSetup object don’t specify the actual characteristics of the differing headers/footers. I explain how you can specify such characteristics in this section.

You can specify different headers/footers for (i) the first page vs. the other pages, or (ii) even vs. odd pages in the following 4 easy steps:

  1. Set the DifferentFirstPageHeaderFooter or OddAndEvenPagesHeaderFooter property (as applicable) to True.
  2. Use the PageSetup.FirstPage or PageSetup.EvenPage property (as applicable) to access the appropriate Page object.
  3. Use the properties of the Page object to access the HeaderFooter object representing the applicable header/footer.
  4. Work with the properties of the HeaderFooter object to specify the characteristics of the relevant header/footer.

I explain step #1, and provide the basic statement syntax you use, above. In this section, we take a closer look at the constructs involved in steps #2 to #4. This includes the following PageSetup properties:

  • #14: PageSetup.FirstPage.
  • #15: PageSetup.EvenPage.

Properties #14 And #15: PageSetup.EvenPage And PageSetup.FirstPage

Both PageSetup.FirstPage and PageSetup.EvenPage return a Page object. The Page object represents a page.

The Page object has the following 6 properties:

  • Page.CenterFooter.
  • Page.CenterHeader.
  • Page.LeftFooter.
  • Page.LeftHeader.
  • Page.RightFooter.
  • Page.RightHeader.

These properties return a HeaderFooter object. Let’s look at the…

HeaderFooter Object

The HeaderFooter object represents a header or footer.

In other words, HeaderFooter is the object you work with for purposes of specifying the headers and footers of either of the following:

  • First page, if the DifferentFirstPageHeaderFooter property is set to True.
  • Even pages, if the OddAndEvenPagesHeaderFooter property is True.

HeaderFooter has the following 2 properties:

  • HeaderFooter.Text.
  • HeaderFooter.Picture.
HeaderFooter.Text Property

The HeaderFooter.Text property allows you to specify the text that appears within a header or footer.

Header and Even Page Header and Left, Center and Right section

The basic syntax you use to specify the text of a header or footer is as follows:

expression.LeftHeader.Text = string
expression.CenterHeader.Text = string
expression.RightHeader.Text = string
expression.RightFooter.Text = string
expression.CenterFooter.Text = string
expression.LeftFooter.Text = string

The following definitions apply:

  • PageSetup: PageSetup object.
  • string: Header or footer you want to set. You generally set these properties to a string.
HeaderFooter.Picture Property

The HeaderFooter.Picture property returns a Graphic object. This Graphic object represents the header or footer picture you use.

I cover the Graphic object in detail when introducing the CenterFooterPicture, CenterHeaderPicture, LeftFooterPicture, LeftHeaderPicture, RightFooterPicture and RightHeaderPicture properties. Those properties return a Graphic object representing a header or footer picture. Just as the HeaderFooter.Picture property we’re looking at in this section.

Therefore, you can use the HeaderFooter.Picture property for purposes of setting a header or footer picture. You specify the characteristics of the picture through the properties of the Graphic object.

I explain the most important properties of the Graphic object above. The comments there are roughly applicable to the object returned by the Picture property here.

There are, however, some differences in the constructs you use in the 3-step process you use to set the header or footer picture. When working with the HeaderFooter.Picture property, you set a header or footer picture in the following 3 simple steps:

  1. Set the equivalent non-picture footer or header property to be equal “&G”.

    Normally, you do this by working with the LeftHeader, CenterHeader, RightHeader, RightFooter, CenterFooter or LeftFooter properties of the PageSetup object. This isn’t the case when dealing with a HeaderFooter object.

    When working with a HeaderFooter object, as we’re doing now, the property you set to equal “&G” is HeaderFooter.Text. In other words, the statements you use look roughly as follows:

    expression.LeftHeader.Text = "&G"
    expression.CenterHeader.Text = "&G"
    expression.RightHeader.Text = "&G"
    expression.RightFooter.Text = "&G"
    expression.CenterFooter.Text = "&G"
    expression.LeftFooter.Text = "&G"
    

    “expression” represents a Page object. In this context, you generally use the PageSetup.FirstPage or PageSetup.EvenPage properties to refer to that object.

  2. Refer to the appropriate Graphic object using the HeaderFooter.Picture property.
  3. Use the properties of the Graphic object to specify the characteristics of the relevant header or footer picture.

Please refer to the appropriate section above for a more detailed explanation of steps #2 and #3.

As a relatively simply example, the basic statement structure you can use to specify the location of the file you use as header or footer picture (Filename property) is as follows:

expression.LeftHeader.Picture.Filename = locationString
expression.CenterHeader.Picture.Filename = locationString
expression.RightHeader.Picture.Filename = locationString
expression.RightFooter.Picture.Filename = locationString
expression.CenterFooter.Picture.Filename = locationString
expression.LeftFooter.Picture.Filename = locationString

The following definitions apply:

  • expression: Page object.
  • locationString: String specifying location of your header or footer image.

HPageBreak And VPageBreak Objects

The HPageBreak and VPageBreak objects represent individual page breaks. The corresponding collections of all page breaks within the print area are HPageBreaks and VPageBreaks.

HPageBreak and HPageBreaks refer to horizontal page breaks. VPageBreak and VPageBreaks refer to vertical page breaks.

You can generally access the HPageBreak of VPageBreak objects through the following properties:

  • Sheets.HPageBreaks or Sheets.VPageBreaks.
  • Worksheets.HPageBreaks or Worksheets.VPageBreaks.
  • Worksheet.HPageBreaks or Worksheet.VPageBreaks.
  • Charts.HPageBreaks or Charts.VPageBreaks.

Generally, the properties above return one of the following:

  • A HPageBreaks collection representing all the horizontal page breaks within the applicable object.
  • A VPageBreaks collection that represents all the vertical page breaks within the object.

In the following sections, I introduce some of the most important VBA constructs you can use to work with page breaks:

HPageBreak.Delete And VPageBreak.Delete Methods

Use the HPageBreak.Delete or the VPageBreak.Delete methods to delete a page break.

Ribbon and Page Layout and Breaks and Remove Page Break

The basic structure of the statements you use to work with these methods is as follows:

HPageBreak.Delete
VPageBreak.Delete

The following definitions apply:

  • HPageBreak: HPageBreak object.
  • VPageBreak: VPageBreak object.

HPageBreak.DragOff And VPageBreak.DragOff Methods

Generally, the easiest way to eliminate a page break is to work with the Delete method I describe in the previous section.

However, if you’re working with the macro recorder, you may encounter the DragOff method. The HPageBreak.DragOff and VPageBreak.DragOff methods drag a page break outside of the print area.

The basic syntax of the DragOff method looks roughly as follows:

HPageBreak.DragOff(Direction, RegionIndex)
VPageBreak.DragOff(Direction, RegionIndex)

The following definitions apply:

  • HPageBreak: HPageBreak object.
  • VPageBreak: VPageBreak object.
  • Direction: The direction in which the drag off occurs. Direction is expressed as one of the following XlDirection constants:
    • xlUp (-4162): Up.
    • xlToRight (-4161): Right.
    • xlToLeft (-4159): Left.
    • xlDown (-4121): Down.
  • RegionIndex: The index of the print area region where the page break is located. If you have a single contiguous print area, there’s only 1 print area region and RegionIndex is 1. If you have non-contiguous printing areas, you’re dealing with more than 1 print area region.

HPageBreak.Location And VPageBreak.Location Properties

The Location property allows you to set the location of a page break.

The basic statement structure you use for these purposes is as follows:

HPageBreak.Location = locationRange
VPageBreak.Location = locationRange

The following definitions are applicable:

  • HPageBreak: HPageBreak object.
  • VPageBreak: VPageBreak object.
  • locationRange: is the Range object (usually a cell) that defines the location of the page break. The following rules apply:
    • HPageBreak.Location: A horizontal page break is set at the top edge of the range you specify as location.
    • VPageBreak.Location: A vertical page break is on the left edge of the range you set as location.

HPageBreaks.Add And VPageBreaks.Add Methods

Use the Add method to add a page break.

Ribbon and Page Layout and Breaks and Insert Page Break

The basic syntax of the Add method is as follows:

HPageBreaks.Add(locationRange)
VPageBreaks.Add(locationRange)

The following definitions are applicable:

  • HPageBreak: HPageBreak object.
  • VPageBreak: VPageBreak object.
  • locationRange: Range object you use to specify the location of the new page break. In this sense, the Add method works in a very similar way to the HPageBreak.Location and VPageBreak.Location properties I describe above.

When specifying the location of the added page break, consider the following rules:

  • HPageBreaks.Add: A horizontal page break is added above the range you specify as location.
  • VPageBreaks.Add: Vertical page breaks are added to the left of the range you define as location.

Worksheet.ResetAllPageBreaks Method

In the previous section, I introduce the HPageBreak and VPageBreak objects. These are the objects you generally work with when dealing with page breaks.

The Worksheet.ResetAllPageBreaks method also deals with page breaks. It resets all page breaks within a worksheet.

Ribbon and Breaks and Reset All Page Breaks

The basic statement structure you use to reset page breaks with ResetAllPageBreaks is as follows:

Worksheet.ResetAllPageBreaks

“Worksheet” is a worksheet object.

Application.InchesToPoints And Application.CentimetersToPoints Methods

In previous sections, I introduce certain VBA constructs that measure distances in points. This is the case, for example, of the properties that deal with margins and image cropping.

In such cases, you may prefer to express those distances in inches or centimeters. The following 2 methods allow you to that:

  • Application.InchesToPoints.
  • Application.CentimetersToPoints.

Both methods take a measurement (in inches or centimeters) and convert it to points. The basic statement syntax you can use for these purposes is as follows:

Application.InchesToPoints(Inches)
Application.CentimetersToPoints(Centimeters)

“Inches” and “Centimeters” are the values you want to convert to points.

Macro Code Examples To Print With Excel

In the following sections, I provide 2 step-by-step examples of VBA code that you can easily adjust to easily manipulate the constructs I introduce in the previous sections.

For these examples, I created a sample workbook. This sample workbook contains a table with 200 entries of random customer data (Name, Address and Email). The emails are all made-up outlook.com addresses.

You can get immediate free access to this example workbook by clicking the button below.

Get immediate free access to the Excel VBA Print Tutorial workbook example

The following screenshot shows how the sample data looks like:

Table with Customer Name, Address and Email

Macro Example #1: Quick Print

The following sample macro (printInExcel) shows how you can quickly print an Excel worksheet with VBA. This Sub procedure prints 2 copies of the first 2 pages of “PrintOut Example”.

Worksheets.PrintOut From, To, Copies, Preview, Collate, IgnorePrintAreas

The macro has a single statement. I break this statement apart in several lines for legibility.

Let’s take a closer look at each of these lines of code:

Line #1: Worksheets(“PrintOut Example”).PrintOut

Uses the Worksheet.PrintOut method to print the worksheet named “PrintOut Example” (Worksheets(“PrintOut Example”)).

The following lines of code (#2 to #7) are parameters of this method.

Lines #2 And #3: From:=1 | To:=2

The From and To parameters specify the pages that Excel prints. In this case, the instruction is as follows:

  • Start printing at page 1 (From:=1).
  • Print until page 2 (To:=2).

Line #4: Copies:=2

The Copies argument specifies that 2 copies are printed.

Line #5: Preview:=False

The Preview parameter is set to its default (False). Because of this, Excel doesn’t display the print preview prior to printing.

Line #6: Collate:=True

The Collate parameter is set to True. This ensures that Excel organizes the printed sheets into separate sets.

In this example, Excel prints 2 copies. Each copy has 2 pages. Therefore, by collating, Excel proceeds as follows:

  1. Print the entire first copy.
  2. Print the entire second copy.

Line #7: IgnorePrintAreas:=True

The IgnorePrintAreas parameter is set to True. The consequence of this is that Excel ignores any print areas and prints the entire worksheet (PrintOut Example).

Macro Example #1 Results

The following images show the rough results I obtain when executing the sample macro above (printInExcel). I display screenshots of the print preview for clarity purposes. The printout looks materially the same.

Print macro results page 1

Print results with macro

As you can see above, the macro does its job but results aren’t necessarily the best.

The macro prints the 2 first pages of the sample worksheet. However, the page setup can be easily improved to, for example:

  • Display all columns within the same sheet of paper. The printout resulting from the execution of the printInExcel macro example above leaves out the Email column.
  • Repeat the header row (Customer Name | Address | Email) in all printed pages.

The following macro example #2 deals with these and several other common page setup settings. Let’s dive right into it:

Macro Example #2: Specify Page Setup And Display Print Preview

The following macro example (pageSetupPrintPreview) does the following:

  1. Specifies several page setup settings.
  2. Displays the print preview of the sample worksheet.

VBA code to setup page and print preview

The code of this Sub procedure may look relatively complex at first glance. Don’t worry about that too much. This code simply implements several of the VBA constructs that I explain in the first part of this VBA Tutorial.

Some of the VBA constructs I include in the macro don’t have a material effect on the print preview that I display at the end. This is the case, for example, with the PageSetup.PrintQuality property I mention in step #7 below. I do this because my main purpose is to provide you examples that you can easily adjust and use.

Let’s dive into some more details of this sample macro. In this case, I take you through each of the main steps the VBA code goes through.

At the beginning of this VBA Tutorial, I mention that you can generally print or display the print preview of a page in 2 easy steps:

  1. Specify the page setup.
  2. Print or display the print preview.

I’m aware that the following explanation goes through (many) more steps. However, I organize it this way mostly for clarity purposes. At a basic level, I’m simply applying the 2 steps above.

Step #1: Variable Declaration And Assignment: Dim myWorksheet As Worksheet | Dim iCounter As Long | Dim myCmPointsBase As Single | Set myWorksheet = Worksheets(“PrintPreview Example”) | myCmPointsBase = Application.CentimetersToPoints(0.5)

Dim Worksheet, Dim Long, Dim Single, Set Worksheet, Assign Single

The first 3 lines of code declare 3 variables, one of these (myWorksheet) an object variable. The fourth and fifth lines of code carry out assignments. This goes as follows:

  1. Dim myWorksheet As Worksheet: myWorksheet represents the worksheet your macro works with.
  2. Dim iCounter As Long: iCounter is the counter for a For… Next Loop I describe further below.
  3. Dim myCmPointsBase As Single: This macro sets several margins and (some) picture sizes. Those measurements must be expressed in points. myCmPointsBase holds a “base” or “lowest common denominator” that I use to calculate those margins/sizes.
  4. Set myWorksheet = Worksheets(“PrintPreview Example”): Assigns a worksheet (PrintPreview Example) to the myWorksheet object variable.
  5. myCmPointsBase = Application.CentimetersToPoints(0.5): The Application.CentimetersToPoints method converts 0.5 centimeters to points. This value becomes the base I use to calculate margins and sizes that must be expressed in points. You can see this at work in steps #8 through #11 below.

Step #2: Set Up With… End With Blocks

With... End With blocks

Notice that there are several With… End With blocks. The purpose of these With… End With blocks is to simplify the syntax. The series of statements within each block work with the object specified in the opening line of the block.

  1. With myWorksheet: Virtually all the statements within the sample macro are within this With… End With block. Generally, the statements within the block work with myWorksheet. myWorksheet is an object variable representing the worksheet you want to print.
  2. With .PageSetup: This block is nested within block #1 above. Therefore, it’s a simplification of “myWorksheet.PageSetup”. Generally, the statements within this block refer to the PageSetup object.
  3. With .CenterHeaderPicture: The block is nested within block #2 above. Therefore, it’s a simplification of “myWorksheet.PageSetup.CenterHeaderPicture”. The statements within the block deal with the Graphic object returned by the CenterHeaderPicture property.
  4. With . EvenPage: This block is also nested within block #2 above. The fully-qualified object reference is “myWorksheet.PageSetup.EvenPage”. The statements within the block work with the Page object that EvenPage returns.
  5. With .CenterHeader: This block is nested within block #4 above. Therefore, it’s a simplification of “myWorksheet.PageSetup.EvenPage.CenterHeader”. The statements within the block refer to the HeaderFooter object that it returns.
  6. With.Picture: The block is nested within block #5 above. This is a simplification of “myWorksheet.PageSetup.EvenPage.CenterHeader.Picture”. The block deals with the Graphic object returned by the HeaderFooter.Picture property. As I explain below, the internal structure of this block is substantially the same as that of block #3 above (With .CenterHeaderPicture).

Step #3: Specify Page Breaks: .ResetAllPageBreaks | For iCounter = 5 To 205 Step 41 | .HPageBreaks.Add .Cells(iCounter, 1) | Next iCounter

.ResetAllPageBreaks | .HPageBreaks.Add

You can specify page breaks in the following 2 easy steps:

  1. Reset all page breaks.
  2. Add the new page breaks you want.

The lines of code we’re looking at are one of the ways in which you can achieve this.

The first of these statements is relatively straightforward:

  • .ResetAllPageBreaks: resets all page breaks within myWorksheet.

The second step is slightly more involved. At its basic level, it adds a page break every 41 rows, starting on the first row with data in the sample worksheet (row 5).

To understand how this is achieve, let’s look at what’s going on:

  1. For iCounter = 5 To 205 Step 41 | Next iCounter: A For… Next loop. I explain loops (including For… Next loops) in the post that you can find within the Archives. For purposes of this VBA Tutorial, I only highlight the main aspects of this loop, as follows:
    • For iCounter = 5 To 205:
      • The loop counter starts at 5 (iCounter = 5) and ends at 205 (To 205). These numbers (5 and 205) correspond to the location of the first (5) and the last (205) rows with data in the sample worksheet the macro works with.
      • In plain English, the loop starts on the first row with data and stops after the last row with data within the worksheet. As I explain below (when setting the PageSetup.PrintArea property), these rows (5 to 205) also correspond to the print area I specify in the macro.
      • You can easily generalize this kind of loop by, for example, getting VBA to identify which is the last row of the worksheet you’re working with.
    • Step 41:
      • Every time the loop goes through a row, the counter changes by 41. Because of this, the loop doesn’t really go through every single row between rows 5 and 205. It starts on row 5, and then goes through every 41th row thereafter. This continues until the value of the counter exceeds 205.
      • In other words, the loop goes through the following rows:
        • Row 5 (see #1 above).
        • Row 46 (5 + 41).
        • Row 87 (46 + 41).
        • Row 128 (87 + 41).
        • Row 169 (128 + 41).
  2. .HPageBreaks.Add .Cells(iCounter, 1):
    • The HPageBreaks.Add method adds a new horizontal page break.
    • Each page break is added above the range identified by “.Cells(iCounter, 1)”. The Worksheet.Cells property refers to the cell located at the intersection of row iCounter and column 1 (column A). iCounter follows the pattern I explain above (5, 46, 87, 128 and 169).
    • Therefore, the construct I explain here adds a page break above each of the rows identified by iCounter. This results in a page break every 41 rows.

Step #4: Specify Print Area, Paper Size And Orientation: . PrintArea = “B5:D205” | .PaperSize = xlPaperA4 | .Orientation = xlPortrait

.PrintArea = "B5:D205" | .PaperSize = xlPaperA4 | .Orientation = xlPortrait

These 3 lines of code use the PageSetup.PrintArea, PageSetup.PaperSize and PageSetup.Orientation properties to specify the print area, paper size and orientation. This goes as follows:

  1. .PrintArea = “B5:D205”: Specifies the print area. The range to print is from cell B5 to cell D205 (“B5:D205”). This corresponds to the cells with data within the sample worksheet.
  2. .PaperSize = xlPaperA4: Sets the size of paper to xlPaperA4. The constant xlPaperA4 represents A4 (210 mm x 297 mm).
  3. .Orientation = xlPortrait: Determines that the page orientation is portrait (xlPortrait).

Step #5: Specify Worksheet Scaling For Printing: .Zoom = False | .FitToPagesTall = False | .FitToPagesWide = 1

.Zoom = False | .FitToPagesTall = False | .FitToPagesWide = 1

One of the main issues with the results obtained when executing macro example #1 above (printInExcel) is that not all the columns appeared in the same piece of paper. The Email column didn’t fit.

The 3 lines of code we’re working with solve this problem. They make Excel scale the worksheet to 1 page wide. Let’s look at what each line of code does:

  • .Zoom = False: Sets the Zoom property to False. This ensures that the worksheet is scaled in accordance with the FitToPagesTall and FitToPagesWide properties.
  • .FitToPagesTall = False: Sets the FitToPagesTall property to False. Like #1 above, this allows the scaling to be determined by a single property: FitToPagesWide in this case.
  • .FitToPagesWide = 1: Scales the worksheet to 1 page wide.

Step #6: Print Gridlines, Headings And Specify Title Rows: .PrintGridlines = True | .PrintHeadings = True | .PrintTitleRows = myWorksheet.Rows(5).Address

.PrintGridlines = True | .PrintHeadings = True | .PrintTitleRows = myWorksheet.Rows(5).Address

These 3 lines of code specify the rules for the printing of certain items, as follows:

  • .PrintGridlines = True: Determines that gridlines are printed.
  • .PrintHeadings = True: Specifies that row and columns headings are printed.
  • .PrintTitleRows = myWorksheet.Rows(5).Address: Specifies that a row is repeated as header row at the top of each printed page. In this case, the row corresponds to row 5 of myWorksheet (myWorksheet.Rows(5)). The statement uses the Address property (.Address) to return a string representing row 5.

Step #7: Specify Print Quality: .PrintQuality = -3

.PrintQuality = -3

This line of code specifies the Print quality.

As I mention in the section on the PageSetup.PrintQuality property, you can generally get a good idea of the syntax you should use by working with the macro recorder. This is what I did to determine that the appropriate value is -3. In the case of the computer/printer I’m working with, this value corresponds to Medium print quality.

The exact statement you use to specify print quality may be different in your situation. Within the context of this example, it doesn’t really make much difference because, at the end, we’re not going to print the worksheet. Just get a print preview.

Step #8: Specify Header And Footer Margins: .FooterMargin = myCmPointsBase * 3 | .HeaderMargin = myCmPointsBase * 3 | .AlignMarginsHeaderFooter = True

.FooterMargin = myCmPointsBase * 3 | .HeaderMargin = myCmPointsBase * 3 | .AlignMarginsHeaderFooter = True

These 3 lines of code specify the margins and basic alignment of headers and footers. For purposes of these statements, remember that the variable myCmPointsBase holds the number of points equivalent to 0.5 centimeters.

The process is as follows:

  • .FooterMargin = myCmPointsBase * 3: Sets the footer margin to 1.5 centimeters (myCmPointsBase * 3 = 0.5 * 3 = 1.5 centimeters converted to points).
  • .HeaderMargin = myCmPointsBase * 3: Like #1 above. Specifies that the header margin is 1.5 centimeters.
  • .AlignMarginsHeaderFooter = True: Aligns headers and footers with general right and left margins (specified in step #9 below).

Step #9: Specify Margins: .TopMargin = myCmPointsBase * 6 | .RightMargin = myCmPointsBase * 5 | .BottomMargin = myCmPointsBase * 6 | .LeftMargin = myCmPointsBase * 5

.TopMargin = myCmPointsBase * 6 | .RightMargin = myCmPointsBase * 5 | .BottomMargin = myCmPointsBase * 6 | .LeftMargin = myCmPointsBase * 5

These 4 lines of code specify the general page margins. For these purposes, I rely on the myCmPointsBase variable. The value held by this variable is the number of points equivalent to 0.5 centimeters. The statements we’re looking at proceed as follows:

  • .TopMargin = myCmPointsBase * 6 | .BottomMargin = myCmPointsBase * 6: Set the top and bottom margins to 3 centimeters (myCmPointsBase * 6 = 0.5 * 6 = 3 centimeters converted to points).
  • .RightMargin = myCmPointsBase * 5 | .LeftMargin = myCmPointsBase * 5: Set the right and left margins to 2.5 centimeters (myCmPointsBase * 5 = 0.5 * 5 = 2.5 centimeters converted to points).

Step #10: Center Contents On Page: .CenterHorizontally = True | .CenterVertically = True

.CenterHorizontally = True | .CenterVertically = True

These 2 lines of code determine that the sheet is centered both horizontally and vertically when printing. Both statements have the same basic structure as follows:

  • .CenterHorizontally = True: Centers the sheet horizontally.
  • .CenterVertically = True: Centers the sheet vertically.

Step #11: Set Headers And Footers

.CenterFooter | .RightFooter | .CenterHeader | ,CenterHeaderPicture | .OddAndEvenPagesHeaderFooter

Within this example, several statements deal with headers and footers. Let’s look at each of the different headers and footers that the macro sets:

Step #11.1: Set Center And Right Footer (Text): .CenterFooter = “&BCustomer List Example” | .RightFooter = “Page &P of &N”

These 2 lines of code set footers. However, the way they work differs, as follows:

  • .CenterFooter = “&BCustomer List Example”: Sets the center footer to display “Customer List Example”. Uses the &B formatting code to toggle bold printing on/off.
  • .RightFooter = “Page &P of &N”: Sets the right footer to display the page number out of the total number of pages. For these purposes, it uses the &P and &N codes. &P prints the page number. &N prints the total number of pages.
Step #11.2: Set Center Header (Allow For Picture): .CenterHeader = “&G”

This statement makes reference to the center header (.CenterHeader). By setting the PageSetup.CenterHeader property to the code “&G”, the picture (see next section) is initialized and displayed in the location of the center header.

Step #11.3: Set Picture Center Header: With .CenterHeaderPicture | .Filename = “https://powerspreadsheets.com/wp-content/uploads/Power-Spreadsheets-Website-Logo.jpg” | .ColorType = msoPictureAutomatic | .LockAspectRatio = msoTrue | .Height = myCmPointsBase * 2 | End With

This With… End With block specifies a center header picture and determines several of its most important characteristics.

The statements within the block work with the Graphic object that the PageSetup.CenterHeaderPicture property returns. Those statements determine the main attributes of the Graphic object, as follows:

  • .Filename = “https://powerspreadsheets.com/wp-content/uploads/Power-Spreadsheets-Website-Logo.jpg”: Specifies the location of the file used as picture header. In this case, this corresponds to the URL where the Power Spreadsheets logo (which you find at the header of this website) is located. In other words, the following image is used:
    CenterHeaderPicture.Filename image
  • .ColorType = msoPictureAutomatic: Specifies that no color transformation is applied to the header image. The msoPictureAutomatic constant represents default color transformation.
  • .LockAspectRatio = msoTrue: Specifies that the original proportional relationship of the picture (height vs. width) is maintained when the image is resized.
  • .Height = myCmPointsBase * 2: Sets the height of the header image to 1 centimeter. myCmPointsBase is a variable representing the number of points equivalent to 0.5 centimeters.
Step #11.4: Specify That Headers And Footers Are Different For Odd And Even-Numbered Pages: .OddAndEvenPagesHeaderFooter = True

This statement uses the PageSetup.OddAndEvenPagesHeaderFooter to specify that header and footers differ between odd and even-numbered pages.

This leads us the next group of statements. Notice that they’re all within a With… End With block (With .EvenPage | End With). Therefore, the statements below refer to the Page object returned by the PageSetup.EvenPage property.

Step #11.5: Set Center And Right Footer (Text) For Even Pages: .CenterFooter.Text = “&BCustomer List Example” | .RightFooter.Text = “Page &P of &N”

These lines of code set the center and right footer for even pages.

The effect of these statements is virtually the same as that which sets the center and right footers in general, which I describe above. In other words:

  • The center footer for even pages is also “Customer List Example”. The &B code turns bold printing on/off.
  • The right footer for even pages also displays the current page number out of the total number of pages (Page # of #) by using the &P and &N codes.

The statement structure, however, differs depending on which footer you set. These differences are as follows:

  • If you want to set the general center footer, you work with the PageSetup.CenterFooter property. If you’re setting the text of the center footer of even pages, you use the Page.CenterFooter and the HeaderFooter.Text properties.
  • Like the above, you set the general right footer with the PageSetup.RightFooter property. In the case of even pages, you use the Page.RightFooter and HeaderFooter.Text properties.
Step #11.6: Set Picture Center Header For Even Pages: With .CenterHeader | .Text = “&G” | With .Picture | .Filename = “https://powerspreadsheets.com/wp-content/uploads/Power-Spreadsheets-Website-Logo.jpg” | .ColorType = msoPictureAutomatic | .LockAspectRatio = msoTrue | .Height = myCmPointsBase * 2 | End With | End With

This group of statements does the following to even pages:

  1. Initializes the header picture and allows it to be displayed in the place of the center header.
  2. Specifies the main attributes of the header picture.

Notice that, further above, I include lines of code that do the same to the general center headers. The statements we analyze in this section use a similar logic and structure to that which I explain then. Let’s take a closer look at this:

  1. The statements we’re looking at are wrapped within a With… End With block (With .CenterHeader | End With). Therefore, we’re working with the HeaderFooter object that the Page.CenterHeader property returns.
  2. The text of the center header is set to the code “&G” (.Text = “&G”). Doing this allows us to display the picture in the location of the center header.
    • This construct differs from that I use for the general center header above (.CenterHeader = “&G”). In that case, the VBA construct I rely on is the PageSetup.CenterHeader property.
  3. A second With… End With block (With .Picture | End With) works with the Graphic object that the HeaderFooter.Picture property returns.
    • This differs from the structure I use above to specify the general center header pictures (With .CenterHeaderPicture | End With). In that case, I access the relevant Graphic object through the PageSetup.CenterHeaderPicture property.
  4. Despite the differences in #3 above, notice that the statements within that With… End With block are the same regardless of the construct I use to access the Graphic object:
    1. .Filename = “https://powerspreadsheets.com/wp-content/uploads/Power-Spreadsheets-Website-Logo.jpg”: Specifies the location of the picture header file. For this example, is the header of the Power Spreadsheets website.
    2. .ColorType = msoPictureAutomatic: Applies the default color transformation to the picture header.
    3. .LockAspectRatio = msoTrue: Locks the proportional relationship between the height and the width of the picture, as it’s resized.
    4. .Height = myCmPointsBase * 2: Sets the height of the picture header to 1 centimeter.
Step #11.7: Set Right Header (Text) For Even Pages: .RightHeader.Text = “This is an even page”

The center footer and center header that I set for even pages is, in practice, the same as that which I specify in general.

However, prior to this line of code. I haven’t specified a right header.

The statement we’re looking at (.RightHeader.Text = “This is an even page”) sets the right header for even pages. The chosen string is “This is an even page”.

Because of the above, this statement generates a practical difference between even and odd pages:

  • Odd pages, which follow the general rule, don’t have a right header.
  • Even pages, which follow the rule we’re looking at, have a right header stating “This is an even page”.

Step #12: Display Print Preview: .PrintPreview

.PrintPreview

After all the page settings are defined by the previous statements, this line of code gets Excel to display the print preview.

If you want to print, this is usually the place where you’d work with the Print method. Macro example #1 above can give you a rough idea of the syntax you can use for these purposes.

Macro Example #2 Results

The images below show the print preview of the sample worksheet. This results in 5 pages.

Notice the following characteristics, caused by the sample macro (pageSetupPrintPreview). You can compare some of these with the results I obtain when executing macro example #1 above.

  1. The worksheet is scaled to 1 page wide. This a consequence of the specifications for worksheet scaling (step #5 above).
  2. The sheet is centered both horizontally and vertically. This setting is explained in step #10 above.
  3. Gridlines and headings are printed. This is a result of the requirements I explain in step #6 above.
  4. Row 5 of the sample worksheet appears at the top of the data in every page. This is also a consequence of step #6 above.
  5. Page breaks exist every 41 rows of the worksheet. This specification is set in step #3 above.
  6. The center header is Power Spreadsheets’ website header, as required by step #11 above.
  7. The center footer states “Customer List Example”. This is also set in step #11 above.
  8. The right footer provides the page number out of the total number of pages. Again, this is a consequence of step #11.
  9. The right header of even pages states “This is an even page”. Just as #5 and #6 above, this is established in step #11.

Macro example results: 1 page wide and printed gridlines

Results of macro to setup page and print: Centered content in page and printed headings

Results of setting up page and printing with macro: title row and page breaks

Results of macro to setup page: Picture header, text header in even pages and text footer

Results of setting up page and printing with macro: no header on odd pages and footer with page numbers

Conclusion

Knowing how to correctly setup and print Excel files is essential. When done appropriately, this helps you to easily share your work with others.

After reading this VBA Tutorial, you have the knowledge you require to begin automating most of your printing and page setup activities. You also have a good understanding of the main VBA constructs you can use. The following are some of these constructs we’ve reviewed in this post:

  • The PrintOut method.
  • The PrintPreview method.
  • The PageSetup object.
  • The HPageBreak and VPageBreak objects.
  • The Worksheet.ResetAllPageBreaks method.
  • The Application.InchesToPoints and Application.CentimetersToPoints methods.

You’ve also seen 2 practical and detailed examples of VBA code that you can adjust and start using immediately.

Remember that this Excel VBA Tutorial is accompanied by a sample workbook. This workbook contains the VBA code of the sample macros and the data I show in the screenshots above. You can get immediate free access to this example workbook by clicking the button below.

Get immediate free access to the Excel VBA Print Tutorial workbook example

На чтение 16 мин. Просмотров 14.5k.

VBA Worksheet

Malcolm Gladwell

Мечтатель начинает с чистого листа бумаги и переосмысливает мир

Эта статья содержит полное руководство по использованию Excel
VBA Worksheet в Excel VBA. Если вы хотите узнать, как что-то сделать быстро, ознакомьтесь с кратким руководством к рабочему листу VBA ниже.

Если вы новичок в VBA, то эта статья — отличное место для начала. Мне нравится разбивать вещи на простые термины и объяснять их на простом языке.

Вы можете прочитать статью от начала до конца, так как она написана в логическом порядке. Или, если предпочитаете, вы можете использовать оглавление ниже и перейти непосредственно к теме по вашему выбору.

Содержание

  1. Краткое руководство к рабочему листу VBA
  2. Вступление
  3. Доступ к рабочему листу
  4. Использование индекса для доступа к рабочему листу
  5. Использование кодового имени рабочего листа
  6.  Активный лист
  7. Объявление объекта листа
  8. Доступ к рабочему листу в двух словах
  9. Добавить рабочий лист
  10. Удалить рабочий лист
  11. Цикл по рабочим листам
  12. Использование коллекции листов
  13. Заключение

Краткое руководство к рабочему листу VBA

В следующей таблице приведен краткий обзор различных методов
Worksheet .

Примечание. Я использую Worksheet в таблице ниже, не указывая рабочую книгу, т.е. Worksheets, а не ThisWorkbook.Worksheets, wk.Worksheets и т.д. Это сделано для того, чтобы примеры были понятными и удобными для чтения. Вы должны всегда указывать рабочую книгу при использовании Worksheets . В противном случае активная рабочая книга будет использоваться по умолчанию.

Задача Исполнение
Доступ к рабочему листу по
имени
Worksheets(«Лист1»)
Доступ к рабочему листу по
позиции слева
Worksheets(2)
Worksheets(4)
Получите доступ к самому
левому рабочему листу
Worksheets(1)
Получите доступ к самому
правому листу
Worksheets(Worksheets.Count)
Доступ с использованием
кодового имени листа (только
текущая книга)
Смотри раздел статьи
Использование кодового имени
Доступ по кодовому имени
рабочего листа (другая рабочая
книга)
Смотри раздел статьи
Использование кодового имени
Доступ к активному листу ActiveSheet
Объявить переменную листа Dim sh As Worksheet
Назначить переменную листа Set sh = Worksheets(«Лист1»)
Добавить лист Worksheets.Add
Добавить рабочий лист и
назначить переменную
Worksheets.Add Before:=
Worksheets(1)
Добавить лист в первую
позицию (слева)
Set sh =Worksheets.Add
Добавить лист в последнюю
позицию (справа)
Worksheets.Add after:=Worksheets(Worksheets.Count)
Добавить несколько листов Worksheets.Add Count:=3
Активировать рабочий лист sh.Activate
Копировать лист sh.Copy
Копировать после листа sh1.Copy After:=Sh2
Скопировать перед листом sh1.Copy Before:=Sh2
Удалить рабочий лист sh.Delete
Удалить рабочий лист без
предупреждения
Application.DisplayAlerts = False
sh.Delete
Application.DisplayAlerts = True
Изменить имя листа sh.Name = «Data»
Показать/скрыть лист sh.Visible = xlSheetHidden
sh.Visible = xlSheetVisible sh.Name = «Data»
Перебрать все листы (For) Dim i As Long
For i = 1 To Worksheets.Count
  Debug.Print Worksheets(i).Name
Next i
Перебрать все листы (For Each) Dim sh As Worksheet
For Each sh In Worksheets
    Debug.Print sh.Name
Next

Вступление

Три наиболее важных элемента VBA — это Рабочая книга, Рабочий лист и Ячейки. Из всего кода, который вы пишете, 90% будут включать один или все из них.

Наиболее распространенное использование Worksheet в VBA для доступа к его ячейкам. Вы можете использовать его для защиты, скрытия, добавления, перемещения или копирования листа.

Тем не менее, вы будете в основном использовать его для выполнения некоторых действий с одной или несколькими ячейками на листе.

Использование Worksheets более простое, чем использование рабочих книг. С книгами вам может потребоваться открыть их, найти, в какой папке они находятся, проверить, используются ли они, и так далее. С рабочим листом он либо существует в рабочей книге, либо его нет.

Доступ к рабочему листу

В VBA каждая рабочая книга имеет коллекцию рабочих листов. В этой коллекции есть запись для каждого рабочего листа. Эта коллекция называется просто Worksheets и используется очень похоже на коллекцию Workbooks. Чтобы получить доступ к рабочему листу, достаточно указать имя.

Приведенный ниже код записывает «Привет Мир» в ячейках A1 на листах: Лист1, Лист2 и Лист3 текущей рабочей книги.

Sub ZapisVYacheiku1()

    ' Запись в ячейку А1 в листе 1, листе 2 и листе 3
    ThisWorkbook.Worksheets("Лист1").Range("A1") = "Привет Мир"
    ThisWorkbook.Worksheets("Лист2").Range("A1") = "Привет Мир"
    ThisWorkbook.Worksheets("Лист3").Range("A1") = "Привет Мир"

End Sub

Коллекция Worksheets всегда принадлежит книге. Если мы не
указываем рабочую книгу, то активная рабочая книга используется по умолчанию.

Sub ZapisVYacheiku1()

    ' Worksheets относятся к рабочим листам в активной рабочей книге.
    Worksheets("Лист1").Range("A1") = "Привет Мир"
    Worksheets("Лист2").Range("A1") = "Привет Мир"
    Worksheets("Лист3").Range("A1") = "Привет Мир"

End Sub

Скрыть рабочий лист

В следующих примерах показано, как скрыть и показать лист.

ThisWorkbook.Worksheets("Лист1").Visible = xlSheetHidden

ThisWorkbook.Worksheets("Лист1").Visible = xlSheetVisible

Если вы хотите запретить пользователю доступ к рабочему
листу, вы можете сделать его «очень скрытым». Это означает, что это может быть
сделано видимым только кодом.

' Скрыть от доступа пользователя
ThisWorkbook.Worksheets("Лист1").Visible = xlVeryHidden

' Это единственный способ сделать лист xlVeryHidden видимым
ThisWorkbook.Worksheets("Лист1").Visible = xlSheetVisible

Защитить рабочий лист

Другой пример использования Worksheet — когда вы хотите защитить его.

ThisWorkbook.Worksheets("Лист1").Protect Password:="Мойпароль"

ThisWorkbook.Worksheets("Лист1").Unprotect Password:="Мойпароль"

Индекс вне диапазона

При использовании Worksheets вы можете получить сообщение об
ошибке:

Run-time Error 9 Subscript out of Range

VBA Subscript out of Range

Это означает, что вы пытались получить доступ к рабочему листу, который не существует. Это может произойти по следующим причинам:

  1. Имя Worksheet , присвоенное рабочим листам, написано неправильно.
  2. Название листа изменилось.
  3. Рабочий лист был удален.
  4. Индекс был большим, например Вы использовали рабочие листы (5), но есть только четыре рабочих листа
  5. Используется неправильная рабочая книга, например Workbooks(«book1.xlsx»).Worksheets(«Лист1») вместо
    Workbooks(«book3.xlsx»).Worksheets («Лист1»).

Если у вас остались проблемы, используйте один из циклов из раздела «Циклы по рабочим листам», чтобы напечатать имена всех рабочих листов коллекции.

Использование индекса для доступа к рабочему листу

До сих пор мы использовали имя листа для доступа к листу.
Указатель относится к положению вкладки листа в рабочей книге. Поскольку
положение может быть легко изменено пользователем, не рекомендуется
использовать это.

 В следующем коде показаны примеры использования индекса.

' Использование этого кода является плохой идеей, так как
' позиции листа все время меняются
Sub IspIndList()

    With ThisWorkbook
        ' Самый левый лист
        Debug.Print .Worksheets(1).Name
        ' Третий лист слева
        Debug.Print .Worksheets(3).Name
        ' Самый правый лист
        Debug.Print .Worksheets(.Worksheets.Count).Name
    End With

End Sub

В приведенном выше примере я использовал Debug.Print для печати в Immediate Window. Для просмотра этого окна выберите «Вид» -> «Immediate Window » (Ctrl + G).

ImmediateWindow

ImmediateSampeText

Использование кодового имени рабочего листа

Лучший способ получить доступ к рабочему листу —
использовать кодовое имя. Каждый лист имеет имя листа и кодовое имя. Имя листа
— это имя, которое отображается на вкладке листа в Excel.

Изменение имени листа не приводит к изменению кодового имени, что означает, что ссылка на лист по кодовому имени — отличная идея.

Если вы посмотрите в окне свойств VBE, вы увидите оба имени.
На рисунке вы можете видеть, что кодовое имя — это имя вне скобок, а имя листа
— в скобках.

code name worksheet

Вы можете изменить как имя листа, так и кодовое имя в окне
свойств листа (см. Изображение ниже).

Width

Если ваш код ссылается на кодовое имя, то пользователь может
изменить имя листа, и это не повлияет на ваш код. В приведенном ниже примере мы
ссылаемся на рабочий лист напрямую, используя кодовое имя.

Sub IspKodImya2()

    ' Используя кодовое имя листа
    Debug.Print CodeName.Name
    CodeName.Range("A1") = 45
    CodeName.Visible = True

End Sub

Это делает код легким для чтения и безопасным от изменения
пользователем имени листа.

Кодовое имя в других книгах

Есть один недостаток использования кодового имени. Он относится только к рабочим листам в рабочей книге, которая содержит код, т.е. ThisWorkbook.

Однако мы можем использовать простую функцию, чтобы найти
кодовое имя листа в другой книге.

Sub ИспЛист()

    Dim sh As Worksheet
    ' Получить рабочий лист под кодовым именем
    Set sh = SheetFromCodeName("CodeName", ThisWorkbook)
    ' Используйте рабочий лист
    Debug.Print sh.Name

End Sub

' Эта функция получает объект листа из кодового имени
Public Function SheetFromCodeName(Name As String, bk As Workbook) As Worksheet

    Dim sh As Worksheet
    For Each sh In bk.Worksheets
        If sh.CodeName = Name Then
           Set SheetFromCodeName = sh
           Exit For
        End If
    Next sh

End Function

Использование приведенного выше кода означает, что если
пользователь изменит имя рабочего листа, то на ваш код это не повлияет.

Существует другой способ получения имени листа внешней
рабочей книги с использованием кодового имени. Вы можете использовать элемент
VBProject этой Рабочей книги.

Вы можете увидеть, как это сделать, в примере ниже. Я включил это, как дополнительную информацию, я бы рекомендовал использовать метод из предыдущего примера, а не этот.

Public Function SheetFromCodeName2(codeName As String _
                             , bk As Workbook) As Worksheet

    ' Получить имя листа из CodeName, используя VBProject
    Dim sheetName As String
    sheetName = bk.VBProject.VBComponents(codeName).Properties("Name")

    ' Используйте имя листа, чтобы получить объект листа
    Set SheetFromCodeName2 = bk.Worksheets(sheetName)

End Function

Резюме кодового имени

Ниже приведено краткое описание использования кодового имени:

  1. Кодовое имя рабочего листа может быть
    использовано непосредственно в коде, например. Sheet1.Range
  2. Кодовое имя будет по-прежнему работать, если имя
    рабочего листа будет изменено.
  3. Кодовое имя может использоваться только для
    листов в той же книге, что и код.
  4. Везде, где вы видите ThisWorkbook.Worksheets
    («имя листа»), вы можете заменить его кодовым именем рабочего листа.
  5. Вы можете использовать функцию SheetFromCodeName
    сверху, чтобы получить кодовое имя рабочих листов в других рабочих книгах.

 Активный лист

Объект ActiveSheet ссылается на рабочий лист, который в данный момент активен. Вы должны использовать ActiveSheet только в том случае, если у вас есть особая необходимость ссылаться на активный лист.

В противном случае вы должны указать рабочий лист, который
вы используете.

Если вы используете метод листа, такой как Range, и не
упоминаете лист, он по умолчанию будет использовать активный лист.

' Написать в ячейку A1 в активном листе
ActiveSheet.Range("A1") = 99

' Активный лист используется по умолчанию, если лист не используется
Range("A1") = 99

Объявление объекта листа

Объявление объекта листа полезно для того, чтобы сделать ваш
код более понятным и легким для чтения.

В следующем примере показан код для обновления диапазонов
ячеек. Первый Sub не объявляет объект листа. Вторая подпрограмма объявляет
объект листа, и поэтому код намного понятнее.

Sub NeObyavObektList()

    Debug.Print ThisWorkbook.Worksheets("Лист1").Name
    ThisWorkbook.Worksheets("Лист1").Range("A1") = 6
    ThisWorkbook.Worksheets("Лист1").Range("B2:B9").Font.Italic = True
    ThisWorkbook.Worksheets("Лист1").Range("B2:B9").Interior.Color = rgbRed

End Sub
Sub ObyavObektList()

    Dim sht As Worksheet
    Set sht = ThisWorkbook.Worksheets("Лист1")

    sht.Range("A1") = 6
    sht.Range("B2:B9").Font.Italic = True
    sht.Range("B2:B9").Interior.Color = rgbRed

End Sub

Вы также можете использовать ключевое слово With с объектом
листа, как показано в следующем примере.

Sub ObyavObektListWith()

    Dim sht As Worksheet
    Set sht = ThisWorkbook.Worksheets("Лист1")

    With sht
        .Range("A1") = 6
        .Range("B2:B9").Font.Italic = True
        .Range("B2:B9").Interior.Color = rgbRed
    End With

End Sub

Доступ к рабочему листу в двух словах

Из-за множества различных способов доступа к рабочему листу вы можете быть сбитыми с толку. Так что в этом разделе я собираюсь разбить его на простые термины.

  1. Если вы хотите использовать тот лист, который активен в данный момент, используйте ActiveSheet.
ActiveSheet.Range("A1") = 55

2. Если лист находится в той же книге, что и код, используйте кодовое имя.

3. Если рабочая таблица находится в другой рабочей книге, сначала получите рабочую книгу, а затем получите рабочую таблицу.

' Получить рабочую книгу
Dim wk As Workbook
Set wk = Workbooks.Open("C:ДокументыСчета.xlsx", ReadOnly:=True)
' Затем получите лист
Dim sh As Worksheet
Set sh = wk.Worksheets("Лист1")

Если вы хотите защитить пользователя от изменения имени листа, используйте функцию SheetFromCodeName из раздела «Имя кода».

' Получить рабочую книгу
Dim wk As Workbook
Set wk = Workbooks.Open("C:ДокументыСчета.xlsx", ReadOnly:=True)

' Затем получите лист
Dim sh As Worksheet
Set sh = SheetFromCodeName("sheetcodename",wk)

Добавить рабочий лист

Примеры в этом разделе показывают, как добавить новую
рабочую таблицу в рабочую книгу. Если вы не предоставите никаких аргументов для
функции Add, то новый
рабочий лист будет помещен перед активным рабочим листом.

Когда вы добавляете рабочий лист, он создается с именем по умолчанию, например «Лист4». Если вы хотите изменить имя, вы можете легко сделать это, используя свойство Name.

В следующем примере добавляется новый рабочий лист и изменяется имя на «Счета». Если лист с именем «Счета» уже существует, вы получите сообщение об ошибке.

Sub DobavitList()

    Dim sht As Worksheet

    ' Добавляет новый лист перед активным листом
    Set sht = ThisWorkbook.Worksheets.Add
    ' Установите название листа
    sht.Name = "Счета"

    ' Добавляет 3 новых листа перед активным листом
    ThisWorkbook.Worksheets.Add Count:=3

End Sub

В предыдущем примере вы добавляете листы по отношению к
активному листу. Вы также можете указать точную позицию для размещения листа.

Для этого вам нужно указать, какой лист новый лист должен
быть вставлен до или после. Следующий код показывает вам, как это сделать.

Sub DobavitListPervPosl()

    Dim shtNew As Worksheet
    Dim shtFirst As Worksheet, shtLast As Worksheet

    With ThisWorkbook

        Set shtFirst = .Worksheets(1)
        Set shtLast = .Worksheets(.Worksheets.Count)

        ' Добавляет новый лист на первую позицию в книге
        Set shtNew = Worksheets.Add(Before:=shtFirst)
        shtNew.Name = "FirstSheet"

        ' Добавляет новый лист к последней позиции в книге
        Set shtNew = Worksheets.Add(After:=shtLast)
        shtNew.Name = "LastSheet"

    End With

End Sub

Удалить рабочий лист

Чтобы удалить лист, просто вызовите Delete.

Dim sh As Worksheet
Set sh = ThisWorkbook.Worksheets("Лист12")
sh.Delete

Excel отобразит предупреждающее сообщение при удалении листа. Если вы хотите скрыть это сообщение, вы можете использовать код ниже:

Application.DisplayAlerts = False
sh.Delete
Application.DisplayAlerts = True

Есть два аспекта, которые нужно учитывать при удалении таблиц.

Если вы попытаетесь получить доступ к рабочему листу после
его удаления, вы получите ошибку «Subscript out of Range», которую мы видели в
разделе «Доступ к рабочему листу».

Dim sh As Worksheet
Set sh = ThisWorkbook.Worksheets("Лист2")
sh.Delete

' Эта строка выдаст «Subscript out of Range», так как «Лист2» не существует
Set sh = ThisWorkbook.Worksheets("Лист2")

Вторая проблема — когда вы назначаете переменную листа. Если вы попытаетесь использовать эту переменную после удаления листа, вы получите ошибку автоматизации, подобную этой:

Run-Time error -21147221080 (800401a8′) Automation Error

Если вы используете кодовое имя рабочего листа, а не
переменную, это приведет к сбою Excel,
а не к ошибке автоматизации.

В следующем примере показано, как происходят ошибки автоматизации.

sh.Delete

' Эта строка выдаст ошибку автоматизации
Debug.Assert sh.Name

Если вы назначите переменную Worksheet действительному рабочему листу, он будет работать нормально.

sh.Delete

' Назначить sh на другой лист
Set sh = Worksheets("Лист3")

' Эта строка будет работать нормально
Debug.Assert sh.Name

Цикл по рабочим листам

Элемент «Worksheets» — это набор рабочих листов, принадлежащих рабочей книге. Вы можете просмотреть каждый лист в коллекции рабочих листов, используя циклы «For Each» или «For».

В следующем примере используется цикл For Each.

Sub CiklForEach()

    ' Записывает «Привет Мир» в ячейку A1 для каждого листа
    Dim sht As Worksheet
    For Each sht In ThisWorkbook.Worksheets
         sht.Range("A1") = "Привет Мир"
    Next sht 

End Sub

В следующем примере используется стандартный цикл For.

Sub CiklFor()
    
    ' Записывает «Привет Мир» в ячейку A1 для каждого листа
    Dim i As Long
    For i = 1 To ThisWorkbook.Worksheets.Count
         ThisWorkbook.Worksheets(i).Range("A1") = "Привет Мир"
    Next sht

End Sub

Вы видели, как получить доступ ко всем открытым рабочим книгам и как получить доступ ко всем рабочим листам в ThisWorkbook. Давайте сделаем еще один шаг вперед — узнаем, как получить доступ ко всем рабочим листам во всех открытых рабочих книгах.

Примечание. Если вы используете код, подобный этому, для записи на листы, то сначала сделайте резервную копию всего, так как в итоге вы можете записать неверные данные на все листы.

Sub NazvVsehStr()

    ' Печатает рабочую книгу и названия листов для
    ' всех листов в открытых рабочих книгах
    Dim wrk As Workbook
    Dim sht As Worksheet
    For Each wrk In Workbooks
        For Each sht In wrk.Worksheets
            Debug.Print wrk.Name + ":" + sht.Name
        Next sht
    Next wrk

End Sub

Использование коллекции листов

Рабочая книга имеет еще одну коллекцию, похожую на Worksheets под названием Sheets. Это иногда путает пользователей. Чтобы понять, в первую очередь, вам нужно знать о типе листа, который является диаграммой.

В Excel есть возможность создать лист, который является диаграммой. Для этого нужно:

  1. Создать диаграмму на любом листе.
  2. Щелкнуть правой кнопкой мыши на графике и выбрать «Переместить».
  3. Выбрать первый вариант «Новый лист» и нажмите «ОК».

Теперь у вас есть рабочая книга, в которой есть типовые листы и лист-диаграмма.

  • Коллекция «Worksheets » относится ко всем рабочим листам в рабочей книге. Не включает в себя листы типа диаграммы.
  • Коллекция Sheets относится ко всем листам, принадлежащим книге, включая листы типовой диаграммы.

Ниже приведены два примера кода. Первый проходит через все
листы в рабочей книге и печатает название листа и тип листа. Второй пример
делает то же самое с коллекцией Worksheets.

Чтобы опробовать эти примеры, вы должны сначала добавить лист-диаграмму в свою книгу, чтобы увидеть разницу.

Sub KollSheets()

    Dim sht As Variant
    ' Показать название и тип каждого листа
    For Each sht In ThisWorkbook.Sheets
        Debug.Print sht.Name & " is type " & TypeName(sht)
    Next sht

End Sub

Sub KollWorkSheets()

    Dim sht As Variant
    ' Показать название и тип каждого листа
    For Each sht In ThisWorkbook.Worksheets
        Debug.Print sht.Name & " is type " & TypeName(sht)
    Next sht

End Sub

Если у вас нет листов диаграмм, то использование коллекции Sheets — то же самое, что использование коллекции WorkSheets.

Заключение

На этом мы завершаем статью о Worksheet VBA. Я надеюсь, что было полезным.

Три наиболее важных элемента Excel VBA — это рабочие книги, рабочие таблицы, диапазоны и ячейки.

Эти элементы будут использоваться практически во всем, что вы делаете. Понимание их сделает вашу жизнь намного проще и сделает изучение VBA увлекательнее.

Понравилась статья? Поделить с друзьями:
  • Excel vba столбец активной ячейки
  • Excel vba стиль ячейки
  • Excel vba стать продвинутым пользователем за неделю
  • Excel vba статус бар
  • Excel vba стандартный модуль