Читать excel файлы vba

You can VBA Read file binary or text data using a couple of different approaches in Excel. VBA provides you a set of native statements like Open to open and ready files. However in this article aside from showing you these native approaches to reading files using Excel Macros you can read CSV files and other structured data schemas using Jet.OLEDB driver, Microsoft Queries or also the FileSystemObject.

Text/binary files are common ways of storing data as opposed to databases or regular Excel files. Looking at various resources I missed a single resource which would demonstrate the various methods for PROPERLY reading files in VBA.

It is important to remember that you shouldn’t read all files using the same approach. Be aware of the structure of the file. If it is a structured CSV use the ADODB connection, if you need to read only a couple of rows read the file row by row or by chunks, else read the whole file. If you want performance – always select the right approach.

Reading text files in VBA

VBA Read text files (line by line)

To read an entire text file line by line use the code below.

Dim fileName As String, textData As String, textRow As String, fileNo As Integer
fileName = "C:text.txt"
fileNo = FreeFile 'Get first free file number  
    
Open fileName For Input As #fileNo
Do While Not EOF(fileNo)
   Line Input #fileNo, textRow
   textData = textData & textRow
Loop
Close #fileNo

VBA Read text files (read whole file)

To read an entire text file in one go (not line by line) use the code below.a

Dim fileName As String, textData As String, fileNo As Integer
fileName = "C:text.txt"
fileNo = FreeFile 'Get first free file number   
 
Open fileName For Input As #fileNo
textData = Input$(LOF(fileNo), fileNo)
Close #fileNo

VBA Read specific number of lines from a text file

In cases when you want to read specific lines from a text file you can adapt the line by line read code as below. It allows you to read a certain number of lines (noLines) from a text file from a specific start line number (sLine). If you set noLines to 0 it will read all lines till end of the file.

Dim fileName As String, textData As String, textRow As String, fileNo As Integer
Dim lineCounter as Long, sLine as Long, noLines as Long

fileName = "C:text.txt"

sLine = 20 'number of the first line you want to read
noLines = 100 'number of lines you want to read

fileNo = FreeFile 
Open fileName For Input As #fileNo
Do While Not EOF(fileNo)
  Line Input #fileNo, textRow
  If lineCount >= sLine and ((noLines > 0 and lineCount < noLines + sLine) or noLines = 0) then
    textData = textData &amp; textRow
  End If
  lineCount = lineCount + 1   
Loop
Close #fileNo

Reading CSV files in VBA

Reading CSV files (read whole file and process each row)

Reading a text file line by line into a string:

'Assuming file looks like this. File path: C:test.csv
'"Col1", "Col2", "Col3"
'1     , 2     , 3

directory = "C:"
fileName = "test.csv" 'Assuming test.csv is in C: directory
Set rs = CreateObject("ADODB.Recordset")
strcon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & directory & ";" _
& "Extended Properties=""text;HDR=Yes;FMT=Delimited"";"
strSQL = "SELECT * FROM " & fileName 
rs.Open strSQL, strcon, 3, 3
rs.MoveFirst
Do
   col1 = rs("Col1")
   col2 = rs("Col2")
   col3 = rs("Col3")
   rs.MoveNext
Loop Until rs.EOF

Reading CSV files (whole file to Worksheet)

Read whole file to an Excel Worksheet:

Dim ws as Worksheet, destRng as Range, fileName as String
fileName = "C:text.txt"
Set destRng = Range("A1")
Set ws = ActiveSheet
With ws.QueryTables.Add(Connection:= "TEXT;" & fileName & "", Destination:=destRng)
    .FieldNames = True
    .RowNumbers = False
    .FillAdjacentFormulas = False
    .PreserveFormatting = True
    .RefreshOnFileOpen = False
    .RefreshStyle = xlInsertDeleteCells
    .SaveData = True
    .AdjustColumnWidth = True
    .RefreshPeriod = 0
    .TextFilePromptOnRefresh = False
    .TextFilePlatform = 852
    .TextFileStartRow = 1
    .TextFileParseType = xlDelimited
    .TextFileTextQualifier = xlTextQualifierDoubleQuote
    'Select your delimiter - selected below for Comma
    .TextFileConsecutiveDelimiter = False
    .TextFileTabDelimiter = False
    .TextFileSemicolonDelimiter = False
    .TextFileCommaDelimiter = True
    .TextFileSpaceDelimiter = False
    .TextFileTrailingMinusNumbers = True
    'This will refresh the query
