Метод open vba excel
Синтаксис оператора Open состоит из следующих частей:
Часть | Описание |
---|---|
путь | Обязательно. Строковое выражение, указывающее имя файла; может включать каталог или папку, а также диск. |
Обязательно. Ключевое слово, задающее режим файла: Добавление, Двоичный, Ввод, Вывод или Прямой. Если элемент не задан, файл открывается для доступа в режиме Прямой. | |
доступ | Необязательно. Ключевое слово, определяющее операции, разрешенные для открытого файла: Чтение, Запись или Чтение и запись. |
блокировка | Необязательно. Ключевое слово, определяющее операции, запрещенные для открытого файла другими процессами: Общий, Блокировка чтения, Блокировка записи и Блокировка чтения и записи. |
filenumber | Обязательно указывать. Допустимый номер файла в диапазоне от 1 до 511 включительно. Чтобы получить следующий доступный номер файла, используйте функцию FreeFile . |
reclength | Необязательно. Число меньше или равное 32767 (байт). Для файлов, открытых для прямого доступа это значение равно значению длины записи. Для файлов с последовательным доступом значение представляет собой число буферизуемых символов. |
Примечания
Перед тем как выполнять операции ввода-вывода для файла, его необходимо открыть. Оператор Open выделяет для файла буфер для операций ввода-вывода и определяет режим доступа, который будет использоваться для буфера.
Если файл, заданный элементом pathname, не существует, он будет создан при открытии файла в режиме Добавление, Двоичный, Вывод или Прямой.
Если файл уже открыт другим процессом и указанный тип доступа не разрешен, операция Open сбой и возникает ошибка.
Предложение Len игнорируется, если выбран режимДвоичный.
В двоичных, входных и случайных режимах можно открыть файл с помощью другого номера файла без первого закрытия файла. В режимах Добавление и Вывод необходимо сначала закрыть файл, перед тем как открыть его с другим номером.
Пример
В этом примере показаны различные способы использования оператора Open для включения операций ввода и вывода для файла.
Следующий код открывает файл в режиме последовательного ввода.
В этом примере показано открытие файла в режиме "Двоичный" только для операций записи.
В следующем примере показано открытие файла в режиме "Прямой". Файл содержит записи определенного пользователем типа.
В этом примере кода открывается файл для последовательного вывода; любой процесс может читать или писать в файл.
Этот пример кода открывает файл в двоичном режиме для чтения; другие процессы не могут читать файл.
См. также
Поддержка и обратная связь
Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.
The Open statement syntax has these parts:
Part | Description |
---|---|
pathname | Required. String expression that specifies a file name; may include directory or folder, and drive. |
mode | Required. Keyword specifying the file mode: Append, Binary, Input, Output, or Random. If unspecified, the file is opened for Random access. |
access | Optional. Keyword specifying the operations permitted on the open file: Read, Write, or Read Write. |
lock | Optional. Keyword specifying the operations restricted on the open file by other processes: Shared, Lock Read, Lock Write, and Lock Read Write. |
filenumber | Required. A valid file number in the range 1 to 511, inclusive. Use the FreeFile function to obtain the next available file number. |
reclength | Optional. Number less than or equal to 32,767 (bytes). For files opened for random access, this value is the record length. For sequential files, this value is the number of characters buffered. |
Remarks
You must open a file before any I/O operation can be performed on it. Open allocates a buffer for I/O to the file and determines the mode of access to use with the buffer.
If the file specified by pathname doesn't exist, it is created when a file is opened for Append, Binary, Output, or Random modes.
If the file is already opened by another process, and the specified type of access is not allowed, the Open operation fails and an error occurs.
The Len clause is ignored if mode is Binary.
In Binary, Input, and Random modes, you can open a file by using a different file number without first closing the file. In Append and Output modes, you must close a file before opening it with a different file number.
Example
This example illustrates various uses of the Open statement to enable input and output to a file.
The following code opens the file in sequential-input mode.
This example opens the file in Binary mode for writing operations only.
The following example opens the file in Random mode. The file contains records of the user-defined type.
This code example opens the file for sequential output; any process can read or write to the file.
This code example opens the file in Binary mode for reading; other processes can't read the file.
See also
Support and feedback
Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.
Хотите создавать решения, которые расширяют возможности Office на разнообразных платформах? Ознакомьтесь с новой моделью надстроек Office. Надстройки Office занимают меньше места по сравнению с надстройками и решениями VSTO, и вы можете создавать их, используя практически любую технологию веб-программирования, например HTML5, JavaScript, CSS3 и XML.
Синтаксис
выражения. Open (FileName, UpdateLinks, ReadOnly, Format, Password, WriteResPassword, IgnoreReadOnlyRecommended, Origin, Delimiter, Editable, Notify, Converter, AddToMru, Local, CorruptLoad)
выражение Переменная, представляюная объект Книги .
Параметры
Имя | Обязательный или необязательный | Тип данных | Описание |
---|---|---|---|
FileName | Необязательный | Variant | Строка. Имя файла книги, которая должна быть открыта. |
UpdateLinks | Необязательный | Variant | Указывает, как обновляются внешние ссылки (ссылки) в файле, =SUM([Budget.xls]Annual!C10:C25) например ссылка на диапазон в книге Budget.xls в следующей формуле. Если этот аргумент не указан, пользователю будет предложено указать, как будут обновляться ссылки. Дополнительные сведения о значениях, используемых этим параметром, см. в разделе Примечание. |
Возвращаемое значение
Объект Книги , представляю который представляет открытую книгу.
Примечания
По умолчанию макрос включен при открытии файлов программным путем. Используйте свойство AutomationSecurity , чтобы настроить режим макрос безопасности, используемый при открытии файлов программным способом.
Вы можете указать одно из следующих значений в параметре UpdateLinks , чтобы определить, обновляются ли внешние ссылки (ссылки) после открытия книги.
Значение | Описание |
---|---|
0 | Внешние ссылки (ссылки) не обновляются после открытия книги. |
3 | Внешние ссылки (ссылки) будут обновляться после открытия книги. |
Можно указать одно из следующих значений в параметре Format , чтобы определить характер делимитера для файла.
Значение | Delimiter |
---|---|
1 | Вкладки |
2 | Запятые |
3 | Пробелы |
4 | Semicolons |
5 | Отсутствует |
6 | Настраиваемый символ (см. аргумент Delimiter ) |
Пример
В следующем примере кода открывается книга Analysis.xls, а затем выполняется Auto_Open макрос.
В следующем примере кода лист из другой книги импортируется на новый лист в текущей книге. Sheet1 в текущей книге должен содержать имя пути для импорта книги в ячейке D3, имя файла в ячейке D4 и имя листа в ячейке D5. Импортируемый лист вставляется после sheet1 в текущей книге.
Поддержка и обратная связь
Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.
Some information relates to prerelease product that may be substantially modified before it’s released. Microsoft makes no warranties, express or implied, with respect to the information provided here.
Opens a workbook.
Parameters
Required String. The file name of the workbook to be opened.
Optional Object. Specifies the way links in the file are updated. If this argument is omitted, the user is prompted to specify how links will be updated. Otherwise, this argument is one of the values listed in the following table.If Microsoft Excel is opening a file in the WKS, WK1, or WK3 format and the UpdateLinks argument is 2, Microsoft Excel generates charts from the graphs attached to the file. If the argument is 0, no charts are created.
Optional Object. True to open the workbook in read-only mode.
Optional Object. If Microsoft Excel is opening a text file, this argument specifies the delimiter character, as shown in the following table. If this argument is omitted, the current delimiter is used.
Optional Object. 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.
Optional Object. 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.
Optional Object. True to have Microsoft Excel not display the read-only recommended message (if the workbook was saved with the Read-Only Recommended option).
Optional Object. 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.
Optional Object. 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.
Optional Object. If the file is a Microsoft Excel 4.0 add-in, this argument is True to open the add-in so that it’s a visible window. If this argument is False or omitted, the add-in is opened as hidden, and it cannot be unhidden. This option doesn't apply to add-ins created in Microsoft Excel 5.0 or later. If the file is an Excel template, use True to open the specified template for editing or False to open a new workbook based on the specified template. The default value is False.
Optional Object. 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.
Optional Object. The index of the first file converter to try when opening the file. The specified file converter is tried first; if this converter doesn’t recognize the file, all other converters are tried. The converter index consists of the row numbers of the converters returned by the FileConverters[Object, Object] property.
Optional Object. True to add this workbook to the list of recently used files. The default value is False.
Optional Object. 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 U.S. English unless the VBA project where Workbooks.Open is run from is an old internationalized XL5/95 VBA project).
Optional Object. Can be one of the following constants: xlNormalLoad, xlRepairFile, and xlExtractData. The default behavior if no value is specified is usually normal, but may be safe load or data recovery if Excel has already attempted to open the file. The first attempt is normal. If Excel stops operating while opening the file, the second attempt is safe load. If Excel again stops operating, the next attempt is data recovery.
Returns
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.
Interested in developing solutions that extend the Office experience across multiple platforms? Check out the new Office Add-ins model. Office Add-ins have a small footprint compared to VSTO Add-ins and solutions, and you can build them by using almost any web programming technology, such as HTML5, JavaScript, CSS3, and XML.
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. |
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.
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.
Support and feedback
Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.
Читайте также: