Excel vba this document

Содержание

  1. Свойство Application.ThisWorkbook (Excel)
  2. Синтаксис
  3. Примечания
  4. Пример
  5. Поддержка и обратная связь
  6. Excel vba this document
  7. Working with Document Objects
  8. Creating a new document
  9. Opening a document
  10. Saving an existing document
  11. Saving a new document
  12. Closing documents
  13. Activating a document
  14. Determining if a document is open
  15. Referring to the active document
  16. Support and feedback
  17. Объект ThisDocument (Visio)
  18. Замечания
  19. Поддержка и обратная связь
  20. Workbook object (Excel)
  21. Remarks
  22. Example
  23. Events
  24. Methods
  25. Properties
  26. See also
  27. Support and feedback

Свойство Application.ThisWorkbook (Excel)

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

Синтаксис

expression. Thisworkbook

выражение: переменная, представляющая объект Application.

Примечания

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

Свойство Workbooks может завершиться ошибкой, так как имя книги, вероятно, изменилось при создании надстройки. Эта книга всегда возвращает книгу, в которой выполняется код.

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

Это свойство можно использовать только из Microsoft Excel. Его нельзя использовать для доступа к книге из любого другого приложения.

Пример

В этом примере закрывается книга, содержащая пример кода. Изменения в книге, если таковые есть, не сохраняются.

Поддержка и обратная связь

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

Источник

Excel vba this document

In these examples, we generate Microsoft Word Documents with various formatting features using the Microsoft Excel VBA scripting language. These techniques can have many useful applications. For instance if you have a list of data like a price or product list in Excel that you want to present in a formatted Word Document, these techniques can prove useful.

In these examples, we assume the reader has at least basic knowledge of VBA, so we will not go over basics of creating and running scripts. This code has been tested on Microsoft Word and Excel 2007. Some changes may be required for other versions of Word and Excel.

Function that demonstrates VBA writing to a Microsoft Word document

The following code illustrates the use of VBA Word.Application object and related properties. In this example, we create a new Word Document add some text.

Some VBA Vocabulary

ParagraphFormat Represents all the formatting for a paragraph.

output in MS Word:

Inserting a Table of Contents into Word Document using Excel VBA

In this example, we generate a Table of Contents into a Word Document using Excel VBA

Some VBA Vocabulary

ActiveDocument.TablesOfContents.Add The TablesOfContents property to return the TablesOfContents collection. Use the Add method to add a table of contents to a document.

Some TablesOfContents Parameters

Range The range where you want the table of contents to appear. The table of contents replaces the range, if the range isn’t collapsed.

UseHeadingStyles True to use built-in heading styles to create the table of contents. The default value is True.

UpperHeadingLevel The starting heading level for the table of contents. Corresponds to the starting value used with the o switch for a Table of Contents (TOC) field. The default value is 1.

LowerHeadingLevel The ending heading level for the table of contents. Corresponds to the ending value used with the o switch for a Table of Contents (TOC) field. The default value is 9.

output Word Table in MS Word:

Write Microsoft Word Tabs

A function that writes tabbed content to a Microsoft Word Document. Note in each iteration, we change the value of the leader character (characters that are inserted in the otherwise blank area created by the tab).

Some VBA Vocabulary

.TabStops.Add Use the TabStops property to return the TabStops collection. In the example above, nprogram adds a tab stop positioned at 0, 2.5 and 5 inches.

output in MS Word:

Write Microsoft Word Tables

In this example, we generate a Microsoft Table using Excel VBA

Some VBA vocabulary

Table.Add Table object that represents a new, blank table added to a document.

Range The range where you want the table to appear. The table replaces the range, if the range isn’t collapsed.

NumRows The number of rows you want to include in the table.

NumColumns The number of columns you want to include in the table.

DefaultTableBehavior Sets a value that specifies whether Microsoft Word automatically resizes cells in tables to fit the cells� contents (AutoFit). Can be either of the following constants: wdWord8TableBehavior (AutoFit disabled) or wdWord9TableBehavior (AutoFit enabled). The default constant is wdWord8TableBehavior.

AutoFitBehavior Sets the AutoFit rules for how Word sizes tables. Can be one of the WdAutoFitBehavior constants.

output in MS Word:

Write Microsoft Word bullet list

