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


 

Серега_

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

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

Здравствуйте.

Подскажите, как макросом открыть сторонний файл, в данном случае exe, где сама книга и файл находятся в одной директории?

Изменено: Серега_19.10.2015 20:41:50

 

knight

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

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

Можно сделать это проще с помощью гиперссылки

 

B.Key

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

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

#3

19.10.2015 22:34:59

Код
Set objSh = CreateObject("Shell.Application")
objSh.Open ("C:Windowsnotepad.exe")
objSh.Open (ThisWorkbook.Path & "ВашаПрограмма.exe")
 

Серега_

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

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

#4

19.10.2015 22:46:53

Цитата
knight написал:
Можно сделать это проще с помощью гиперссылки

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

 

Серега_

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

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

#5

19.10.2015 22:47:17

Цитата
B.Key написал:
Код?123Set objSh = CreateObject(«Shell.Application»)objSh.Open («C:Windowsnotepad.exe»)objSh.Open (ThisWorkbook.Path & «ВашаПрограмма.exe»)

Открывается блокнот…

 

B.Key

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

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

Так блокнот для примера написан :), закоментируйте.
Впишите вместо ВашаПрограмма имя Вашей программы.

 

B.Key

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

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

Может у Вас там ярлык? и программа запускается с доп параметрами?

 

Серега_

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

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

#8

19.10.2015 22:58:55

Цитата
B.Key написал:
Так блокнот для примера написан , закоментируйте.
Впишите вместо ВашаПрограмма имя Вашей программы

Может что не так

Код
Set objSh = CreateObject("Shell.Application")
objSh.Open (ThisWorkbook.Path & "densitydensity.exe")

что то вообще молчит.

 

B.Key

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

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

#9

19.10.2015 23:08:05

Цитата
написал:
где сама книга и файл находятся в одной директории?

значит должно быть так

Код
Set objSh = CreateObject("Shell.Application")
objSh.Open (ThisWorkbook.Path & "density.exe")

Изменено: B.Key19.10.2015 23:09:02

 

Серега_

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

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

#10

19.10.2015 23:15:03

Цитата
B.Key написал:
где сама книга и файл находятся в одной директории?

Файл excl и папка (density) с файлом density.exe находятся в одной директории и эта директория находится на носителе. Я даже его гиперссылкой открыть не могу, выходит сообщение, что системный файл не обнаружен, который находится тоже в директории с файлом ехе.

Изменено: Серега_19.10.2015 23:26:19

 

Серега_

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

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

#11

19.10.2015 23:25:02

При таком варианте

Код
Set objSh = CreateObject("Shell.Application")
objSh.Open (ThisWorkbook.Path & "densitydensity.exe")

Выходит сообщение что системный файл не обнаружен.
А при таком

Код
Set objSh = CreateObject("Shell.Application")
objSh.Open (ThisWorkbook.Path & "density.exe")

вообще молчит…

 

The_Prist

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

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

Профессиональная разработка приложений для MS Office

А Вас не наводит на мысль сообщение ОС, что файл не обнаружен? Зачем искать причину в коде, когда причина в другом месте? Как можно открыть файл, если система его просто не видит по Вашему пути?
Я бы посоветовал Вам простым кодом получить путь до Вашего файла и уже этот путь попробовать в гиперссылку и в код подставить. Вполне возможно, что-то в части пути упускаете.

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

B.Key

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

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

#13

19.10.2015 23:29:36

Код
set objSh = createobject("Wscript.Shell")
objSh.CurrentDirectory=ThisWorkbook.Path & ""
objSh.run ThisWorkbook.Path & "density.exe"),0

попробуйте так

Изменено: B.Key19.10.2015 23:30:08

 

Серега_

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

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

#14

19.10.2015 23:38:07

Цитата
The_Prist написал:
простым кодом

Это что создать гиперссылку?

 

Серега_

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

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

#15

19.10.2015 23:38:29

Цитата
B.Key написал:
попробуйте так

Не находит системный файл System.dll (он в той же директории что и density.exe)

Изменено: Серега_19.10.2015 23:39:53

 

B.Key

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

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

а он двойным кликом запускается?

 

Серега_

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

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

#17

19.10.2015 23:46:18

Цитата
B.Key написал:
а он двойным кликом запускается?

Да конечно

 

