Каталог расширений

Популярные теги

3gp       avi       fb2       jpg       mp3       pdf      

Как указать путь к файлу в vba


Практическое руководство. Анализ путей к файлам - Visual Basic

  • Чтение занимает 2 мин

В этой статье

Объект FileSystem предоставляет ряд полезных методов при анализе путей к файлам.The FileSystem object offers a number of useful methods when parsing file paths.

  • Метод CombinePath получает два пути и возвращает комбинированный путь в правильном формате.The CombinePath method takes two paths and returns a properly formatted combined path.

  • Метод GetParentPath возвращает абсолютный путь к родительскому элементу указанного пути.The GetParentPath method returns the absolute path of the parent of the provided path.

  • Метод GetFileInfo возвращает объект FileInfo , к которому можно выполнить запрос, чтобы определить свойства файла, например имя и путь.The GetFileInfo method returns a FileInfo object that can be queried to determine the file's properties, such as its name and path.

По расширению файла не всегда можно с уверенностью судить о его содержимом.Do not make decisions about the contents of the file based on the file name extension. Например, файл с именем Form1.vb может вовсе не быть исходным файлом Visual Basic.For example, the file Form1.vb may not be a Visual Basic source file.

Определение имени и пути для файлаTo determine a file's name and path

  • Используйте свойства DirectoryName и Name объекта FileInfo , чтобы определить для файла имя и путь.Use the DirectoryName and Name properties of the FileInfo object to determine a file's name and path. В этом примере определяются и отображаются имя и путь.This example determines the name and path and displays them.

    Dim testFile As System.IO.FileInfo testFile = My.Computer.FileSystem.GetFileInfo("C:\TestFolder1\test1.txt") Dim folderPath As String = testFile.DirectoryName MsgBox(folderPath) Dim fileName As String = testFile.Name MsgBox(fileName) 

Объединение имени и каталога файла для создания полного путиTo combine a file's name and directory to create the full path

  • Используйте метод CombinePath , указав каталог и имя.Use the CombinePath method, supplying the directory and name. В этом примере объединяются строки folderPath и fileName , созданные в предыдущем примере, и отображается результат.This example takes the strings folderPath and fileName created in the previous example, combines them, and displays the result.

    Dim fullPath As String fullPath = My.Computer.FileSystem.CombinePath(folderPath, fileName) MsgBox(fullPath) 

См. также разделSee also

Операции с файлами и каталогами - Visual Basic

  • Чтение занимает 7 мин

В этой статье

В этом пошаговом руководстве приводятся основные сведения о файловом вводе-выводе в Visual Basic.This walkthrough provides an introduction to the fundamentals of file I/O in Visual Basic. В нем описывается создание небольшого приложения, перечисляющего текстовые файлы в каталоге и анализирующего их.It describes how to create a small application that lists and examines text files in a directory. Для каждого выбранного текстового файла приложение предоставляет атрибуты файла и первую строку содержимого.For each selected text file, the application provides file attributes and the first line of content. Кроме того, предоставляется возможность записать информацию в файл журнала.There is an option to write information to a log file.

В этом пошаговом руководстве используются члены My.Computer.FileSystem Object, доступные в Visual Basic.This walkthrough uses members of the My.Computer.FileSystem Object, which are available in Visual Basic. Дополнительные сведения см. в разделе FileSystem.See FileSystem for more information. В конце пошагового руководства приводится эквивалентный пример, в котором используются классы пространства имен System.IO.At the end of the walkthrough, an equivalent example is provided that uses classes from the System.IO namespace.

Примечание

Отображаемые на компьютере имена или расположения некоторых элементов пользовательского интерфейса Visual Studio могут отличаться от указанных в следующих инструкциях.Your computer might show different names or locations for some of the Visual Studio user interface elements in the following instructions. Это зависит от имеющегося выпуска Visual Studio и используемых параметров.The Visual Studio edition that you have and the settings that you use determine these elements. Дополнительные сведения см. в разделе Персонализация среды IDE.For more information, see Personalizing the IDE.

Создание проектаTo create the project

  1. В меню Файл выберите пункт Создать проект.On the File menu, click New Project.

    Откроется диалоговое окно Новый проект .The New Project dialog box appears.

  2. В области Установленные шаблоны разверните узел Visual Basic и выберите элемент Windows.In the Installed Templates pane, expand Visual Basic, and then click Windows. В середине области Шаблоны щелкните Приложение Windows Forms.In the Templates pane in the middle, click Windows Forms Application.

  3. В поле Имя введите FileExplorer, чтобы задать имя проекта, а затем нажмите кнопку ОК.In the Name box, type FileExplorer to set the project name, and then click OK.

    Visual Studio добавит проект в обозреватель решений, после чего откроется конструктор Windows Forms.Visual Studio adds the project to Solution Explorer, and the Windows Forms Designer opens.

  4. Добавьте в форму элементы управления из приведенной ниже таблицы и установите для их свойств соответствующие значения.Add the controls in the following table to the form, and set the corresponding values for their properties.

    Элемент управленияControl СвойствоProperty ЗначениеValue
    ListBoxListBox НазваниеName filesListBox
    КнопкаButton НазваниеName

    ТекстText

    browseButton

    ОбзорBrowse

    КнопкаButton НазваниеName

    ТекстText

    examineButton

    ИсследоватьExamine

    CheckBoxCheckBox НазваниеName

    ТекстText

    saveCheckBox

    Сохранить результатыSave Results

    FolderBrowserDialogFolderBrowserDialog НазваниеName FolderBrowserDialog1

Выбор папки и перечисление файлов в нейTo select a folder, and list files in a folder

  1. Создайте обработчик событий нажатия Click для кнопки browseButton, дважды щелкнув этот элемент управления в форме.Create a Click event handler for browseButton by double-clicking the control on the form. Откроется редактор кода.The Code Editor opens.

  2. Добавьте следующий код в обработчик событий Click.Add the following code to the Click event handler.

    If FolderBrowserDialog1.ShowDialog() = DialogResult.OK Then ' List files in the folder. ListFiles(FolderBrowserDialog1.SelectedPath) End If 

    Вызов FolderBrowserDialog1.ShowDialog открывает диалоговое окно Выбор папки.The FolderBrowserDialog1.ShowDialog call opens the Browse For Folder dialog box. Когда пользователь нажимает OK, свойство SelectedPath передается как аргумент методу ListFiles, который добавляется в следующем шаге.After the user clicks OK, the SelectedPath property is sent as an argument to the ListFiles method, which is added in the next step.

  3. Добавьте приведенный ниже метод ListFiles.Add the following ListFiles method.

    Private Sub ListFiles(ByVal folderPath As String) filesListBox.Items.Clear() Dim fileNames = My.Computer.FileSystem.GetFiles( folderPath, FileIO.SearchOption.SearchTopLevelOnly, "*.txt") For Each fileName As String In fileNames filesListBox.Items.Add(fileName) Next End Sub 

    Этот код сперва очищает элемент ListBox.This code first clears the ListBox.

    Затем метод GetFiles возвращает коллекцию строк — по одной для каждого файла в каталоге.The GetFiles method then retrieves a collection of strings, one for each file in the directory. Метод GetFiles принимает аргумент шаблона поиска, чтобы извлечь файлы, соответствующие определенному шаблону.The GetFiles method accepts a search pattern argument to retrieve files that match a particular pattern. В этом примере возвращаются только файлы с расширением TXT.In this example, only files that have the extension .txt are returned.

    Строки, возвращаемые методом GetFiles, затем добавляются в элемент управления ListBox.The strings that are returned by the GetFiles method are then added to the ListBox.

  4. Запустите приложение.Run the application. Нажмите кнопку Обзор.Click the Browse button. В диалоговом окне Выбор папки перейдите в папку, содержащую TXT-файлы, выберите папку и нажмите кнопку ОК.In the Browse For Folder dialog box, browse to a folder that contains .txt files, and then select the folder and click OK.

    Элемент ListBox содержит список TXT-файлов в выбранной папке.The ListBox contains a list of .txt files in the selected folder.

  5. Остановите работу приложения.Stop running the application.

Получение атрибутов файла и содержимого текстового файлаTo obtain attributes of a file, and content from a text file

  1. Создайте обработчик событий нажатия Click для кнопки examineButton, дважды щелкнув этот элемент управления в форме.Create a Click event handler for examineButton by double-clicking the control on the form.

  2. Добавьте следующий код в обработчик событий Click.Add the following code to the Click event handler.

    If filesListBox.SelectedItem Is Nothing Then MessageBox.Show("Please select a file.") Exit Sub End If ' Obtain the file path from the list box selection. Dim filePath = filesListBox.SelectedItem.ToString ' Verify that the file was not removed since the ' Browse button was clicked. If My.Computer.FileSystem.FileExists(filePath) = False Then MessageBox.Show("File Not Found: " & filePath) Exit Sub End If ' Obtain file information in a string. Dim fileInfoText As String = GetTextForOutput(filePath) ' Show the file information. MessageBox.Show(fileInfoText) 

    Этот код проверяет, выбран ли элемент в элементе ListBox.The code verifies that an item is selected in the ListBox. Затем он получает запись пути к файлу из элемента ListBox.It then obtains the file path entry from the ListBox. Метод FileExists позволяет проверить, существует ли файл.The FileExists method is used to check whether the file still exists.

    Путь к файлу передается как аргумент методу GetTextForOutput, который добавляется в следующем шаге.The file path is sent as an argument to the GetTextForOutput method, which is added in the next step. Этот метод возвращает строку, содержащую информацию о файле.This method returns a string that contains file information. Информация о файле отображается в элементе MessageBox.The file information appears in a MessageBox.

  3. Добавьте приведенный ниже метод GetTextForOutput.Add the following GetTextForOutput method.

    Private Function GetTextForOutput(ByVal filePath As String) As String ' Verify that the file exists. If My.Computer.FileSystem.FileExists(filePath) = False Then Throw New Exception("File Not Found: " & filePath) End If ' Create a new StringBuilder, which is used ' to efficiently build strings. Dim sb As New System.Text.StringBuilder() ' Obtain file information. Dim thisFile As System.IO.FileInfo = My.Computer.FileSystem.GetFileInfo(filePath) ' Add file attributes. sb.Append("File: " & thisFile.FullName) sb.Append(vbCrLf) sb.Append("Modified: " & thisFile.LastWriteTime.ToString) sb.Append(vbCrLf) sb.Append("Size: " & thisFile.Length.ToString & " bytes") sb.Append(vbCrLf) ' Open the text file. Dim sr As System.IO.StreamReader = My.Computer.FileSystem.OpenTextFileReader(filePath) ' Add the first line from the file. If sr.Peek() >= 0 Then sb.Append("First Line: " & sr.ReadLine()) End If sr.Close() Return sb.ToString End Function 

    Метод GetFileInfo используется в коде для получения параметров файла.The code uses the GetFileInfo method to obtain file parameters. Параметры файла добавляются в StringBuilder.The file parameters are added to a StringBuilder.

    Метод OpenTextFileReader считывает содержимое файла в StreamReader.The OpenTextFileReader method reads the file contents into a StreamReader. Первая строка содержимого файла извлекается из StreamReader и добавляется в StringBuilder.The first line of the contents is obtained from the StreamReader and is added to the StringBuilder.

  4. Запустите приложение.Run the application. Нажмите кнопку Обзор и перейдите в папку с TXT-файлами.Click Browse, and browse to a folder that contains .txt files. Нажмите кнопку ОК.Click OK.

    Выберите файл в элементе ListBox и щелкните Исследовать.Select a file in the ListBox, and then click Examine. В окне MessageBox будет выведена информация о файле.A MessageBox shows the file information.

  5. Остановите работу приложения.Stop running the application.

Добавление записи в журналTo add a log entry

  1. В конец обработчика событий examineButton_Click добавьте приведенный ниже код.Add the following code to the end of the examineButton_Click event handler.

    If saveCheckBox.Checked = True Then ' Place the log file in the same folder as the examined file. Dim logFolder As String = My.Computer.FileSystem.GetFileInfo(filePath).DirectoryName Dim logFilePath = My.Computer.FileSystem.CombinePath(logFolder, "log.txt") Dim logText As String = "Logged: " & Date.Now.ToString & vbCrLf & fileInfoText & vbCrLf & vbCrLf ' Append text to the log file. My.Computer.FileSystem.WriteAllText(logFilePath, logText, append:=True) End If 

    Код задает путь к файлу журнала, чтобы файл журнала помещался в тот же каталог, где находится выбранный файл.The code sets the log file path to put the log file in the same directory as that of the selected file. Запись журнала должна содержать текущие дату и время, а далее информацию о файле.The text of the log entry is set to the current date and time followed by the file information.

    Метод WriteAllText, которому передается аргумент append со значением True, используется для создания записи в журнале.The WriteAllText method, with the append argument set to True, is used to create the log entry.

  2. Запустите приложение.Run the application. Перейдите к текстовому файлу, выберите его в элементе ListBox, установите флажок Сохранить результаты и щелкните Исследовать.Browse to a text file, select it in the ListBox, select the Save Results check box, and then click Examine. Проверьте, добавлена ли запись в файл log.txt.Verify that the log entry is written to the log.txt file.

  3. Остановите работу приложения.Stop running the application.

Использование текущего каталогаTo use the current directory

  1. Создайте обработчик событий для события Form1_Load, дважды щелкнув форму.Create an event handler for Form1_Load by double-clicking the form.

  2. Добавьте в обработчик событий приведенный ниже код.Add the following code to the event handler.

    ' Set the default directory of the folder browser to the current directory. FolderBrowserDialog1.SelectedPath = My.Computer.FileSystem.CurrentDirectory 

    Этот код задает текущий каталог в качестве каталога по умолчанию для обозревателя папок.This code sets the default directory of the folder browser to the current directory.

  3. Запустите приложение.Run the application. При первом нажатии кнопки Обзор открывается диалоговое окно Выбор папки с текущим каталогом.When you click Browse the first time, the Browse For Folder dialog box opens to the current directory.

  4. Остановите работу приложения.Stop running the application.

