Vba excel открыть книгу по пути

Открытие книги 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, существование книги, обратиться к открытой книге.


 

deathogre

Пользователь

Сообщений: 14
Регистрация: 09.02.2016

Здрасьте. Как программно открыть книгу эксель и сохранить эту книгу (объект) в глобальной переменной?

 

Юрий М

Модератор

Сообщений: 60575
Регистрация: 14.09.2012

Контакты см. в профиле

#2

13.02.2016 13:53:37

1. Открытие нужной книги запишите макрорекордером — получите готовый код.
2.

Код
Dim Wb As Workbook
Set Wb = ActiveWorkbook
 

Hugo

Пользователь

Сообщений: 23251
Регистрация: 22.12.2012

#3

13.02.2016 13:53:58

Код
Set wb = Workbooks.Open(filename)
 

deathogre

Пользователь

Сообщений: 14
Регистрация: 09.02.2016

Мне нужно открыть книгу из другой книги

 

Юрий М

Модератор

Сообщений: 60575
Регистрация: 14.09.2012

Контакты см. в профиле

#5

13.02.2016 13:55:02

Цитата
deathogre написал:
Мне нужно открыть книгу из другой книги

И что?

 

deathogre

Пользователь

Сообщений: 14
Регистрация: 09.02.2016

#6

13.02.2016 14:02:59

Объявил глобальную переменную в модуле ЭтаКнига

Код
Public Главнейшая As Workbook

открыл книгу в модуле АктивХ формы

Код
ChDir "\Margo123Тест"
Workbooks.Open Filename:="\Margo123Тест6.02.2016.xlsm"
Set ЭтаКнига.Главнейшая = Workbooks("\Margo123Тест6.02.2016.xlsm")

выдает ошибку на 3 строке, Run-time error 9 Subscript out of range

 

Юрий М

Модератор

Сообщений: 60575
Регистрация: 14.09.2012

Контакты см. в профиле

Глобальную переменную в стандартный модуль — будет доступна всюду. И  модуль не нужно указывать.
Если книга уже открыта — зачем указывать путь?

 

deathogre

Пользователь

Сообщений: 14
Регистрация: 09.02.2016

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

 

Юрий М

Модератор

Сообщений: 60575
Регистрация: 14.09.2012

Контакты см. в профиле

#9

13.02.2016 14:21:54

Обращайтесь — кто мешает? )

Код
Public Wb As Workbook
Sub Макрос1()
    Workbooks.Open Filename:="D:ОтчетыСостояние ТС.xlsm"
    Set Wb = ActiveWorkbook
    MsgBox Wb.Name
End Sub
 

KL

Пользователь

Сообщений: 2186
Регистрация: 01.01.2013

#10

13.02.2016 14:53:27

Или даже так:

Код
Public Wb As Workbook
Sub Макрос1()
    Set Wb = Workbooks.Open (Filename:="D:ОтчетыСостояние ТС.xlsm")
    MsgBox Wb.Name
End Sub

KL

 

KL

Пользователь

Сообщений: 2186
Регистрация: 01.01.2013

Кстати, ChDir для открытия книги таким способом не нужен. Он нужен для функции GetOpenFileName, которая, кстати, тоже уже не нужна, т.к. уже давно есть Application.FileDialog(msoFileDialogOpen) :)

 

Юрий М

Модератор

Сообщений: 60575
Регистрация: 14.09.2012

Контакты см. в профиле

Кирилл, а рекордер упорно пишет  ChDir ))

 

KL

Пользователь

Сообщений: 2186
Регистрация: 01.01.2013

Юр, ну мало ли что на заборах пишут. Рекордер еще и Select обожает :)

 

Юрий М

Модератор

Сообщений: 60575
Регистрация: 14.09.2012

Контакты см. в профиле

#14

13.02.2016 15:16:46

))

To open a workbook using VBA, you need to use the “Workbook.Open” method and specify the path of the file (make sure to specify the full path to the workbook with name and extension file type). This method has a total of fifteen optional arguments which you can use to deal with different kinds of files.

In this tutorial, we will explore it in detail and look at an alternative method that you can use.

Steps to Open a Workbook using VBA

  1. To start the code, use the “Workbooks” object.
  2. Type a dot (.) after that and select the Open method from the list.
  3. Specify the file path in the first argument and make sure to enclose it in double quotation marks.
  4. In the end, run the code to open the workbook.
Sub vba_open_workbook()
Workbooks.Open "C:UsersDellDesktopmyFile.xlsx"
End Sub

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

Workbook.Open Syntax

Now it’s time to look at the syntax of the method that you just have used in the above example. As I mentioned, there are fifteen arguments that you can use:

expression.Open (FileName, UpdateLinks, _
ReadOnly, Format, Password, WriteResPassword, IgnoreReadOnlyRecommended, Origin, _
Delimiter, Editable, Notify, Converter, AddToMru, Local, CorruptLoad)

You won’t be using all these arguments. But a few of them are quite important and could be useful for you in the real world.

Opening a Password Protected Workbook

If you want to open a workbook that is password-protected, in that case, you can specify the password with the password argument.

Here I have a workbook on the desktop that has the password “test123” and now I want to open it and unprotect it at the same time. Following is the code that I need to use.

Workbooks.Open "C:UsersDellDesktopmyFile.xlsx", , , Password:="test123"

Opening a Workbook as Read Only

When you open a workbook as read-only you can’t make changes to the same workbook, but you need to save a copy of it.

Workbooks.Open "C:UsersDellDesktopFolder1.xlsx", , True

Open All the Workbooks from a Folder

Sub vba_open_multiple_workbooks_folder()
    Dim wb As Workbook
    Dim strFolder As String
    Dim strFile As String
        strFolder = "C:UsersDellDesktopFolder"
        strFile = Dir(strFolder & "*.xls*")
        Do While strFile <> ""
            Set wb = Workbooks.Open(strFolder & strFile)
            strFile = Dir
        Loop
End Sub

To use it as per your needs, make sure to change the folder path.

Sub vba_open_dialog()
    Dim strFile As String
    strFile = Application.GetOpenFilename()
    Workbooks.Open (strFile)
End Sub

More on VBA Workbooks

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

  • VBA Workbook

Excel VBA allows you to open a workbook directly — all you need is the full path of the file, including the file name. However, locating and supplying the file path each time may can be tedious when working with multiple files. In this guide, we’re going to show you how to display File Open dialog in VBA.

Download Workbook

Opening a workbook in VBA

You can open workbooks in VBA using the Workbooks.Open method. This method accepts fifteen optional arguments, including the file name of the workbook you want to open.

Workbooks.Open (FileName, UpdateLinks, ReadOnly, Format, Password, WriteResPassword, IgnoreReadOnlyRecommended, Origin, Delimiter, Editable, Notify, Converter, AddToMru, Local, CorruptLoad)

Supply the file name with its full path to open the workbook.

Workbooks.Open «C:My DocumentsJuneIncome.xlsx»

Or

Workbooks.Open Filename:=»C:My DocumentsJuneIncome.xlsx»

Either line of code can open the workbook in the given path. The opened workbook becomes the active workbook.

Check out other optional arguments to determine how you want to open your workbook, such as in read-only mode, by updating external links, or with a password. Here is the documentation.

Displaying File Open dialog

File Open dialog can return the file name, which is needed for Workbooks.Open, along with its path. To display the File Open dialog, you need to call the Application.GetOpenFilename method.

Application.GetOpenFilename (FileFilter, FilterIndex, Title, ButtonText, MultiSelect)

The Application.GetOpenFilename method can take five optional arguments using which you can select the accepted file types, title of the dialog, or allow selecting multiple files.

To open the dialog in default state (without any filtering and ability to select single file) use it without any arguments. Assign the command to a string variable to set the variable with selected file’s full path.

Dim FullFileName as String
FullFileName = Application.GetOpenFilename

File Filter

On the other hand, applying a filter can be helpful in giving the end user only the files they need. You can use FileFilter to set filters on the Open File dialog box.

The FileFilter argument accepts a special string specifying file filtering criteria. You need to supply file types as friendly name — file type pairs. Each pair, name and type is separated by a comma (,) character.

friendly name 1, file type 1, friendly name 2, file type 2,

If a friendly name covers multiple types, use semicolon characters to split file types:

friendly name 1, file type 1; file type 2; file type …, friendly name 2, file type 4; file type 5; file type …,

Here is an example for displaying the dialog that accepts Excel Files only.

FullFileName = Application.GetOpenFilename(FileFilter:=»Excel Files,*.xl*»)

The following sample demonstrates the scenario at the above screenshot which displays two items as filters:

ExternalFileName = Application.GetOpenFilename(FileFilter:=»Excel Files,*.xl*;*.xm*,Text Files,*.txt;*.csv»)

Multiple Files

Another important feature of the Open File dialog is its ability to allow selecting multiple files. If the MultiSelect argument is set to True, the Open File dialog returns each selected file name in an array. Thus, you need to assign the dialog to a Variant type of variable instead of String.

Dim ExternalFileName As Variant
ExternalFileName = Application.GetOpenFilename(FileFilter:=»Excel Files,*.xl*,Text Files,*.txt;*.csv», MultiSelect:=True)

When you click the Open button, the assigned variable will have an array of filenames with paths. A common scenario is to use a loop to access each file name.

For i = LBound(ExternalFileName) To UBound(ExternalFileName)
    Workbooks.Open ExternalFileName(i)
Next i

Before start, you need to open the VBA (Visual Basic for Applications) window and add a module. A module is where you can write code.

  1. Press Alt + F11 to open the VBA window
  2. In the VBA window, click Insert on the toolbar
  3. Click the Module option

Open a single workbook

The following code displays the Open File dialog for Excel and some text files by allowing to select a single file only. After file name and path are set to the string variable, the code can copy content from the opened file to the existing file. You can simply copy this code and paste your VBA.

How to display File Open dialog in VBA 03 - Single File

Note: GetFilenameFromPath is a custom function which parse the file name from the full path. You can find its code in the example file.

Open multiple workbooks

This time Application.GetOpenFilename method is updated for multiple file selection. You can see the MultiSelect:=True argument in the code below. This is an example where the code was modified to execute same action in a loop.

Sub SingleFile()
    'Turn off screen updates to hide window transactions
    Application.ScreenUpdating = False
    'Ignore alerts such as "large amount of data" message while copying
    Application.DisplayAlerts = False
    
    'Define and set variables
    Dim PrimaryFileName As String, ExternalFileName As String
    PrimaryFileName = ThisWorkbook.Name
    
    'Call Open File dialog
    ExternalFileName = Application.GetOpenFilename(FileFilter:="Excel Files,*.xl*,Text Files,*.txt;*.csv")
    'End the macro if no ile is selected
    If ExternalFileName = False Then
        MsgBox "You are not selected a file"
        Exit Sub
    End If
    
    'Open the specified file and execute your code
    Workbooks.Open ExternalFileName
    Range("A1:G20").Copy 'Copy range from external file
    Windows(PrimaryFileName).Activate 'Activate the primary file
    Sheets.Add After:=ActiveSheet 'Add a new sheet
    ActiveSheet.Paste 'Paste into new sheet
    Workbooks(GetFilenameFromPath(ExternalFileName)).Close SaveChanges:=False 'Close the external file without saving
    
    'Reactivate alerts and screen updates
    Application.DisplayAlerts = True
    Application.ScreenUpdating = True
End Sub

How to display File Open dialog in VBA 04 - Multiple Files

In this Article

  • Open a Workbook in VBA
    • Open Workbook From Path
    • Open Workbook – ActiveWorkbook
    • Open Workbook and Assign to a Variable
    • Workbook Open File Dialog
    • Open New Workbook
    • Open New Workbook To Variable
  • Open Workbook Syntax
    • Open Workbook Read-Only
    • Open Password Protected Workbook
    • Open Workbook Syntax Notes
  • Close a Workbook in VBA
    • Close Specific Workbook
    • Close Active Workbook
    • Close All Open Workbooks
    • Close First Opened Workbook
    • Close Without Saving
    • Save and Close Without Prompt
  • Other Workbook Open Examples
    • Open Multiple New Workbooks
    • Open All Excel Workbooks in a Folder
    • Check if a Workbook is Open
    • Workbook_Open Event
  • Open Other Types of Files in VBA
    • Open a Text file and Read its Contents
    • Open a Text File and Append to it
    • Opening a Word File and Writing to it