In this example, we write with bullet list and outline numbers with Excel VBA

Источник

Working with Document Objects

In Visual Basic, the methods for modifying files are methods of the Document object or the Documents collection. This topic includes Visual Basic examples related to the tasks identified in the following sections.

Creating a new document

The Documents collection includes all of the open documents. To create a new document, use the Add method to add a Document object to the Documents collection. The following instruction creates a document.

A better way to create a document is to assign the return value to an object variable. The Add method returns a Document object that refers to the new document. In the following example, the Document object returned by the Add method is assigned to an object variable. Then, several properties and methods of the Document object are set. You can easily control the new document using an object variable.

Opening a document

To open an existing document, use the Open method with the Documents collection. The following instruction opens a document named Sample.doc located in the MyFolder folder.

Saving an existing document

To save a single document, use the Save method with the Document object. The following instruction saves the document named Sales.doc.

You can save all open documents by applying the Save method to the Documents collection. The following instruction saves all open documents.

Saving a new document

To save a single document, use the SaveAs2 method with a Document object. The following instruction saves the active document as «Temp.doc» in the current folder.

The FileName argument can include only the file name or the complete path (for example, «C:DocumentsTemporary File.doc»).

Closing documents

To close a single document, use the Close method with a Document object. The following instruction closes and saves the document named Sales.doc.

You can close all open documents by applying the Close method of the Documents collection. The following instruction closes all documents without saving changes.

The following example prompts the user to save each document before the document is closed.

Activating a document

To change the active document, use the Activate method with a Document object. The following instruction activates the open document named Sales.doc.

Determining if a document is open

To determine if a document is open, you can enumerate the Documents collection by using a For Each. Next statement. The following example activates the document named Sample.doc if the document is open, or opens Sample.doc if it is not currently open.

Referring to the active document

Instead of referring to a document by name or by index number—for example, Documents(«Sales.doc») —the ActiveDocument property returns a Document object that refers to the active document (the document with the focus). The following example displays the name of the active document, or if there are no documents open, it displays a message.

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

Источник

Объект ThisDocument (Visio)

Проект Visual Basic для приложений (VBA) каждого документа Visio содержит модуль класса ThisDocument. При указании ссылки из кода в проекте объект ThisDocument возвращает ссылку на объект Document проекта.

Имя документа проекта VBA можно отобразить в окне сообщения с помощью следующей инструкции.

Первую страницу документа проекта VBA можно получить с помощью следующего кода.

Замечания

Если вы хотите управлять документом, связанным с проектом VBA, используйте объект ThisDocument .

Если вы хотите управлять документом, но не обязательно документом, связанным с проектом VBA, получите объект Document из коллекции Documents .

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

Вы можете расширить набор свойств и методов объекта Document проекта, добавив открытые свойства и методы в модуль класса ThisDocument этого проекта. Новые методы и свойства предоставляются так же, как и встроенные методы и свойства, реализованные Visio.

Новые методы и свойства недоступны при ссылке на другие объекты Document . Объект ThisDocument недоступен для кода, который не является частью проекта VBA документа Visio.

Поддержка и обратная связь

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

Источник

Workbook object (Excel)

Represents a Microsoft Excel workbook.

The Workbook object is a member of the Workbooks collection. The Workbooks collection contains all the Workbook objects currently open in Microsoft Excel.

The ThisWorkbook property of the Application object returns the workbook where the Visual Basic code is running. In most cases, this is the same as the active workbook. However, if the Visual Basic code is part of an add-in, the ThisWorkbook property won’t return the active workbook. In this case, the active workbook is the workbook calling the add-in, whereas the ThisWorkbook property returns the add-in workbook.

If you are creating an add-in from your Visual Basic code, you should use the ThisWorkbook property to qualify any statement that must be run on the workbook that you compile into the add-in.

Example

Use Workbooks (index), where index is the workbook name or index number, to return a single Workbook object. The following example activates workbook one.

The index number denotes the order in which the workbooks were opened or created. Workbooks(1) is the first workbook created, and Workbooks(Workbooks.Count) is the last one created. Activating a workbook doesn’t change its index number. All workbooks are included in the index count, even if they are hidden.

The Name property returns the workbook name. You cannot set the name by using this property; if you need to change the name, use the SaveAs method to save the workbook under a different name.

The following example activates Sheet1 in the workbook named Cogs.xls (the workbook must already be open in Microsoft Excel).

The ActiveWorkbook property of the Application object returns the workbook that’s currently active. The following example sets the name of the author for the active workbook.

This example emails a worksheet tab from the active workbook by using a specified email address and subject. To run this code, the active worksheet must contain the email address in cell A1, the subject in cell B1, and the name of the worksheet to send in cell C1.

Events

Methods

Properties

See also

Support and feedback

Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

Источник

Home / VBA / VBA ThisWorkbook (Current Excel File)

In VBA, you can use the ThisWorkbook property to refer to the workbook where you are writing the code. When you use it, you get access to all the properties and methods of the current workbook. In simple words, you can execute all the tasks in the current workbook without using the name.

Let’s say you want to count the sheets from the current workbook. The code you need to write would be like the following.

Sub vba_thisworkbook()
MsgBox ThisWorkbook.Sheets.Count
End Sub
vba-thisworkbook

When you run this code shows you a message box with the count of the sheets that you have in the current workbook.

message-box-with-the-count-of-sheets

As I said, when you use the ThisWorkbook it gives you access to the properties and method for the current workbook. You can see all of these when you enter a (.) dot to see the complete list.

access-to-the-properties

Helpful Links: Run a Macro – Macro Recorder – Visual Basic Editor – Personal Macro Workbook

Using ThisWorkbook with a Variable

Next, I’ll show you a real-life code example to declare a variable to use the ThisWorkbook property. Let’s say you want to perform multiple activities in the current workbook.

Sub vba_thisworkbook()
Dim myWB As Workbook
Set myWB = ThisWorkbook
With myWB
    .Activate
    .Sheets(1).Activate
    .Range("A1") = Now
    .Save
    .Close
End With
End Sub

In the first part of this code, you have a variable and then assign “ThisWorkbook” property to it. And then in the second part, you have the WITH STATEMENT to perform multiple activities with the current variable.

ActiveWorkBook Vs. ThisWorkbook

Let me explain it with a simple analogy, so, be with me for the next 2 minutes.

You have two workbooks open at the same time (Book1 and Book2). You are writing code in book1 but book2 is active at this point. So when you run that code which refers to the ActiveWorkbook it will perform that activity in Book2.

But when you use the ThisWorkbook VBA always refers to the workbook where code is being written.

Here’s the thing: It’s always preferable to use the ThisWorkbook because it eliminates the chances of any error.

More on VBA Workbooks

VBA Save Workbook | VBA Close Workbook | VBA Delete Workbook | VBA Rename Workbook | VBA Activate Workbook | VBA Combine Workbook | VBA Protect Workbook (Unprotect) | VBA Check IF a Workbook is Open | VBA Open Workbook | VBA Check IF an Excel Workbook Exists in a Folder| VBA Create New Workbook (Excel File)

  • VBA Workbook

Using Excel VBA to create Microsoft Word documents

In these examples, we generate Microsoft Word Documents with various formatting features using
the Microsoft Excel VBA scripting language. These techniques can have many useful applications.
For instance if you have a list of data like a price or product list in Excel that you want to present
in a formatted Word Document, these techniques can prove useful.

In these examples, we assume the reader has at least basic knowledge of VBA, so we will not
go over basics of creating and running scripts. This code has been tested on Microsoft Word and Excel
2007. Some changes may be required for other versions of Word and Excel.

Writing to Word
Inserting a Table of Contents
Inserting Tabs
Inserting Tables
Inserting Bullet List
more on Inserting Tables
Multiple Features

Function that demonstrates VBA writing to a Microsoft Word document

The following code illustrates the use of VBA Word.Application object and related properties.
In this example, we create a new Word Document add some text.

    'In Tools > References, add reference to "Microsoft Word XX.X Object Library" before running.
	
    'Early Binding
    Dim wdApp As Word.Application
    Set wdApp = New Word.Application
    
    'Alternatively, we can use Late Binding
    'Dim wdApp As Object
    'Set wdApp = CreateObject("word.Application")
        
    With wdApp
        .Visible = True
        .Activate
        .Documents.Add
        
        With .Selection
            .ParagraphFormat.Alignment = wdAlignParagraphCenter
            .Font.Bold = True
            .Font.Name = "arial"
            .Font.Size = 14
            .TypeText ("My Heading")
            .TypeParagraph            
        End With
    End With 

Some VBA Vocabulary

ParagraphFormat
Represents all the formatting for a paragraph.

output in MS Word:

Inserting a Table of Contents into Word Document using Excel VBA

In this example, we generate a Table of Contents into a Word Document using Excel VBA

Sub sAddTableOfContents()
    
    Dim wdApp As Word.Application
    Set wdApp = New Word.Application
	
    'Alternatively, we can use Late Binding
    'Dim wdApp As Object
    'Set wdApp = CreateObject("word.Application")
    
    Dim wdDoc As Word.Document
    Set wdDoc = wdApp.Documents.Add
    
    ' Note we define a Word.range, as the default range wouled be an Excel range!
    Dim myWordRange As Word.range
    Dim Counter As Integer
    
    wdApp.Visible = True
    wdApp.Activate
    
    'Insert Some Headers
    With wdApp
        For Counter = 1 To 5
            .Selection.TypeParagraph
            .Selection.Style = "Heading 1"
            .Selection.TypeText "A Heading Level 1"
            .Selection.TypeParagraph
            .Selection.TypeText "Some details"
        Next
    End With

    ' We want to put table of contents at the top of the page
	Set myWordRange = wdApp.ActiveDocument.range(0, 0)
    
    wdApp.ActiveDocument.TablesOfContents.Add _
     range:=myWordRange, _
     UseFields:=False, _
     UseHeadingStyles:=True, _
     LowerHeadingLevel:=3, _
     UpperHeadingLevel:=1

End Sub

Some VBA Vocabulary

ActiveDocument.TablesOfContents.Add
The TablesOfContents property to return the TablesOfContents collection.
Use the Add method to add a table of contents to a document.

Some TablesOfContents Parameters

Range The range where you want the table of contents to appear. The table of contents replaces the range, if the range isn’t collapsed.

UseHeadingStyles True to use built-in heading styles to create the table of contents. The default value is True.

UpperHeadingLevel The starting heading level for the table of contents. Corresponds to the starting value used with the o switch for a Table of Contents (TOC) field. The default value is 1.

LowerHeadingLevel The ending heading level for the table of contents. Corresponds to the ending value used with the o switch for a Table of Contents (TOC) field. The default value is 9.

output Word Table in MS Word:

Write Microsoft Word Tabs

A function that writes tabbed content to a Microsoft Word Document. Note in each iteration, we change the
value of the leader character (characters that are inserted in the otherwise blank area created by the tab).

Public Sub sWriteMicrosoftTabs()

    'In Tools > References, add reference to "Microsoft Word XX.X Object Library" before running.
    
    'Early Binding
    Dim wdApp As Word.Application
    Set wdApp = New Word.Application
    
    'Alternatively, we can use Late Binding
    'Dim wdApp As Object
    'Set wdApp = CreateObject("word.Application")
        
    With wdApp
        .Visible = True
        .Activate
        .Documents.Add
    
        For Counter = 1 To 3
            .Selection.TypeText Text:=Counter & " - Tab 1 "
            
            ' position to 2.5 inches
            .Selection.Paragraphs.TabStops.Add Position:=Application.InchesToPoints(2.5), _
                Leader:=Counter, Alignment:=wdAlignTabLeft
            
            .Selection.TypeText Text:=vbTab & " - Tab 2 "
            
            ' position to 5 inches
            .Selection.Paragraphs.TabStops.Add Position:=Application.InchesToPoints(5), _
                Leader:=Counter, Alignment:=wdAlignTabLeft
            
            .Selection.TypeText Text:=vbTab & " - Tab 3 "
                    
            .Selection.TypeParagraph
        Next Counter
        
    End With
End Sub

Some VBA Vocabulary

.TabStops.Add Use the TabStops property to return the TabStops collection. In the example above,
nprogram adds a tab stop positioned at 0, 2.5 and 5 inches.

output in MS Word:

Write Microsoft Word Tables

In this example, we generate a Microsoft Table using Excel VBA