Выборочное включение элементов управленияTo selectively enable controls

  1. Добавьте приведенный ниже метод SetEnabled.Add the following SetEnabled method.

    Private Sub SetEnabled() Dim anySelected As Boolean = (filesListBox.SelectedItem IsNot Nothing) examineButton.Enabled = anySelected saveCheckBox.Enabled = anySelected End Sub 

    Метод SetEnabled включает и отключает элементы управления в зависимости от того, выбран ли элемент в элементе ListBox.The SetEnabled method enables or disables controls depending on whether an item is selected in the ListBox.

  2. Создайте обработчик событий SelectedIndexChanged для элемента filesListBox, дважды щелкнув элемент управления ListBox в форме.Create a SelectedIndexChanged event handler for filesListBox by double-clicking the ListBox control on the form.

  3. Добавьте вызов метода SetEnabled в новый обработчик событий filesListBox_SelectedIndexChanged.Add a call to SetEnabled in the new filesListBox_SelectedIndexChanged event handler.

  4. Добавьте вызов метода SetEnabled в конце обработчика событий browseButton_Click.Add a call to SetEnabled at the end of the browseButton_Click event handler.

  5. Добавьте вызов метода SetEnabled в конце обработчика событий Form1_Load.Add a call to SetEnabled at the end of the Form1_Load event handler.

  6. Запустите приложение.Run the application. Флажок Сохранить результаты и кнопка Исследовать отключены, если элемент не выбран в элементе ListBox.The Save Results check box and the Examine button are disabled if an item is not selected in the ListBox.

Полный пример с использованием My.Computer.FileSystemFull example using My.Computer.FileSystem

Ниже приведен полный пример.Following is the complete example.

 ' This example uses members of the My.Computer.FileSystem ' object, which are available in Visual Basic. Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load ' Set the default directory of the folder browser to the current directory. FolderBrowserDialog1.SelectedPath = My.Computer.FileSystem.CurrentDirectory SetEnabled() End Sub Private Sub browseButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles browseButton.Click If FolderBrowserDialog1.ShowDialog() = DialogResult.OK Then ' List files in the folder. ListFiles(FolderBrowserDialog1.SelectedPath) End If SetEnabled() End Sub Private Sub ListFiles(ByVal folderPath As String) filesListBox.Items.Clear() Dim fileNames = My.Computer.FileSystem.GetFiles( folderPath, FileIO.SearchOption.SearchTopLevelOnly, "*.txt") For Each fileName As String In fileNames filesListBox.Items.Add(fileName) Next End Sub Private Sub examineButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles examineButton.Click If filesListBox.SelectedItem Is Nothing Then MessageBox.Show("Please select a file.") Exit Sub End If ' Obtain the file path from the list box selection. Dim filePath = filesListBox.SelectedItem.ToString ' Verify that the file was not removed since the ' Browse button was clicked. If My.Computer.FileSystem.FileExists(filePath) = False Then MessageBox.Show("File Not Found: " & filePath) Exit Sub End If ' Obtain file information in a string. Dim fileInfoText As String = GetTextForOutput(filePath) ' Show the file information. MessageBox.Show(fileInfoText) If saveCheckBox.Checked = True Then ' Place the log file in the same folder as the examined file. Dim logFolder As String = My.Computer.FileSystem.GetFileInfo(filePath).DirectoryName Dim logFilePath = My.Computer.FileSystem.CombinePath(logFolder, "log.txt") Dim logText As String = "Logged: " & Date.Now.ToString & vbCrLf & fileInfoText & vbCrLf & vbCrLf ' Append text to the log file. My.Computer.FileSystem.WriteAllText(logFilePath, logText, append:=True) End If End Sub Private Function GetTextForOutput(ByVal filePath As String) As String ' Verify that the file exists. If My.Computer.FileSystem.FileExists(filePath) = False Then Throw New Exception("File Not Found: " & filePath) End If ' Create a new StringBuilder, which is used ' to efficiently build strings. Dim sb As New System.Text.StringBuilder() ' Obtain file information. Dim thisFile As System.IO.FileInfo = My.Computer.FileSystem.GetFileInfo(filePath) ' Add file attributes. sb.Append("File: " & thisFile.FullName) sb.Append(vbCrLf) sb.Append("Modified: " & thisFile.LastWriteTime.ToString) sb.Append(vbCrLf) sb.Append("Size: " & thisFile.Length.ToString & " bytes") sb.Append(vbCrLf) ' Open the text file. Dim sr As System.IO.StreamReader = My.Computer.FileSystem.OpenTextFileReader(filePath) ' Add the first line from the file. If sr.Peek() >= 0 Then sb.Append("First Line: " & sr.ReadLine()) End If sr.Close() Return sb.ToString End Function Private Sub filesListBox_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles filesListBox.SelectedIndexChanged SetEnabled() End Sub Private Sub SetEnabled() Dim anySelected As Boolean = (filesListBox.SelectedItem IsNot Nothing) examineButton.Enabled = anySelected saveCheckBox.Enabled = anySelected End Sub 

Полный пример с использованием System.IOFull example using System.IO

Следующий пример выполняет те же действия, используя классы из пространства имен System.IO вместо объектов My.Computer.FileSystem.The following equivalent example uses classes from the System.IO namespace instead of using My.Computer.FileSystem objects.

 ' This example uses classes from the System.IO namespace. Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load ' Set the default directory of the folder browser to the current directory. FolderBrowserDialog1.SelectedPath = System.IO.Directory.GetCurrentDirectory() SetEnabled() End Sub Private Sub browseButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles browseButton.Click If FolderBrowserDialog1.ShowDialog() = DialogResult.OK Then ' List files in the folder. ListFiles(FolderBrowserDialog1.SelectedPath) SetEnabled() End If End Sub Private Sub ListFiles(ByVal folderPath As String) filesListBox.Items.Clear() Dim fileNames As String() = System.IO.Directory.GetFiles(folderPath, "*.txt", System.IO.SearchOption.TopDirectoryOnly) For Each fileName As String In fileNames filesListBox.Items.Add(fileName) Next End Sub Private Sub examineButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles examineButton.Click If filesListBox.SelectedItem Is Nothing Then MessageBox.Show("Please select a file.") Exit Sub End If ' Obtain the file path from the list box selection. Dim filePath = filesListBox.SelectedItem.ToString ' Verify that the file was not removed since the ' Browse button was clicked. If System.IO.File.Exists(filePath) = False Then MessageBox.Show("File Not Found: " & filePath) Exit Sub End If ' Obtain file information in a string. Dim fileInfoText As String = GetTextForOutput(filePath) ' Show the file information. MessageBox.Show(fileInfoText) If saveCheckBox.Checked = True Then ' Place the log file in the same folder as the examined file. Dim logFolder As String = System.IO.Path.GetDirectoryName(filePath) Dim logFilePath = System.IO.Path.Combine(logFolder, "log.txt") ' Append text to the log file. Dim logText As String = "Logged: " & Date.Now.ToString & vbCrLf & fileInfoText & vbCrLf & vbCrLf System.IO.File.AppendAllText(logFilePath, logText) End If End Sub Private Function GetTextForOutput(ByVal filePath As String) As String ' Verify that the file exists. If System.IO.File.Exists(filePath) = False Then Throw New Exception("File Not Found: " & filePath) End If ' Create a new StringBuilder, which is used ' to efficiently build strings. Dim sb As New System.Text.StringBuilder() ' Obtain file information. Dim thisFile As New System.IO.FileInfo(filePath) ' Add file attributes. sb.Append("File: " & thisFile.FullName) sb.Append(vbCrLf) sb.Append("Modified: " & thisFile.LastWriteTime.ToString) sb.Append(vbCrLf) sb.Append("Size: " & thisFile.Length.ToString & " bytes") sb.Append(vbCrLf) ' Open the text file. Dim sr As System.IO.StreamReader = System.IO.File.OpenText(filePath) ' Add the first line from the file. If sr.Peek() >= 0 Then sb.Append("First Line: " & sr.ReadLine()) End If sr.Close() Return sb.ToString End Function Private Sub filesListBox_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles filesListBox.SelectedIndexChanged SetEnabled() End Sub Private Sub SetEnabled() Dim anySelected As Boolean = (filesListBox.SelectedItem IsNot Nothing) examineButton.Enabled = anySelected saveCheckBox.Enabled = anySelected End Sub 

См. также разделSee also

Оператор put (VBA) | Microsoft Docs

  • Чтение занимает 4 мин

В этой статье

Записывает данные из переменной в файл на диске.Writes data from a variable to a disk file.

СинтаксисSyntax

Put [ # ] FileNumber, [ рекнумбер ], имя_переменнойPut [ # ] filenumber, [ recnumber ], varname

Синтаксис оператора Put состоит из следующих частей:The Put statement syntax has these parts:

ЧастьPart ОписаниеDescription
filenumberfilenumber Обязательно указывать.Required. Любой допустимый номер файла.Any valid file number.
рекнумберrecnumber Необязательно.Optional. Имеет тип Variant (Long).Variant (Long). Номер записи (файлы в режиме Random) или номер байта (файлы в режиме Binary), определяющий место начала записи.Record number (Random mode files) or byte number (Binary mode files) at which writing begins.
varnamevarname Обязательный.Required. Имя переменной, содержащей данные, которые необходимо записать на диск.Name of the variable containing data to be written to disk.

ПримечанияRemarks

Данные, записанные с помощью Put , обычно считываются из файла с помощью Get.Data written with Put is usually read from a file with Get.

Первая запись или байт в файле находятся на позиции 1, вторая запись или байт — на позиции 2 и т. д.The first record or byte in a file is at position 1, the second record or byte is at position 2, and so on. Если опустить рекнумбер, записывается следующая запись или байт после последнего оператора Get или Put или, на который указывает последняя функция поиска , записывается.If you omit recnumber, the next record or byte after the last Get or Put statement, or pointed to by the last Seek function, is written. Необходимо добавить разделяющие запятые, например:You must include delimiting commas, for example:

Put #4,,FileBuffer 

Для файлов, открытых в случайном режиме, применяются следующие правила:For files opened in Random mode, the following rules apply:

  • Если длина записываемых данных меньше длины, указанной в предложении Len оператора Open , то функция Put записывает последующие записи по границам записей.If the length of the data being written is less than the length specified in the Len clause of the Open statement, Put writes subsequent records on record-length boundaries. Пространство между концом одной записи и началом следующей записи заполняется существующим содержимым файлового буфера.The space between the end of one record and the beginning of the next record is padded with the existing contents of the file buffer. Поскольку объем данных для заполнения не может быть точно определен, обычно рекомендуется, чтобы длина записи соответствовала длине записываемых данных.Because the amount of padding data can't be determined with any certainty, it is generally a good idea to have the record length match the length of the data being written. Если длина записываемых данных окажется больше длины, указанной в предложении Len оператора Open, возникает ошибка.If the length of the data being written is greater than the length specified in the Len clause of the Open statement, an error occurs.

  • Если записываемая переменная является строкой переменной длины, оператор Put записывает 2-байтовый дескриптор, содержащий длину строки, а затем переменную.If the variable being written is a variable-length string, Put writes a 2-byte descriptor containing the string length and then the variable. Длина записи, указанная предложением Len в операторе Open, должна быть по крайней мере на 2 байта больше, чем фактическая длина строки.The record length specified by the Len clause in the Open statement must be at least 2 bytes greater than the actual length of the string.

  • Если записываемая переменная имеет тип Variantчислового типа, оператор Put записывает 2 байта, указывающих VarType типа Variant, а затем записывает переменную.If the variable being written is a Variant of a numeric type, Put writes 2 bytes identifying the VarType of the Variant and then writes the variable. Например, при записи типа Variant как VarType 3, оператор Put записывает 6 байтов: 2 байта, указывающих тип Variant как VarType 3 (Long), и 4 байта, содержащих данные типа Long.For example, when writing a Variant of VarType 3, Put writes 6 bytes: 2 bytes identifying the Variant as VarType 3 (Long) and 4 bytes containing the Long data. Длина записи, указанная предложением Len в операторе Open, должна быть по крайней мере на 2 байта больше фактического числа байтов, необходимых для сохранения переменной.The record length specified by the Len clause in the Open statement must be at least 2 bytes greater than the actual number of bytes required to store the variable.

    Примечание

    Оператор Put можно использовать для записимассива Variantна диск, но нельзя использовать Put для записи скалярного варианта , содержащего массив на диск.You can use the Put statement to write a Variantarray to disk, but you can't use Put to write a scalar Variant containing an array to disk. Нельзя также использовать оператор Put для записи объектов на диск.You also can't use Put to write objects to disk.

  • Если записываемая переменная имеет тип Variant как VarType 8 (String), оператор Put записывает 2 байта, указывающих тип VarType, 2 байта, указывающих длину строки, а затем записывает строку данных.If the variable being written is a Variant of VarType 8 (String), Put writes 2 bytes identifying the VarType, 2 bytes indicating the length of the string, and then writes the string data. Длина строки, указанная в предложении Len оператора Open, должна быть по крайней мере на 4 байта больше фактической длины строки.The record length specified by the Len clause in the Open statement must be at least 4 bytes greater than the actual length of the string.

  • Если записываемая переменная является динамическим массивом, Put записывает дескриптор, длина которого равна 2 плюс в 8 раз больше числа измерений, то есть 2 + 8 * нумберофдименсионс.If the variable being written is a dynamic array, Put writes a descriptor whose length equals 2 plus 8 times the number of dimensions, that is, 2 + 8 * NumberOfDimensions. Длина записи, заданная в предложении Len в операторе Open , должна быть больше или равна сумме всех байтов, необходимых для записи данных массива и дескриптора массива.The record length specified by the Len clause in the Open statement must be greater than or equal to the sum of all the bytes required to write the array data and the array descriptor. Например, для записи представленного ниже массива на диск необходимо 118 байт.For example, the following array declaration requires 118 bytes when the array is written to disk.

    Dim MyArray(1 To 5,1 To 10) As Integer 
  • 118 байт распределяются следующим образом: 18 байт для дескриптора (2 + 8 * 2) и 100 байт для данных (5 * 10 * 2).The 118 bytes are distributed as follows: 18 bytes for the descriptor (2 + 8 * 2), and 100 bytes for the data (5 * 10 * 2).

  • Если записываемая переменная является массивом фиксированного размера, оператор Put записывает только данные.If the variable being written is a fixed-size array, Put writes only the data. Дескриптор не записывается на диск.No descriptor is written to disk.

  • Если записываемая переменная является переменной любого другого типа (не переменной с переменной длиной и не переменной типа Variant), оператор Put записывает только данные переменной.If the variable being written is any other type of variable (not a variable-length string or a Variant), Put writes only the variable data. Длина записи, указанная в предложении Len оператора Open, должна быть больше длины записываемых данных или равна ей.The record length specified by the Len clause in the Open statement must be greater than or equal to the length of the data being written.

  • Put записывает элементы пользовательских типов так, как если бы они были записаны отдельно, за исключением отсутствия заполнения между элементами.Put writes elements of user-defined types as if each were written individually, except that there is no padding between elements. На диске динамический массив в пользовательском типе, написанном с помощью оператора Put , предваряется дескриптором, длина которого равна 2 плюс 8 раз, то есть 2 + 8 * нумберофдименсионс.On disk, a dynamic array in a user-defined type written with Put is prefixed by a descriptor whose length equals 2 plus 8 times the number of dimensions, that is, 2 + 8 * NumberOfDimensions. Длина записи, заданная в предложении Len в операторе Open , должна быть больше или равна сумме всех байтов, необходимых для записи отдельных элементов, включая массивы и их дескрипторы.The record length specified by the Len clause in the Open statement must be greater than or equal to the sum of all the bytes required to write the individual elements, including any arrays and their descriptors.

Для файлов, открытых в двоичном режиме, применяются все правила случайного режима, кроме следующих случаев:For files opened in Binary mode, all of the Random rules apply, except:

  • Предложение Len оператора Open не оказывает какого-либо влияния.The Len clause in the Open statement has no effect. Оператор Put записывает все переменные на диск последовательно; это означает, что не применяется заполнение между записями.Put writes all variables to disk contiguously; that is, with no padding between records.

  • Для любого другого массива, отличного массива, имеющего тип, определяемый пользователем, оператор Put записывает только данные.For any array other than an array in a user-defined type, Put writes only the data. Дескриптор при этом не записывается.No descriptor is written.

  • Оператор Put записывает строки переменной длины, не являющиеся элементами типов, определяемых пользователем, без дескриптора, имеющего длину в 2 байта.Put writes variable-length strings that are not elements of user-defined types without the 2-byte length descriptor. Число записанных байтов равняется числу знаков в строке.The number of bytes written equals the number of characters in the string. Например, следующие операторы записывают 10 байтов в файл номер 1:For example, the following statements write 10 bytes to file number 1:

     VarString$ = String$(10," ") Put #1,,VarString$ 

ПримерExample

В этом примере используется оператор Put для записи данных в файл.This example uses the Put statement to write data to a file. В файл записываются пять записей определяемого пользователем типа.Five records of the user-defined type are written to the file.

Type Record ' Define user-defined type. ID As Integer Name As String * 20 End Type Dim MyRecord As Record, RecordNumber ' Declare variables. ' Open file for random access. Open "TESTFILE" For Random As #1 Len = Len(MyRecord) For RecordNumber = 1 To 5 ' Loop 5 times. MyRecord.ID = RecordNumber ' Define ID. MyRecord.Name = "My Name" & RecordNumber ' Create a string. Put #1, RecordNumber, MyRecord ' Write record to file. Next RecordNumber Close #1 ' Close file. 

См. такжеSee also

Поддержка и обратная связьSupport and feedback

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи?Have questions or feedback about Office VBA or this documentation? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

Как указать путь к файлу excel в моем VBA?



Как я уже говорил, Путь мой файл excel в моем vba? То, что я пытаюсь сделать, это скопировать содержимое файла excel в конец другого файла excel. Я выбрал все ячейки файла excel и скопировал их следующим образом

This is my excelfile1.xlsx Range("A2").Select Range(Selection, Selection.End(xlToRight)).Select Range(Selection, Selection.End(xlDown)).Select Selection.Copy 

Теперь после копирования всего файла я должен вставить его в конец другого файла excel, расположенного в D:\samples\excel2.xls

Как я могу указать путь к этому файлу в VBA и вставить его в конец из моего кода VBA?

vba excel
Поделиться Источник niko     01 августа 2011 в 12:52

1 ответ


  • Нужен ли путь к файлу в функции (Shell) VBA?

    У меня есть Matlab-сгенерированный исполняемый файл, Myfile.exe , чтобы позвонить из excel-vba . Я узнал (функция Shell) - это то, что мне нужно использовать. Я не хочу включать весь путь к файлу, так как не хочу ограничивать пользователя определенной папкой в определенном месте на каждом...

  • C# ProcessStartInfo: как указать путь к файлу?

    Я вижу, что в ProcessStartInfo можно указать имя файла, но как указать путь к файлу? Спасибо.



2

Если вы запишете этот шаг действий, вы получите почти тот же самый код, который был бы результатом написания его вручную;

Workbooks.Open Filename:="d:\samples\excel2.xls" Range("Al").Select ActiveSheet.Paste 

Поделиться Alex K.     01 августа 2011 в 12:57


Похожие вопросы:


Как указать путь к файлу в Java?

Хорошо, это домашние вопросы, но я не могу найти ответ нигде, даже в книге. Путь к файлам Если пользователь хочет указать путь к файлу, типичная прямая косая черта заменяется на __________________....


Путь к файлу AutoCAD, содержащему файл Excel

У меня есть встроенный Excel (.xls) файл в формате AutoCAD (.файл DWG. Используя VBA (под Excel), я хочу извлечь путь к файлу, который его содержит (путь к файлу AutoCAD).


Путь к файлу ссылок в документе Word

Я работаю над excel vba, я просто хочу получить доступ к документу word и перечислить путь к файлу всех ссылок в нем. т.е.. c:\excelfile.xls


Нужен ли путь к файлу в функции (Shell) VBA?

У меня есть Matlab-сгенерированный исполняемый файл, Myfile.exe , чтобы позвонить из excel-vba . Я узнал (функция Shell) - это то, что мне нужно использовать. Я не хочу включать весь путь к файлу,...


C# ProcessStartInfo: как указать путь к файлу?

Я вижу, что в ProcessStartInfo можно указать имя файла, но как указать путь к файлу? Спасибо.


Как указать другой путь к файлу для сохраненного импорта Excel

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


Используйте Excel VBA для изменения подключения Powerpivot к файлу csv

Как я могу использовать vba для изменения подключения Powerpivot к файлу csv? У меня есть книга Excel с моделью Powerpivot, которая подключается к файлу csv. В окне Powerpivot я могу перейти на...


Замените путь к файлу в VBA на имя пользователя

У меня есть файл Excel с записанным на нем VBA, который извлекает информацию из файла на моем компьютере. Файл Excel находится в сетевой папке, и я хотел бы, чтобы другие пользователи в сети также...


Как указать путь к файлу в файле web.xml

я разрабатываю приложение в java, и я новичок в этой платформе java ee. У меня есть файл набора данных под названием 51Degrees-EnterpriseV3_2.dat в моей папке ресурсов. как указать путь к этому...


Откройте презентацию PowerPoint из Excel с помощью VBA без указания пути к файлу Excel

Я ищу способ для VBA в PowerPoint автоматически идентифицировать единственный открытый файл Excel на моем компьютере и использовать этот файл Excel для чтения данных из него. Я бы хотел избежать...

Свойство Document. Path (Word) | Microsoft Docs

  • Чтение занимает 2 мин

В этой статье

Возвращает диск или веб-путь к документу.Returns the disk or Web path to the document. Строка, доступная только для чтения.Read-only String.

СинтаксисSyntax

Expression. Path (путь )expression.Path

выражение (обязательно).expression Required. Переменная, представляющая объект Document .A variable that represents a Document object.

ПримечанияRemarks

Путь не включает замыкающий символ (например, "К:\мсоффицеhttps://MyServer" или ""), если не запрашивается путь к документу, хранящемуся в корне сетевого диска (например, для Н:\филе.доккс "n\:" указано значение N — это сетевой диск, по сравнению с "c:" для к:\филе.доккс, где C — это локальный диск).The path doesn't include a trailing character — for example, "C:\MSOffice" or "https://MyServer" — unless requesting a path of a document stored at a network drive root (e.g. for N:\file.docx "N:\" is returned provided N is a network drive, compared to "C:" for C:\file.docx where C is a local drive).

Используйте свойство пассепаратор для добавления знака, который отделяет папки и буквы дисков.Use the PathSeparator property to add the character that separates folders and drive letters. Используйте свойство Name для возврата имени файла без пути и используйте свойство FullName , чтобы вернуть имя файла и путь вместе.Use the Name property to return the file name without the path and use the FullName property to return the file name and the path together.

Примечание

Свойство пассепаратор можно использовать для создания веб-адресов, несмотря на то, что они содержат косую черту (/), а свойство пассепаратор по умолчанию имеет обратную косую черту ().You can use the PathSeparator property to build web addresses even though they contain forward slashes (/) and the PathSeparator property defaults to a backslash ().

ПримерExample

В этом примере отображается путь и имя файла активного документа.This example displays the path and file name of the active document.

MsgBox ActiveDocument.Path & Application.PathSeparator & _ ActiveDocument.Name 

В этом примере показано, как изменить текущую папку на путь к шаблону, присоединенному к активному документу.This example changes the current folder to the path of the template attached to the active document.

ChDir ActiveDocument.AttachedTemplate.Path 

См. такжеSee also

Объект DocumentDocument Object

Поддержка и обратная связьSupport and feedback

Есть вопросы или отзывы, касающиеся Office VBA или этой статьи?Have questions or feedback about Office VBA or this documentation? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.

Относительные вместо абсолютных путей в Excel VBA

Я написал макрос Excel VBA, который импортирует данные из HTML-файла (хранится локально) перед выполнением вычислений по данным.

на данный момент HTML-файл упоминается с абсолютным путем:

Workbooks.Open FileName:="C:\Documents and Settings\Senior Caterer\My Documents\Endurance Calculation\TRICATEndurance Summary.html" 

однако я хочу использовать относительный путь, чтобы ссылаться на него, а не на абсолют (это потому, что я хочу распространять электронную таблицу коллегам, которые могут не использовать ту же структуру папок). Как html-файл и электронная таблица excel сидят в в той же папке я бы не подумал, что это будет сложно, однако я просто не могу этого сделать. Я искал в интернете, и предлагаемые решения все оказались очень сложными.

Я использую Excel 2000 и 2002 на работе, но поскольку я планирую его распространять, я бы хотел, чтобы он работал с как можно большим количеством версий Excel.

любые предложения с благодарностью приняты.

36