Open 语句

打开一个数据通道。

语法:

Open FileName As String [For Mode] [Access IOMode] [Protected] As [#]FileNumber As Integer [Len = DatasetLength]

参数:

FileName: Name and path of the file to open. If you try to read a file that does not exist (Access = Read), an error message appears. If you try to write to a file that does not exist (Access = Write), a new file is created.

Mode: 指定文件模式的“关键字”。有效值: Append(附加至顺序文件),Binary(可以使用 Get 和 Put 按字节访问的数据),Input(打开数据通道以便读取),Output(打开数据通道以便写入)和 Random(编辑相关文件)。

IOMode:定义访问类型的关键字。有效值:Read(只读)、Write(只写)和 Read Write(读写)。

Protected:指定文件打开后的安全状态的关键字。有效值:Shared(文件可以被其他应用程序打开)、Lock Read(文件受读取保护)、Lock Write(文件受写入保护)、Lock Read Write(拒绝对文件进行访问)。

FileNumber:指定可用数据通道数目的任意整数表达式,其值必须在 0 到 511 之间。您可以通过数据通道传送命令以访问文件。文件编号需要借助 Open 语句之前的 FreeFile 函数来确定。

DatasetLength:对于随机访问文件,将设置记录的长度。

批注图标

您只能修改通过 Open 语句打开的文件的内容。如果您尝试打开一个已经打开的文件,则会显示一个错误信息。


示例:

Sub ExampleWorkWithAFile

Dim iNumber As Integer

Dim sLine As String

Dim aFile As String

Dim sMsg As String

    aFile = "c:\data.txt"

    iNumber = Freefile

    Open aFile For Output As #iNumber

    Print #iNumber, "This is a line of text"

    Print #iNumber, "This is another line of text"

    Close #iNumber

    iNumber = Freefile

    Open aFile For Input As iNumber

    While Not eof(iNumber)

        Line Input #iNumber, sLine

        If sLine <>"" Then

            sMsg = sMsg & sLine & chr(13)

        End If

    Wend

    Close #iNumber

    MsgBox sMsg

End Sub