Sub sWriteMSWordTable ()
 
    'In Tools > References, add reference to "Microsoft Word XX.X Object Library" before running.
    
    'Early Binding
    Dim wdApp As Word.Application
    Set wdApp = New Word.Application
    
    'Alternatively, we can use Late Binding
    'Dim wdApp As Object
    'Set wdApp = CreateObject("word.Application")
        
    With wdApp
        .Visible = True
        .Activate
        .Documents.Add
        
        With .Selection
        
            .Tables.Add _
                    Range:=wdApp.Selection.Range, _
                    NumRows:=1, NumColumns:=3, _
                    DefaultTableBehavior:=wdWord9TableBehavior, _
                    AutoFitBehavior:=wdAutoFitContent
            
            For counter = 1 To 12
                .TypeText Text:="Cell " & counter
                If counter <> 12 Then
                    .MoveRight Unit:=wdCell
                End If
            Next
        
        End With
        
    End With

End Sub

Some VBA vocabulary

Table.AddTable object that represents a new, blank table added to a document.

Table.Add properties

Range The range where you want the table to appear. The table replaces the range, if the range isn’t collapsed.

NumRows The number of rows you want to include in the table.

NumColumns The number of columns you want to include in the table.

DefaultTableBehavior Sets a value that specifies whether Microsoft Word automatically resizes cells in tables to fit the cells� contents (AutoFit). Can be either of the following constants: wdWord8TableBehavior (AutoFit disabled) or wdWord9TableBehavior (AutoFit enabled). The default constant is wdWord8TableBehavior.

AutoFitBehavior Sets the AutoFit rules for how Word sizes tables. Can be one of the WdAutoFitBehavior constants.

output in MS Word:

Write Microsoft Word bullet list

In this example, we write with bullet list and outline numbers with Excel VBA

    'In Tools > References, add reference to "Microsoft Word XX.X Object Library" before running.
    
    'Early Binding
    Dim wdApp As Word.Application
    Set wdApp = New Word.Application
    
    'Alternatively, we can use Late Binding
    'Dim wdApp As Object
    'Set wdApp = CreateObject("word.Application")
    
    With wdApp
        .Visible = True
        .Activate
        .Documents.Add
        ' turn on bullets
        .ListGalleries(wdBulletGallery).ListTemplates(1).Name = ""
        .Selection.Range.ListFormat.ApplyListTemplate ListTemplate:=.ListGalleries(wdBulletGallery).ListTemplates(1), _
            continuepreviouslist:=False, applyto:=wdListApplyToWholeList, defaultlistbehavior:=wdWord9ListBehavior
        
        With .Selection
            .ParagraphFormat.Alignment = wdAlignParagraphLeft
            .Font.Bold = False
            .Font.Name = "Century Gothic"
            .Font.Size = 12
            .TypeText ("some details")
            .TypeParagraph
            .TypeText ("some details")
            .TypeParagraph
        End With
        
        ' turn off bullets
        .Selection.Range.ListFormat.RemoveNumbers wdBulletGallery
        
        With .Selection
            .ParagraphFormat.Alignment = wdAlignParagraphLeft
            .TypeText ("some details")
            .TypeParagraph
            .TypeText ("some details")
            .TypeParagraph
            
        End With
        
        ' turn on outline numbers
        .ListGalleries(wdOutlineNumberGallery).ListTemplates(1).Name = ""
        .Selection.Range.ListFormat.ApplyListTemplate ListTemplate:=.ListGalleries(wdOutlineNumberGallery).ListTemplates(1), _
            continuepreviouslist:=False, applyto:=wdListApplyToWholeList, defaultlistbehavior:=wdWord9ListBehavior
        
        With .Selection
            .ParagraphFormat.Alignment = wdAlignParagraphLeft
            .TypeText ("some details")
            .TypeParagraph
            .TypeText ("some details")
            
        End With
        
    End With

output in MS Word:

Another example of Writing Tables to Microsoft Word

In this example we will create a word document with 20 paragraphs. Each paragraph will have a header with a header style element

    
   'In Tools > References, add reference to "Microsoft Word XX.X Object Library" before running.
    Dim wdApp As Word.Application
    Dim wdDoc As Word.Document

    Set wdApp = New Word.Application
    wdApp.Visible = True
    
    
    Dim x As Integer
    Dim y As Integer
    
    wdApp.Visible = True
    wdApp.Activate
    wdApp.Documents.Add
            
    wdApp.ActiveDocument.Tables.Add Range:=wdApp.Selection.Range, NumRows:=2, NumColumns:= _
        2, DefaultTableBehavior:=wdWord9TableBehavior, AutoFitBehavior:= _
        wdAutoFitFixed
                
    With wdApp.Selection.Tables(1)
        If .Style <> "Table Grid" Then
            .Style = "Table Grid"
        End If
        .ApplyStyleHeadingRows = True
        .ApplyStyleLastRow = False
        .ApplyStyleFirstColumn = True
        .ApplyStyleLastColumn = False
        .ApplyStyleRowBands = True
        .ApplyStyleColumnBands = False
    End With
            
    With wdApp.Selection
        
        For x = 1 To 2
            ' set style name
            .Style = "Heading 1"
            .TypeText "Subject" & x
            .TypeParagraph
            .Style = "No Spacing"
            For y = 1 To 20
                .TypeText "paragraph text "
            Next y
            .TypeParagraph
        Next x
    
        ' new paragraph
        .TypeParagraph
        
        ' toggle bold on
        .Font.Bold = wdToggle
        .TypeText Text:="show some text in bold"
        .TypeParagraph
        
        'toggle bold off
        .Font.Bold = wdToggle
        .TypeText "show some text in regular front weight"
        .TypeParagraph
        
        
    End With
        
    

Some VBA vocabulary

TypeText

Inserts specified text at the beginning of the current selection. The selection is turned into an insertion point at the end of the inserted text.
If Options.ReplaceSelection = True then the original selection will be replaced. This behaves exactly the same as typing some text at the keyboard.

TypeParagraph

Insert a new blank paragraph. The selection is turned into an insertion point after the inserted paragraph mark. If Options.ReplaceSelection = True then the original selection will be replaced. This behaves exactly the same as pressing the Enter key.

output in MS Word:

Generating a Word table with VBA
	'In Tools > References, add reference to "Microsoft Word XX.X Object Library" before running.

	Dim wdApp As Word.Application
	Dim wdDoc As Word.Document
	Dim r As Integer

	Set wdApp = CreateObject("Word.Application")
	wdApp.Visible = True

	Set wdDoc = wdApp.Documents.Add
	wdApp.Activate

	Dim wdTbl As Word.Table
	Set wdTbl = wdDoc.Tables.Add(Range:=wdDoc.Range, NumRows:=5, NumColumns:=1)

	With wdTbl

		.Borders(wdBorderTop).LineStyle = wdLineStyleSingle
		.Borders(wdBorderLeft).LineStyle = wdLineStyleSingle
		.Borders(wdBorderBottom).LineStyle = wdLineStyleSingle
		.Borders(wdBorderRight).LineStyle = wdLineStyleSingle
		.Borders(wdBorderHorizontal).LineStyle = wdLineStyleSingle
		.Borders(wdBorderVertical).LineStyle = wdLineStyleSingle
		
		For r = 1 To 5
			.Cell(r, 1).Range.Text = ActiveSheet.Cells(r, 1).Value
		Next r
	End With

	

output in MS Word:

Option Explicit
Dim wdApp As Word.Application
 
Sub extractToWord()

   'In Tools > References, add reference to "Microsoft Word 12 Object Library" before running.
   
    Dim lastCell
    Dim rng As Range
    Dim row As Range
    Dim cell As Range
    Dim arrayOfColumns
    arrayOfColumns = Array("", "", "", "", "", "", "", "", "", "", "", "", "", "", "")
    Dim thisRow As Range
    Dim thisCell As Range
    Dim myStyle As String
    
    ' get last cell in column B
    lastCell = getLastCell()
    
    Set rng = Range("B2:H" & lastCell)
    
    'iterate through rows
    For Each thisRow In rng.Rows
            
        'iterate through cells in row row
        For Each thisCell In thisRow.Cells

            If thisCell.Value = arrayOfColumns(thisCell.Column) Or thisCell.Value = "" Then
            ' do nothing
                ''frWriteLine thisCell.Value, "Normal"
                ''frWriteLine arrayOfColumns(thisCell.Column), "Normal"
                  If thisCell.Value = arrayOfColumns(thisCell.Column) Or thisCell.Value = "" Then
                  End If
                  
            Else
                myStyle = "Normal"
                Select Case thisCell.Column
                    Case 2
                        myStyle = "Heading 1"
                    Case 3
                        myStyle = "Heading 2"
                    Case 4
                        myStyle = "Heading 3"
                    Case Is > 5
                        myStyle = "Normal"
                    
                End Select
                    
                frWriteLine thisCell.Value, myStyle
            End If
        
        arrayOfColumns(thisCell.Column) = thisCell.Value
    
      Next thisCell
    Next thisRow
    
