Excel открыть любой файл vba excel

Открытие файла другой программы из кода VBA Excel с помощью функции ShellExecute, методов Wscript.Shell.Run и Workbook.FollowHyperlink по ассоциации с его расширением.

Функция ShellExecute

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

Или не произойдет ничего.

Чтобы открыть файл другой программы с помощью функции ShellExecute, ее необходимо объявить в разделе Declarations того модуля, в котором она будет использоваться.

Разместите следующий код в раздел Declarations программного модуля:

Declare Function ShellExecute Lib «shell32.dll» Alias «ShellExecuteA» (ByVal hWnd As Long, ByVal lpOperation As String, ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long

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

ShellExecute 0, vbNullString, «C:ТестоваяСправка VBA Excel.doc», vbNullString, vbNullString, vbNormalFocus

Замените адрес файла «C:ТестоваяСправка VBA Excel.doc» на адрес своего файла, который необходимо открыть по ассоциации с его расширением.

Минус этого способа заключается в необходимости объявлять функцию ShellExecute в разделе Declarations каждого модуля, где планируется ее использование.

Метод Run объекта Wscript.Shell

Метод Wscript.Shell.Run также позволяет открывать файлы других приложений из кода VBA Excel по ассоциации с их расширениями. Но если открываемый объект не существует, будет сгенерирована ошибка.

Используйте следующий код VBA Excel, чтобы открыть файл другой программы с помощью метода Run объекта Wscript.Shell:

Sub Primer1()

Dim ws As Object

  Set ws = CreateObject(«WScript.Shell»)

    ws.Run «C:Тестовая123.png»

  Set ws = Nothing

End Sub

Если адрес будет содержать пробелы, произойдет следующая ошибка:

Чтобы избежать ошибки, необходимо использовать тройные кавычки:

Sub Primer2()

Dim ws As Object

  Set ws = CreateObject(«WScript.Shell»)

    ws.Run «»«C:Тестовая папкаНовый точечный рисунок.bmp»«»

  Set ws = Nothing

End Sub

Метод Workbook.FollowHyperlink

Метод Workbook.FollowHyperlink позволяет открыть файл другой программы с помощью всего одной строки кода VBA Excel. Кроме того, при использовании этого метода не нужно экранировать кавычками полные имена файлов с пробелами.

Используйте следующую строку для открытия файлов других программ по их расширению с помощью метода FollowHyperlink объекта Workbook:

ThisWorkbook.FollowHyperlink («C:Тестовая папкаНовый точечный рисунок.bmp»)

Если открываемый объект не существует, будет сгенерирована ошибка, как и в случае с методом Wscript.Shell.Run.

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


devenge

9 / 9 / 2

Регистрация: 11.11.2011

Сообщений: 208

1

Как открыть любой файл через код?

11.01.2013, 16:14. Показов 7265. Ответов 5

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

Ищу код, который может при нажатии на ячейку открыть указанный файл. Пока нашёл что-то подобное, но он открывает файл через Excel. А как сделать, чтобы открывался не через Excel, а сам файл?

Visual Basic
1
Application.Workbooks.Open ("C:/image.png")



0



Казанский

15136 / 6410 / 1730

Регистрация: 24.09.2011

Сообщений: 9,999

11.01.2013, 16:35

2

В смысле — открыть файл в его «родном» приложении?

Visual Basic
1
2
3
shell "cmd /c C:/image.png",vbNormalFocus
'или
createobject("wscript.shell").run "C:/image.png"



1



Эксперт MS Access

26777 / 14456 / 3192

Регистрация: 28.04.2012

Сообщений: 15,782

11.01.2013, 16:40

3

devenge
Апишная функция ShellExecute и поле типа гиперссылка, открывают файл по записанному пути в его «родном» приложении. Если файл исполнимый (*.exe, *.bat, *.vbs), то годится «родная», ВБ-шная функция Shell



1



0 / 0 / 0

Регистрация: 21.03.2018

Сообщений: 4

21.03.2018, 10:19

4

Подскажите пожалуйста,

почему при выполнении команды

CreateObject(«WScript.Shell»).Run Chr(34) & Chr(34) & Chr(34) & MyArray(ListBox1.ListIndex + 1, 4) & Chr(34) & Chr(34) & Chr(34)

Программа не открывает файл, а открывает «Мой компьютер»

При этом если вставляю ссылку вручную:

CreateObject(«WScript.Shell»).Run «»»C:UsersSGulikovDesktopÇàäà÷è142_Âèçèò_â_îô èñ_ïðîäàæ_BPMN_13.07.2017.vsdx»»»

файл благополучно открывается



0



Казанский

15136 / 6410 / 1730

Регистрация: 24.09.2011

Сообщений: 9,999

21.03.2018, 12:23

5

Сергуня1987, не надо столько чаров34

Visual Basic
1
2
3
CreateObject("WScript.Shell").Run Chr(34) & MyArray(ListBox1.ListIndex + 1, 4) & Chr(34)
'или
CreateObject("WScript.Shell").Run """" & MyArray(ListBox1.ListIndex + 1, 4) & """"

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



0



0 / 0 / 0

Регистрация: 21.03.2018

Сообщений: 4

17.04.2018, 17:31

6

Спасибо, помогло)



0



 

Серега_

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

Сообщений: 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

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

Сообщений: 14181
Регистрация: 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

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

Сообщений: 14181
Регистрация: 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

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

Сообщений: 2201
Регистрация: 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

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

Сообщений: 2201
Регистрация: 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

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

Сообщений: 2201
Регистрация: 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

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

Сообщений: 14181
Регистрация: 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

Задача по объединению данных из нескольких 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

Visual Basic for Applications (VBA) is a frequently used utility for Microsoft applications — including Microsoft Excel, Office, PowerPoint, Word, and Publisher. As VBA is a fairly complicated language to learn, much has been written about it and its capabilities (and if you want to learn more about VBA and Excel, you can read about it here).

One of the most basic tasks you can use VBA for is to open and manipulate files, such as an Excel file. VBA open files will open the Excel file — from there you can control how it is read and written. Commonly, you would use VBA code to open the file, and then use Excel VBA macros to write to the file. 

Let’s take a deeper look into how VBA open files can be used with an Excel Workbook.

What is VBA Open Files and how does it work?

VBA is extremely similar to Visual Basic, a programming language used within the Microsoft ecosystem. It is used to create “macros.” A macro is a sequence of automated events which can fine-tune, optimize, automate, and improve your operations. The Excel VBA implementation can open files and run macros on them.

In Excel, you use VBA by inserting the code in the Visual Basic Editor. You can also choose the “Macro” button on the Developer Tab. From there, you will enter in code as though programming.

Before you start digging into VBA, you should have some understanding of programming. Programming means directing a computer to perform a certain sequence of events. Keep a few things in mind:

  • You should always test your programming thoroughly to make sure it does what you want it to do.
  • You should never implement your programming in a “live” environment with important data rather than test data.
  • You should save your work frequently and you should be prepared to restore both your programming and your data if needed.
Person wearing headphones looking at laptop screen and typing

Running the macros you program

When macros are created, they’re assigned to given keypresses. Sometimes this is a combination of keys, and sometimes it’s an extra mouse button. Regardless, they’re intended to set off an automated chain of events whenever you do the given action (whether it’s pressing a key on your keyboard, or a button on your mouse). You can also run a macro manually by selecting it.

So, when you run a macro, you have Microsoft Excel already open. The macro runs within Excel, and you will do all your VBA programming inside of that program. Likewise, you will do your Microsoft Word VBA programming inside of Microsoft Word.

Opening an Excel file with VBA

The first step to updating, modifying, and saving Excel files is to be able to open them. To open an Excel file with VBA you would program as follows:

Sub openworksheet()
	Workbooks.Open filename:= _ “filepath”
	End sub

The “sub” above is a lot like a function. It creates a small amount of code that is intended to take action. It begins with “Sub” and ends with “End Sub.”

In the above code, note that the italicized “filepath” references the full path of the workbook. Without the appropriate Workbooks.Open filename, you won’t be able to open the given file. You will also need the appropriate file type (Microsoft Excel, which is either XLS or XLSX) or the open method will fail.

Of course, the above assumes that you are always going to be opening the Workbook at the “filepath.” You might also want to open any file at all. You can create a macro that opens a dialog, through which you can select any file.

	Sub openworksheet()
	Dim Flocation as Variant
	Flocation = Application.GetOpenFileName()
	If Flocation <> false then 
	Workbooks.Open Filename:= Flocation
	End If
	End Sub