End With

To refresh the CSV upload (in case the CSV was updated) simply run:

  
ws.QueryTables.Refresh BackgroundQuery:=False

Reading binary files in VBA

Dim fileName As String, fileNo As Integer, intVar As Integer
fileName = "C:text.bin"
fileNo = FreeFile

Open fileName For Binary Lock Read As #fileNo
Get #fileNo, , intVar
Close #fileNo

With Binary files often you will be using objects which are not of fixed byte length like Integers. For example you would want to read Strings from binary files together with other data types. In such cases use the Type object data type when writing to a file. Learn more here.
Below a simple example of reading a file to which a Type data type was saved to, including an Integer and String.

Type TestType
    intVar As Integer
    strVar As String
End Type

Sub ReadBinary()
    Dim fileName As String, fileNo As Integer, testVar As TestType
    fileName = "C:test.bin"

    fileNo = FreeFile
    Open fileName For Binary Lock Read As #fileNo
    Get #fileNo, , testVar
    Debug.Print testVar.intVar 'Print the Integer
    Debug.Print testVar.strVar 'Print the String
    Close #fileNo
End Sub

Reading XML files in VBA

XML files are basically text files which follow the XML taxonomy. You can try to read and process XML files similarly as text files shown above. However, given you will probably want to extract specific XML tag or attribute information I suggest reading my dedicated article below.

Functions needed to read files in VBA

Function Description
Open [path_to_file] For [Mode] [Access] [Lock] As [long_variable] Opens the file for read/write and returns the # file number (needs to be type of long) into long_variable
More info here. Parameters below:

  • Mode – Append, Binary, Input, Output, or Random
  • Access optional. Read, Write, or Read Write
  • Lock optional. Shared, Lock Read, Lock Write, and Lock Read Write.
Close Closes the file using the # file number.
More info here.
FreeFile Get next free file number available for the Open statement / FileOpen function. Using this function is important especially when operating on multiple files simultaneously.
More info here.
BOF(fileNumber) Returns true if you are at the beginning of the file described by the file number.
More info here.
EOF(fileNumber) Returns true if you have reached the end of the file described by the file number. More info here.
Loc(fileNumber) Returns the current read/write position within an open file. More info here.
LOF(fileNumber) Returns the size in bytes of the file represented by the file number. More info here.

Above functions allow native upload of file data. However for more complicated scenario you will probably go for the FileSystemObject.

VBA Read File Summary

Reading files in VBA is not hard and requires just a few lines of code usually. It is, however, important to use the appropriate approach to read a file in VBA. Not all files need to be read line-by-line which is usually inefficient. Equally so you need not always read the entire file if you just need the first few / last rows. Working with XML files is also not a challenge if you read through my post on how to work with XML files.

Want to Write to files instead?

If you are looking to write to files instead using VBA, read my article on how to write to files using VBA.

Чтение и запись в файл, открытый с помощью оператора Open. Операторы Input, Line Input, Write и функция EOF. Примеры использования в VBA Excel.

Операторы чтения и записи в файл

Оператор Input #

Оператор Input # считывает данные из открытого файла с последовательным доступом и присваивает эти данные переменным.

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

Синтаксис оператора Input #:

Input #Номер_файла, Переменные

Компоненты оператора Input #:

  • Номер_файла – обязательный параметр, представляющий из себя номер, присвоенный файлу при открытии с помощью оператора Open.
  • Переменные – обязательный параметр, представляющий из себя список переменных, разделенных запятой, которым присваиваются значения, считанные из файла.

Особенности применения оператора Input #:

  • Элементы данных в файле должны быть указаны в том же порядке, что и переменные в списке Переменные, и соответствовать им по типу данных. Если переменная числовая, а данные текстовые, этой переменной будет присвоено нулевое значение.
  • Если при чтении данных достигнут конец файла, чтение прерывается и возникает ошибка. Для ее предупреждения в коде VBA Excel используется функция EOF.
  • Чтобы данные из файла могли быть правильно прочитаны и записаны в переменные с помощью оператора Input #, они должны быть записаны в файл с помощью оператора Write #. Он обеспечивает правильное разделение каждого из полей (элементов) данных.

Оператор Line Input #

Оператор Line Input # считывает одну строку из открытого файла с последовательным доступом и присваивает ее значение строковой переменной.

Оператор Line Input # считывает из файла по одному символу до тех пор, пока не встретится символ возврата каретки (Chr(13)) или последовательность символа возврата каретки и перевода строки (Chr (13) + Chr(10)).

Синтаксис оператора Line Input #:

Line Input #Номер_файла, Переменная

Компоненты оператора Line Input #:

  • Номер_файла – обязательный параметр, представляющий из себя номер, присвоенный файлу при открытии с помощью оператора Open.
  • Переменная – обязательный параметр, представляющий из себя имя переменной, объявленной как String или Variant, которой присваивается строка, считанная из файла.

Оператор Write #

Оператор Write # записывает данные в файл с последовательным доступом.

Синтаксис оператора Write #:

Write #Номер_файла, [Данные]

Компоненты оператора Write #:

  • Номер_файла – обязательный параметр, представляющий из себя номер, присвоенный файлу при открытии с помощью оператора Open.
  • Данные – необязательный параметр, представляющий из себя одно или несколько числовых или строковых выражений, разделенных запятой, которые нужно записать в файл.

Особенности применения оператора Write #:

  • Данные, записанные с помощью оператора Write #, считываются из файла с помощью оператора Input #.
  • Если опустить параметр Данные и добавить запятую после Номер_файла, в файл будет добавлена пустая строка.
  • Несколько выражений в списке Данные могут быть разделены точкой с запятой или запятой.
  • Числовые данные всегда записываются с точкой в качестве разделителя целой и дробной части.
  • Оператор Write # вставляет запятые между элементами и прямые парные кавычки вокруг строк при их записи в файл.
  • После записи в файл последнего символа из параметра Данные оператор Write # вставляет символы возврата каретки и перевода строки (Chr (13) + Chr(10)).

Функция EOF

Функция EOF возвращает логическое значение True, когда достигнут конец файла, открытого для последовательного (Input) или произвольного (Random) доступа.

Синтаксис функции EOF:

Номер_файла – это номер, присвоенный файлу при открытии с помощью оператора Open.

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

Примеры чтения и записи в файл

Пример 1
Открытие (или создание, если он не существует) текстового файла для чтения и записи и запись в него одной строки, состоящей из двух текстовых и одного числового значений. Файл с именем myFile1.txt будет создан в той же папке, где расположен файл Excel с кодом VBA.

Sub Test1()

Dim ff As Integer

‘Получаем свободный номер для открываемого файла

ff = FreeFile

‘Открываем (или создаем) файл для чтения и записи

Open ThisWorkbook.Path & «myFile1.txt» For Output As ff

‘Записываем в файл одну строку

Write #ff, «Дает корова молоко!», _

«Куда идет король?», 25.35847

‘Закрываем файл

Close ff

‘Открываем файл для просмотра

ThisWorkbook.FollowHyperlink (ThisWorkbook.Path & «myFile1.txt»)

End Sub

Строки и число можно предварительно присвоить переменным, объявленным с соответствующими типами данных, и использовать их для записи данных в файл (в строках кода с оператором Write #, как в этом и следующем примерах).

Пример 2
Открытие (или создание, если он не существует) файла без расширения для чтения и записи и запись в него трех строк: двух текстовых и одной в числовом формате. Файл с именем myFile2 будет создан в той же папке, где расположен файл Excel с кодом VBA.

Так как у файла нет расширения, Windows выведет диалоговое окно для выбора открывающей его программы. Выберите любой текстовый редактор или интернет-браузер.

Sub Test2()

Dim ff As Integer

‘Получаем свободный номер для открываемого файла

ff = FreeFile

‘Открываем (или создаем) файл для чтения и записи

Open ThisWorkbook.Path & «myFile2» For Output As ff

‘Записываем в файл три строки

Write #ff, «Дает корова молоко!»

Write #ff, «Куда идет король?»

Write #ff, 25.35847

‘Закрываем файл

Close ff

‘Открываем файл для просмотра

ThisWorkbook.FollowHyperlink (ThisWorkbook.Path & «myFile2»)

End Sub

Пример 3
Считываем строку, разделенную на отдельные элементы, из файла myFile1.txt и записываем в три переменные, по типу данных соответствующие элементам.

Sub Test3()

Dim ff As Integer, str1 As String, _

str2 As String, num1 As Single

‘Получаем свободный номер для открываемого файла

ff = FreeFile

‘Открываем файл myFile1.txt для чтения

Open ThisWorkbook.Path & «myFile1.txt» For Input As ff

‘Считываем строку из файла и записываем в переменные

Input #ff, str1, str2, num1

Close ff

‘Смотрим, что записалось в переменные

MsgBox «str1 = « & str1 & vbNewLine _

& «str2 = « & str2 & vbNewLine _

& «num1 = « & num1

End Sub

Попробуйте заменить в этом примере строку Input #ff, str1, str2, num1 сначала на строку Input #ff, str1, затем на строку Line Input #ff, str1, чтобы наглядно увидеть разницу между операторами Input # и Line Input #.

В следующих примерах (4 и 5) замена оператора Input # на Line Input # не приведет ни к каким изменениям, так как данные в строках файла myFile2 не разделены на элементы (поля).

Пример 4
Считываем поочередно три строки из файла myFile2 и записываем в три элемента массива, объявленного как Variant, так как в этот файл ранее были записаны две строки с текстом и одна с числом.

Sub Test4()

Dim ff As Integer, a(2) As Variant, i As Byte

‘Получаем свободный номер для открываемого файла

ff = FreeFile

‘Открываем файл myFile2 для чтения

Open ThisWorkbook.Path & «myFile2» For Input As ff

‘Считываем строки из файла и записываем в элементы массива

   For i = 0 To 2

      Input #ff, a(i)

   Next

Close ff

‘Смотрим, что записалось в элементы массива

MsgBox «a(0) = « & a(0) & vbNewLine _

& «a(1) = « & a(1) & vbNewLine _

& «a(2) = « & a(2)

End Sub

Пример 5
Считываем с помощью цикла Do While… Loop все строки из файла myFile2 и записываем построчно в переменную, объявленную как String (число из третьей строки запишется как текст). Для остановки цикла при достижении конца файла используем функцию EOF.

Sub Test5()

Dim ff As Integer, a As Variant, b As String

‘Получаем свободный номер для открываемого файла

ff = FreeFile

‘Открываем файл myFile2 для чтения

Open ThisWorkbook.Path & «myFile2» For Input As ff

‘Считываем строки из файла и записываем в элементы массива

   Do While Not EOF(ff)

      Input #ff, a

      b = b & a & vbNewLine

   Loop

Close ff

‘Смотрим, что записалось в переменную

MsgBox b

End Sub


Предыдущая часть темы об открытии файла для ввода и вывода информации опубликована в статье: Оператор Open (синтаксис, параметры). Смотрите также связанную статью: Функция FreeFile.

Смотрите, как создавать и открывать текстовые файлы с помощью методов CreateTextFile и OpenTextFile. Чтение файла, запись и добавление информации с помощью объекта TextStream.


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

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

Используя эти функции, вы при помощи одной строки кода сможете записать текст из переменной в файл, или наоборот, загрузить содержимое текстового файла в переменную.
Подразумевается, что текстовые файлы имеют формат ANSI (он же ASCII, он же windows-1251)

Чтение текстового файла в переменную:

Function ReadTXTfile(ByVal filename As String) As String
    Set fso = CreateObject("scripting.filesystemobject")
    Set ts = fso.OpenTextFile(filename, 1, True): ReadTXTfile = ts.ReadAll: ts.Close
    Set ts = Nothing: Set fso = Nothing
End Function

Запись в текстовый файл из переменной:

Function SaveTXTfile(ByVal filename As String, ByVal txt As String) As Boolean
    On Error Resume Next: Err.Clear
    Set fso = CreateObject("scripting.filesystemobject")
    Set ts = fso.CreateTextFile(filename, True)
    ts.Write txt: ts.Close
    SaveTXTfile = Err = 0
    Set ts = Nothing: Set fso = Nothing
End Function

Добавление в текстовый файл из переменной:

Function AddIntoTXTfile(ByVal filename As String, ByVal txt As String) As Boolean
    On Error Resume Next: Err.Clear
    Set fso = CreateObject("scripting.filesystemobject")
    Set ts = fso.OpenTextFile(filename, 8, True): ts.Write txt: ts.Close
    Set ts = Nothing: Set fso = Nothing
    AddIntoTXTfile = Err = 0
End Function
  • 107181 просмотр

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

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

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