In this tutorial, you will learn how to use VBA to open and close Excel Workbooks and other types of Files in several ways.

VBA allows you to open or close files using the standard methods .Open and .Close.

If you want to learn how to check if a file exists before attempting to open the file, you can click on this link: VBA File Exists

Open a Workbook in VBA

Open Workbook From Path

If you know which file you want to open, you can specify its full path name in the function. Here is the code:

Workbooks.Open "C:VBA FolderSample file 1.xlsx"

This line of the code opens “Sample file 1” file from the “VBA Folder”.

Open Workbook – ActiveWorkbook

When you open a workbook, it automatically becomes the ActiveWorkbook.  You can reference the newly opened workbook like so:

ActiveWorkbook.Save

When you reference a sheet or range and omit the workbook name, VBA will assume you are referring to the ActiveWorkbook:

Sheets("Sheet1").Name = "Input"

Open Workbook and Assign to a Variable

You can also open a workbook and assign it directly to an object variable. This procedure will open a workbook to the wb variable and then save the workbook.

Sub OpenWorkbookToVariable()
    Dim wb As Workbook
    Set wb = Workbooks.Open("C:VBA FolderSample file 1.xlsx")

    wb.Save
End Sub

Assigning workbooks to variables when they open is the best way to keep track of your workbooks

Workbook Open File Dialog

You can also trigger the workbook Open File Dialog box. This allows the user to navigate to a file and open it:

Sub OpenWorkbook ()

    Dim strFile As String

    strFile = Application.GetOpenFilename()
    Workbooks.Open (strFile)

End Sub

vba open close file

As you can see in Image 1, with this approach users can choose which file to open. The Open File Dialog Box can be heavily customized. You can default to a certain folder, choose which types of files are visible (ex. .xlsx only), and more. Read our tutorial on the Open File Dialog Box for detailed examples.

Open New Workbook

This line of code will open a new workbook:

Workbooks.Add

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

automacro

Learn More

Open New Workbook To Variable

This procedure will open a new workbook, assigning it to variable wb:

Sub OpenNewWorkbook()
    Dim wb As Workbook
    Set wb = Workbooks.Add
End Sub

Open Workbook Syntax

When you use Workbooks.Open you might notice that there are many options available when opening the workbook:

vba open workbook syntax

The Filename is required. All other arguments are optional – and you probably won’t need to know most of the other arguments.  Here are the two most common:

Open Workbook Read-Only

When workbook is opened read-only, you can’t save over the original file. This prevents the file from being edited by the user.

Workbooks.Open "C:VBA FolderSample file 1.xlsx", , True

VBA Programming | Code Generator does work for you!

Open Password Protected Workbook

A workbook might be password-protected. Use this code to open the password-protected workbook:

Workbooks.Open "C:VBA FolderSample file 1.xlsx", , , "password"

Open Workbook Syntax Notes