B.Key

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

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

В общем если ничего не помогает (бывает такое) надо батник программно писать и потом его запускать.

 

Серега_

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

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

#19

19.10.2015 23:51:08

Цитата
B.Key написал:
В общем если ничего не помогает (бывает такое) надо батник программно писать и потом его запускать.

Смотри-ка как, думал хоть тут проблем не будет… Решил, создам гиперссылку, а открытие файл запишу макросом, не тут то было.

Лады оставим это…
Спасибо

B.Key

что уделили внимание.

 

B.Key

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

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

 

Серега_

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

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

#21

19.10.2015 23:59:50

Цитата
B.Key написал:
Это из этой оперы?

Да нет, это программка определение плотности топлива в зависимости от температуры с построением графика.

 

The_Prist

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

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

Профессиональная разработка приложений для MS Office

#22

20.10.2015 00:19:26

Цитата
Серега_ написал:
Это что создать гиперссылку?
Код
Sub ShowGetOpenDialod()    Dim avFiles
    'по умолчанию к выбору доступны текстовые файлы
    avFiles = Application.GetOpenFilename _
                ("Excel files(*.xls*),*.xls*", 1, "Выбрать Excel файлы", , False)
    If VarType(avFiles) = vbBoolean Then
        'была нажата кнопка отмены - выход из процедуры
        Exit Sub
    End If
    'avFiles - примет тип String
    MsgBox "Выбран файл: '" & avFiles & "'", vbInformation, "www.excel-vba.ru"
    set objSh = createobject("Wscript.Shell")
    objSh.run (avFiles,1)
End Sub

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

Код
dim path as string
path = ThisWorkbook.Path & "densitydensity.exe"
Set objSh = CreateObject("Shell.Application")
objSh.run """" & path & """", 1

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

Серега_

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

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

#23

20.10.2015 00:50:30

Цитата
The_Prist написал:
еще бытует мнение, что если в пути к файлу есть пробелы, то лучше брать в доп.кавычки:

Если я
правильно понял то точная ссылка

Код
K:объем2015densitydensity.exe

Но открыть файл по данной ссылке тоже невозможно также ОС не находит системный файл System.dll…

 

Doober

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

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

Как вариант, замените объем на англицкие буквы
Переименуйте папку

Изменено: Doober20.10.2015 01:03:59

 

Серега_

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

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

#25

20.10.2015 01:09:00

Цитата
Doober написал:
Как вариант, замените объем на англицкие буквы

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

Изменено: Серега_20.10.2015 01:09:17

 

Doober

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

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

#26

20.10.2015 01:18:24

Полный текст ошибки в студию.
А если эту папку на диск с перенести и проверить.Какие файлы найти не может?
Попробуйте в макросе перед запуском выполнить

Код
CHDIR   Ваш путь к папке

Указать таким образом текущую директорию

Изменено: Doober20.10.2015 01:22:43

<#0>

 

Серега_

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

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

#27

20.10.2015 01:33:43

Код
А если эту папку на диск с перенести и проверить.Какие файлы найти не может?

Системный файл System.dll, который находится в той же директории что и файл exe.

Код
Полный текст ошибки в студию.

Ошибки как таковой нет, есть сообщение пороги

Прикрепленные файлы

  • 01.jpg (41.31 КБ)

Изменено: Серега_20.10.2015 01:36:03

 

Doober

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

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

#28

20.10.2015 03:14:43

Кидаете батник в папку с  density.exe.
Запускаете батник,смотрите результат.
Если положительный,то запускаете батник как

Код
path = ThisWorkbook.Path & "densityЗапуск.bat"

Будьте внимательны,кодировка файла ОЕМ866,используйте  лучше латиницу,если нет опыта

Прикрепленные файлы

  • Запуск.rar (172 Б)

Изменено: Doober20.10.2015 03:19:16

<#0>

 

The_Prist

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

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

Профессиональная разработка приложений для MS Office

#29

20.10.2015 11:03:56

Цитата
Серега_ написал:
Ошибки как таковой нет, есть сообщение пороги

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

Даже самый простой вопрос можно превратить в огромную проблему. Достаточно не уметь формулировать вопросы…

 

B.Key

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

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

#30

20.10.2015 12:18:24

Ну если Doober с батником не поможет, останется еще запасной вариант с sendkeys

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
title keywords f1_keywords ms.prod api_name ms.assetid ms.date ms.localizationpriority

Workbooks.Open method (Excel)

vbaxl10.chm203082

vbaxl10.chm203082

excel

Excel.Workbooks.Open

1d1c3fca-ae1a-0a91-65a2-6f3f0fb308a0

08/14/2019

medium

Workbooks.Open method (Excel)

Opens a workbook.

[!includeAdd-ins note]

Syntax

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

expression A variable that represents a Workbooks object.

Parameters

Name Required/Optional Data type Description
FileName Optional Variant String. The file name of the workbook to be opened.
UpdateLinks Optional Variant Specifies the way external references (links) in the file, such as the reference to a range in the Budget.xls workbook in the following formula =SUM([Budget.xls]Annual!C10:C25), are updated. If this argument is omitted, the user is prompted to specify how links will be updated. For more information about the values used by this parameter, see the Remarks section.

If Microsoft Excel is opening a file in the WKS, WK1, or WK3 format and the UpdateLinks argument is 0, no charts are created; otherwise, Microsoft Excel generates charts from the graphs attached to the file.

ReadOnly Optional Variant True to open the workbook in read-only mode.
Format Optional Variant If Microsoft Excel opens a text file, this argument specifies the delimiter character. If this argument is omitted, the current delimiter is used. For more information about the values used by this parameter, see the Remarks section.
Password Optional Variant A string that contains the password required to open a protected workbook. If this argument is omitted and the workbook requires a password, the user is prompted for the password.
WriteResPassword Optional Variant A string that contains the password required to write to a write-reserved workbook. If this argument is omitted and the workbook requires a password, the user will be prompted for the password.
IgnoreReadOnlyRecommended Optional Variant True to have Microsoft Excel not display the read-only recommended message (if the workbook was saved with the Read-Only Recommended option).
Origin Optional Variant If the file is a text file, this argument indicates where it originated, so that code pages and Carriage Return/Line Feed (CR/LF) can be mapped correctly. Can be one of the following XlPlatform constants: xlMacintosh, xlWindows, or xlMSDOS. If this argument is omitted, the current operating system is used.
Delimiter Optional Variant If the file is a text file and the Format argument is 6, this argument is a string that specifies the character to be used as the delimiter. For example, use Chr(9) for tabs, use «,» for commas, use «;» for semicolons, or use a custom character. Only the first character of the string is used.
Editable Optional Variant If the file is a Microsoft Excel 4.0 add-in, this argument is True to open the add-in so that it is a visible window. If this argument is False or omitted, the add-in is opened as hidden, and it cannot be unhidden. This option does not apply to add-ins created in Microsoft Excel 5.0 or later.

If the file is an Excel template, True to open the specified template for editing. False to open a new workbook based on the specified template. The default value is False.

Notify Optional Variant If the file cannot be opened in read/write mode, this argument is True to add the file to the file notification list. Microsoft Excel will open the file as read-only, poll the file notification list, and then notify the user when the file becomes available. If this argument is False or omitted, no notification is requested, and any attempts to open an unavailable file will fail.
Converter Optional Variant The index of the first file converter to try when opening the file. The specified file converter is tried first; if this converter does not recognize the file, all other converters are tried. The converter index consists of the row numbers of the converters returned by the FileConverters property.
AddToMru Optional Variant True to add this workbook to the list of recently used files. The default value is False.
Local Optional Variant True saves files against the language of Microsoft Excel (including control panel settings). False (default) saves files against the language of Visual Basic for Applications (VBA) (which is typically United States English unless the VBA project where Workbooks.Open is run from is an old internationalized XL5/95 VBA project).
CorruptLoad Optional XlCorruptLoad Can be one of the following constants: xlNormalLoad, xlRepairFile and xlExtractData. The default behavior if no value is specified is xlNormalLoad, and does not attempt recovery when initiated through the OM.

Return value

A Workbook object that represents the opened workbook.

Remarks

By default, macros are enabled when opening files programmatically. Use the AutomationSecurity property to set the macro security mode used when opening files programmatically.

You can specify one of the following values in the UpdateLinks parameter to determine whether external references (links) are updated when the workbook is opened.

Value Description
0 External references (links) will not be updated when the workbook is opened.
3 External references (links) will be updated when the workbook is opened.