End Sub

Public Function getLastCell() As Integer

    Dim lastRowNumber As Long
    Dim lastRowString As String
    Dim lastRowAddress As String
         
    With ActiveSheet
        getLastCell = .Cells(.Rows.Count, 2).End(xlUp).row
    End With
    
End Function

Public Function frWriteLine(someData As Variant, myStyle As String)
    
    If wdApp Is Nothing Then
        
        Set wdApp = New Word.Application
        With wdApp
            .Visible = True
            .Activate
            .Documents.Add
        End With
            
    End If
    
    With wdApp
        
        With .Selection
            .ParagraphFormat.Alignment = wdAlignParagraphCenter
            .Style = myStyle
            .TypeText (someData)
            .TypeParagraph
        End With
    End With
    
End Function

output in MS Word:

Открытие книги Excel из кода VBA. Проверка существования книги. Создание новой книги, обращение к открытой книге и ее закрытие. Методы Open, Add и Close.

Открытие существующей книги

Существующая книга открывается из кода VBA Excel с помощью метода Open:

Workbooks.Open Filename:=«D:test1.xls»

или

Workbooks.Open («D:test1.xls»)

В кавычках указывается полный путь к открываемому файлу Excel. Если такой файл не существует, произойдет ошибка.

Проверка существования файла

Проверить существование файла можно с помощью функции Dir. Проверка существования книги Excel:

If Dir(«D:test1.xls») = «» Then

    MsgBox «Файл не существует»

Else

    MsgBox «Файл существует»

End If

Или, если файл (книга Excel) существует, можно сразу его открыть:

If Dir(«D:test1.xls») = «» Then

    MsgBox «Файл не существует»

Else

    Workbooks.Open Filename:=«D:test1.xls»

End If

Создание новой книги

Новая рабочая книга Excel создается в VBA с помощью метода Add:

Созданную книгу, если она не будет использоваться как временная, лучше сразу сохранить:

Workbooks.Add

ActiveWorkbook.SaveAs Filename:=«D:test2.xls»

В кавычках указывается полный путь сохраняемого файла Excel, включая присваиваемое имя, в примере — это «test2.xls».

Обращение к открытой книге

Обращение к активной книге:

Обращение к книге с выполняемым кодом:

Обращение к книге по имени:

Workbooks(«test1.xls»)

Workbooks(«test2.xls»)

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

Открытая рабочая книга закрывается из кода VBA Excel с помощью метода Close:

Workbooks(«test1.xlsx»).Close

Если закрываемая книга редактировалась, а внесенные изменения не были сохранены, тогда при ее закрытии Excel отобразит диалоговое окно с вопросом: Вы хотите сохранить изменения в файле test1.xlsx? Чтобы файл был закрыт без сохранения изменений и вывода диалогового окна, можно воспользоваться параметром метода Close — SaveChanges:

Workbooks(«test1.xlsx»).Close  SaveChanges:=False

или

Workbooks(«test1.xlsx»).Close  (False)

Закрыть книгу Excel из кода VBA с сохранением внесенных изменений можно также с помощью параметра SaveChanges:

Workbooks(«test1.xlsx»).Close  SaveChanges:=True

или

Workbooks(«test1.xlsx»).Close (True)


Фразы для контекстного поиска: открыть книгу, открытие книги, создать книгу, создание книги, закрыть книгу, закрытие книги, открыть файл Excel, открытие файла Excel, существование книги, обратиться к открытой книге.


Get our FREE VBA eBook of the 30 most useful Excel VBA macros.

Automate Excel so that you can save time and stop doing the jobs a trained monkey could do.

Claim your free eBook


VBA Code Snippets

In the Windows Explorer it is possible to view a document’s properties.  Right-click on the file and select Properties.

There is useful information in here, such as author, creation date, last saved date etc.  The good news is, we can access this information using VBA with  the BuiltinDocumentProperties Property.

Not all document properties are populated with data, as it depends on the file type. For example, Excel files do not have data about the number of slides property, but a PowerPoint file does.  Yet, both Excel and PowerPoint files have a number of slides property, it’s just not used in all circumstances.

The basic VBA code

'Finding the author of the ActiveWorkbook
Debug.Print ActiveWorkbook.BuiltinDocumentProperties("Author")

'Finding the creation date of another workbook
Dim Wb As Workbook
Set Wb = Workbooks("myFileTest.xlsx")
Debug.Print Wb.BuiltinDocumentProperties("Creation date")

Working with closed files

By using the BuiltinDocumentProperties there is no way to read the properties from a closed file.  Therefore it is necessary to open the file, read the properties, then close the file.

'Find the Last saved time of a currently closed file
Dim Wb As Workbook
Set Wb = Workbooks.Open("C:UsersmarksDocumentsmyFileTest.xlsx")
Debug.Print Wb.BuiltinDocumentProperties("Last save time")
Wb.Close

Note: Take a look in the comments section below as there appears to be a way to read and change properties on a closed file.  But that is outside the scope of this post.

Catching errors

Referencing a property which does not have any information will throw and error.

Builtin Properties - Catching Error

It is possible to catch the errors so that you know the value is blank:

'Catching errors when there is no value
Dim fileProperty As Variant
fileProperty = "Number of slides"

On Error Resume Next
Debug.Print ActiveWorkbook.BuiltinDocumentProperties(fileProperty)
If Err.Number <> 0 Then
    Debug.Print fileProperty & " is blank"
End If
On Error GoTo 0

All the available properties

The available properties are:

Title
Subject
Author
Keywords
Comments
Template
Last author
Revision number
Application name
Last print date
Creation date
Last save time
Total editing time
Number of pages
Number of words
Number of characters
Security
Category
Format
Manager
Company
Number of bytes
Number of lines
Number of paragraphs
Number of slides
Number of notes
Number of hidden Slides
Number of multimedia clips
Hyperlink base
Number of characters (with spaces)
Content type
Content status
Language
Document version

It is also possible to loop through and list all of the available properties:

'List all the file properties available
Dim fileProperty As Variant
For Each fileProperty In ActiveWorkbook.BuiltinDocumentProperties
    Debug.Print fileProperty.Name
Next fileProperty


Headshot Round

About the author

Hey, I’m Mark, and I run Excel Off The Grid.

My parents tell me that at the age of 7 I declared I was going to become a qualified accountant. I was either psychic or had no imagination, as that is exactly what happened. However, it wasn’t until I was 35 that my journey really began.

In 2015, I started a new job, for which I was regularly working after 10pm. As a result, I rarely saw my children during the week. So, I started searching for the secrets to automating Excel. I discovered that by building a small number of simple tools, I could combine them together in different ways to automate nearly all my regular tasks. This meant I could work less hours (and I got pay raises!). Today, I teach these techniques to other professionals in our training program so they too can spend less time at work (and more time with their children and doing the things they love).


Do you need help adapting this post to your needs?

I’m guessing the examples in this post don’t exactly match your situation. We all use Excel differently, so it’s impossible to write a post that will meet everybody’s needs. By taking the time to understand the techniques and principles in this post (and elsewhere on this site), you should be able to adapt it to your needs.

But, if you’re still struggling you should:

  1. Read other blogs, or watch YouTube videos on the same topic. You will benefit much more by discovering your own solutions.
  2. Ask the ‘Excel Ninja’ in your office. It’s amazing what things other people know.
  3. Ask a question in a forum like Mr Excel, or the Microsoft Answers Community. Remember, the people on these forums are generally giving their time for free. So take care to craft your question, make sure it’s clear and concise.  List all the things you’ve tried, and provide screenshots, code segments and example workbooks.
  4. Use Excel Rescue, who are my consultancy partner. They help by providing solutions to smaller Excel problems.

What next?
Don’t go yet, there is plenty more to learn on Excel Off The Grid.  Check out the latest posts:

Понравилась статья? Поделить с друзьями:
  • Excel vba textbox фокус на textbox
  • Excel vba textbox события
  • Excel vba textbox on enter
  • Excel vba textbox format
  • Excel vba text color