Notice that in the image above, we included a parenthesis “(” to show the syntax.  If you use parenthesis when working with Workbooks.Open, you must assign the workbook to a variable:

Sub OpenWB()
    Dim wb As Workbook
    Set wb = Workbooks.Open("C:VBA FolderSample file 1.xlsx", True, True)
End Sub

Close a Workbook in VBA

Close Specific Workbook

Similarly to opening a workbook, there are several ways to close a file. If you know which file you want to close, you can use the following code:

Workbooks.Close ("C:VBA FolderSample file 1.xlsx")

This line of code closes the file “Sample file 1” if it’s opened. If not, it will return an error, so you should take care of error handling.

Close Active Workbook

If you want to close the Workbook which is currently active, this line of code will enable you to do that:

ActiveWorkbook.Close

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

Close All Open Workbooks

To close all open Workbooks, you can simply use this code:

Workbooks.Close

Close First Opened Workbook

This will close the first opened/created workbook:

Workbooks(1).Close

Replace 1 with 2 to close the second opened / created workbook and so on.

Close Without Saving

This will close a Workbook without saving and without showing the save prompt:

ActiveWorkbook.Close savechanges:=False

Save and Close Without Prompt

Similarly this will save and close a Workbook without showing the save prompt:

ActiveWorkbook.Close savechanges:=True

Note: There are several other ways to indicate whether to save or not save a Workbook and also whether to show prompts or not. This is discussed in more detail here.

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

Other Workbook Open Examples

Open Multiple New Workbooks

This procedure will open multiple new workbooks, assigning the new workbooks to an array:

Sub OpenMultipleNewWorkbooks()
    Dim arrWb(3) As Workbook
    Dim i As Integer
    
    For i = 1 To 3
        Set arrWb(i) = Workbooks.Add
    Next i
End Sub

Open All Excel Workbooks in a Folder

This procedure will open all Excel Workbooks in a folder, using the Open File Dialog picker.

Sub OpenMultipleWorkbooksInFolder()
    Dim wb As Workbook
    Dim dlgFD As FileDialog
    Dim strFolder As String
    Dim strFileName As String
    Set dlgFD = Application.FileDialog(msoFileDialogFolderPicker)
    If dlgFD.Show = -1 Then
        strFolder = dlgFD.SelectedItems(1) & Application.PathSeparator
        strFileName = Dir(strFolder & "*.xls*")
        Do While strFileName <> ""
            Set wb = Workbooks.Open(strFolder & strFileName)
            
            strFileName = Dir
        Loop
    End If
End Sub

Check if a Workbook is Open

This procedure will test if a workbook is open:

Sub TestByWorkbookName()
Dim wb As Workbook
 
    For Each wb In Workbooks
        If wb.Name = "New Microsoft Excel Worksheet.xls" Then
            MsgBox "Found it"
            Exit Sub 'call code here, we'll just exit for now
        End If
    Next
 
End Sub

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

Workbook_Open Event

VBA Events are “triggers” that tell VBA to run certain code. You can set up workbook events for open, close, before save, after save and more.

Read our Workbook_Open Event tutorial to learn more about automatically running macros when a workbook is opened.

Open Other Types of Files in VBA

You can use the VBA to open other types of files with VBA – such as txt or Word files.

Open a Text file and Read its Contents

The VBA open method allows you to read or write to the file once you have opened it. To read the contents of a file, we  can open the file for INPUT.

Sub OpenTextFile()
   Dim strFile As String
   Dim strBody As String
   Dim intFile As Integer

   strFile = "C:datatest.txt"
   intFile = FreeFile
   Open strFile For Input As intFile
   strBody = Input(LOF(intFile), intFile)
   'loop here through your text body and extract what you need
   ''some vba code here
   Debug.Print strBody
   Close intFile
End Sub

The code above will open the text file “test.txt” and then it will read the entire contents of the file to the strBody variable.  Once you have extracted the file data into the strBody variable, you can use it for what you require. Using the Debug.Print command above enables us to see the contents of the strBody variable in the Immediate window in the VBE.

Open a Text File and Append to it

We can also open a text file in VBA, and then append to the bottom of the file using the Append method.

Sub AppendToTextFile()
Dim strFile As String
Dim strBody As String
Dim intFile As Integer

   strFile = "C:datatest.txt"
   intFile = FreeFile
   Open strFile For Append As intFile
'add two lines to the bottom
   Print #intFile, "This is an extra line of text at the bottom"
   Print #intFile, "and this is another one"
'close the file
   Close intFile
End Sub

The above code will open the text file and then append 2 lines of text to the bottom of the file using the #intFile variable (the # sign is the key!).  The code then closes the file.

Opening a Word File and Writing to it

We can also use VBA in Excel to open a Word file.

Sub OpenWordFile()
   Dim wApp As Object
   Dim wDoc As Object
   Set wApp = CreateObject("Word.Application")
   Set wd = wApp.documents.Open("c:datatest.docx")
   wApp.Visible = True
End Sub

This code will open a copy of Word, and then open the document test.docx.

Like this post? Please share to your friends:
  • Vba excel операции с датами
  • Vba excel открыть книгу если открыта
  • Vba excel операторы сравнения
  • Vba excel открыть книгу для записи
  • Vba excel оператор условия