The above code prompts the user to give a file name. If the user does give a file name (the variable, Flocation is no longer false), then the program will open that file.

Also note that Flocation is just the name of the variable that’s being used. You could call it something else; in fact, you could even call it just “f.” All that’s important is that you don’t use a word that the code already uses, such as “Variant” or “Filename.”

You might also be wondering why this code is so important. After all, you can open your own files at any time. But you can bind it to a specific keypress, making it a macro. So, now, typing something like “F8” will automatically open the “open a file” dialog.

But once you’ve automatically opened a file, what’s next? Generally, opening the file is only the first step. Once you’ve opened the Excel file, you still need to be able to read and write to it.

Reading the Excel file

You’ve opened your Excel file. But what’s inside of it? Luckily for you, it’s pretty easy to start reading an Excel file once you’ve opened it with VBA.

First, you should know that when you open a file, it becomes the ActiveWorkbook, which can be referenced in code as “ActiveWorkbook.”

Let’s say you want to read the first cell of the book.

Dim contents As Integer
	contents = ActiveWorkbook.Range(“A1”).value

Now, that does assume that the cell is an Integer. You would need to change it to a String if you were reading a string, or a Date if you were reading a Date. Consequently, you need to be really familiar with the type of data you’re reading before you go any further.

Now, note that this is reading the contents of the cell into just a variable. That’s not displaying it. That’s not doing anything with it at all. If you wanted to see, perhaps, what the contents were, you would then type:

MsgBox contents

Alternatively, you could:

MsgBox ActiveWorkbook.Range(“A1”).value

Either of these options should display the value. But, of course, it’s a static value; it’s always going to display A1. So, you might need to code things a little more expressively if you’re trying to read the entirety of a document, or if you’re trying to transition one document to another.

Writing to the file

So, you have your workbook open through the power of VBA. But now you want to write to the file. Writing can be used in tandem with reading; once the Workbook is open you could do both. 

As an example, you could write a macro that would open a Workbook and copy one column to another column, by reading the data in the first column and then writing that data to the second column.

Similarly, you could write a macro that would open two Workbooks and copy data from one to another, and then save both Workbooks, and then close both Workbooks.

As mentioned, once you open a workbook with VBA, the workbook that you opened becomes the ActiveWorkbook. This also happens if you have created a new workbook within VBA.

You can then access its data through:

ActiveWorkbook.Sheets
ActiveWorbook.Cells

As an example, if you wanted to edit the cell at column 1, row 1, on Sheet 1, you would write as follows:

ActiveWorkbook.Sheets(“Sheet 1”).Cells(1,1).Value= “1”

If this is confusing, you can also use the “Range” field.

ActiveWorkbook.Sheets(“Sheet 1”).Range(“A1”).Value= “1”

The above would have the same result.  

Writing to a sheet can become very complex. Consider that, when you’re writing the macro system, you don’t know what data is in those cells. You only know their positions. You’re essentially writing to that position blindly.

Macros are frequently used to do things such as read CSV files and import that CSV information into a brand new Microsoft Excel workbook. But it takes a lot of time and a lot of testing to ensure that the data is going through correctly.

In the above case, you’re only altering range A1. But you could iterate through all the rows and columns of a workbook one by one if you were trying to fill it out line by line. As you learn more about Excel and VBA, you will learn more advanced methods of both reading and writing data.

Saving the Excel workbook file

Just like when you’re using Excel regularly, you still need to save your changes. If you have opened and changed a Workbook, save it before you close it. 

ActiveWorkbook.Save

You could even write a Macro that would save all your workbooks and close them, as follows:

For each workbook in Application.Workbooks
		workbook.Save
	Next workbook
		Application.Quit

The above code iterates through each Workbook saving it until it cannot find a Workbook anymore. Once it can no longer find a Workbook, it quits the application. This is very useful for those who want to shut down fast and have a lot of workbooks left to save.

Closing the selected file

Closing the file is just as easy as opening a workbook. In fact, it’s actually easier, because you don’t need to know the file name. VBA already knows which file it has opened.

To close the Excel file you would type:

ActiveWorkbook.Close

On the other hand, perhaps you wanted to close a specific Workbook. In that case, you would use the following:

Workbooks(“book.xlsx”).Close

This is under the assumption the book was called “book.xlsx”; you would replace the given name for your sheet. Once you have closed the Workbook, you will not be able to make any further modifications to it until you open it again.

Opening a Microsoft Excel workbook that is password protected

Sometimes you may have password-protected your workbooks. That goes into more complicated territory. Understandably, it’s not going to open if you just try to directly open it. 

But you can still open it with VBA.

Workbooks.Open(filename:= “filename”, Password:= “password”)

As you can see above, you just added the password directly into the macro. Now the file is going to open just fine.

But there’s a problem with the above, which (if you’re good with security) you already know. You just saved your password as plain text! 

Now, anyone with access to your computer could potentially open that file without knowing the password. And if you’ve been using that password for multiple files (a big no-no), they could be compromised, too.

So, VBA does provide a method of opening files that have a password. But it’s not a good method because of the above reasons. It means that your system could be compromised. If you just have a password to prevent outside intrusion (the file being sent somewhere else and opened by an outsider), this may not be a problem. But if you’re trying to protect your file internally as well as externally, it can be a major issue.

The alternative is to use the previous method of opening a file with a dialogue box. When you press a button (or otherwise launch your macro), you’ll be given a dialogue box, and you’ll be able to open whatever file you want. Your macro can then continue actions on the file after you have manually entered your password. 

Opening a read-only file

Some Microsoft Excel files don’t have a password when you open them. Instead, they are set to read-only. If they’re set to read-only, you’ll be able to open and read from them. But you won’t be able to actually write to them without a secondary password. 

ActiveWorkbook.Password = “password”

Above is the method that you would call after you’ve opened the book so that you can start to write to it. You wouldn’t include the password when opening the file, because you wouldn’t have been prompted for it then.

The benefits of using Excel VBA Open

VBA is used to automate routine, mundane tasks, such as copying large volumes of data from one book to another. Any time you’re finding yourself spending hours just copying and pasting data, or running fairly mundane calculations, a macro can help.

You can also use VBA to automate smaller tasks that you find use a lot of keypresses. If you find yourself frequently needing to open the same 10 Excel Workbooks at once, for instance, you can create a macro that will open all of them on a single keypress, and close them all, too.

While it may only save you a few minutes of time, those minutes of time add up.

Potential issues with Excel VBA Open

It’s possible to run into issues with VBA open. If you have a protected workbook, you won’t be able to open it without the password (as noted). If you don’t have the password, you aren’t going to be able to open the file.

If the selected file is read-only, you aren’t going to be able to write to it without the right permissions. If you don’t realize that the file is read-only, you could try writing to it only for the action to fail. 

And because you can’t always see what the macro is doing until you run it, you can potentially overwrite data or delete it altogether. This is why it’s always important to test your macros with test data before trying to implement it with live data.

But even so, Excel VBA open is a robust language. Most common activities with Workbooks (such as opening, closing, reading, writing, and saving) can be completed quite intuitively and often with a single line of code.

Learning more about Excel VBA

In the right hands, VBA is very powerful. If you have any automated, routine tasks in Excel, consider automating them with Excel VBA. Even better, once you learn the basics of VBA, you can also use it in other Microsoft applications such as Microsoft Word.

Still, powerful also means that mistakes can be made. Because VBA can open files and write to them, it’s also possible that it can overwrite data. This is why testing your programming is so important. 


Frequently Asked Questions:

Can a macro open a file?

The Excel Macro can be used to prompt a user to open a file or to open a specific file (given the entire filename). 

How do I open a text file in Excel VBA?

The VBA OpenTextFile method can be used to open a text file, just as the VBA Workbooks.Open method is used to open an Excel file.

How do I open a new workbook in VBA?

To open a new workbook in VBA, you would use the Workbooks.Add() VBA function. This function both creates a new workbook and prioritizes it as the active workbook.

Понравилась статья? Поделить с друзьями:
  • Excel открыть лист формула
  • Excel открыть лист на весь экран
  • Excel открыть книгу в отдельном окне
  • Excel открыть документ в листе
  • Excel открыть в другой кодировке