You can specify one of the following values in the Format parameter to determine the delimiter character for the file.

Value Delimiter
1 Tabs
2 Commas
3 Spaces
4 Semicolons
5 Nothing
6 Custom character (see the Delimiter argument)

Example

The following code example opens the workbook Analysis.xls and then runs its Auto_Open macro.

Workbooks.Open "ANALYSIS.XLS" 
ActiveWorkbook.RunAutoMacros xlAutoOpen

The following code example imports a sheet from another workbook onto a new sheet in the current workbook. Sheet1 in the current workbook must contain the path name of the workbook to import in cell D3, the file name in cell D4, and the worksheet name in cell D5. The imported worksheet is inserted after Sheet1 in the current workbook.

Sub ImportWorksheet() 
    ' This macro will import a file into this workbook 
    Sheets("Sheet1").Select 
    PathName = Range("D3").Value 
    Filename = Range("D4").Value 
    TabName = Range("D5").Value 
    ControlFile = ActiveWorkbook.Name 
    Workbooks.Open Filename:=PathName & Filename 
    ActiveSheet.Name = TabName 
    Sheets(TabName).Copy After:=Workbooks(ControlFile).Sheets(1) 
    Windows(Filename).Activate 
    ActiveWorkbook.Close SaveChanges:=False 
    Windows(ControlFile).Activate 
End Sub

[!includeSupport and feedback]

Задача по объединению данных из нескольких Excel-файлов, или подгрузка доп.данных из внешнего файла решается достаточно просто: создается объект Excel, который можно скрыть визуально, затем открывается необходимый файл и выполняются нужные действия. Просто приведу несколько примеров.

Открытие файла Excel

Set objExcel = New Excel.Application
objExcel.Visible = False
Set wb = objExcel.Workbooks.Open(fname)
Set ws = wb.Sheets(1)

В первой строке запускаем новый Excel, затем делаем его невидимым, в 3-й строке открываем файл fname. В последней строке получаем первый лист открытого excel-кого файла.

Альтернативный вариант открытия файла

Set objExcel = New Excel.Application
Set wb = objExcel.Workbooks
wb.Open fname, local:=True
Set ws = wb.Item(1).ActiveSheet

При открытии файла можно использовать доп.параметры (приведу некоторые):

UpdateLinks — обновлять или нет внешние ссылки при открытии файла;
ReadOnly — открытие в режиме только для чтения;
Format — используемый при открытии разделитель (1 — символ tab, 2 — запятые, 3 — пробелы, 4 — точка с запятой, 5 — без разделителя, 6 — пользовательский разделитель, заданный в Delimiter);
Delimiter — пользовательский разделитель (в случае, если Format = 6);
Origin — тип операционной системы (xlMacintosh, xlWindows или xlMSDOS);
Local — использование в Excel языка такого же, как в открываемом файле.

Теперь можно выполнять какие-то действия с открытым файлом, просто обращаясь через wb и ws.

ws.Cells(1, 1).Value = "Test"
ws.Cells(1, 1).Font.Size = 18 ' Поменять размер шрифта
ws.Cells(1, 1).HorizontalAlignment = xlCenter ' 

Записать книгу и закрыть

wb.Save ' Записать с тем же именем
wb.SaveAs Filename:="имя_нового_файла", FileFormat:=xlOpenXMLWorkbookMacroEnabled ' Записать в новый файл
wb.Close ' Закрыть книгу

Для записи текущей книги (где находится макрос), можно использовать:

ActiveWorkbook.SaveAs 

Чтобы сохранить или перезаписать книгу Excel без вопросов, можно применить такой вариант:

Application.DisplayAlerts = False
ActiveWorkbook.SaveAs Filename:="c:Temp001.xlsm", FileFormat:=xlOpenXMLWorkbookMacroEnabled
Application.DisplayAlerts = True

У метода SaveAs есть несколько параметров сохранения, с ними можно ознакомиться на сайте Microsoft.

Если нужно, можно закрыть книгу Excel без сохранения изменений таким образом:

wb.Close False

Понравилась статья? Поделить с друзьями:
  • Vba для excel функция поиск
  • Vba для word если ошибка
  • Vba для excel фильтр
  • Vba для excel удалить пустые строки
  • Vba для excel ссылка на ячейку