VB如何打开一个文本文件?

VB如何打开一个文本文件?,第1张

1、获取文本文件路径\x0d\x0a2、通过流的方式打开文本文件\x0d\x0a示例:\x0d\x0aDim MyString\x0d\x0aPrivate Sub Command1_Click() ’按钮事件\x0d\x0a Open App.Path + "\Myfile.txt" For Input As #1 '打开文本文件,读取。\x0d\x0a Do While Not EOF(1) '是否没到文件末尾\x0d\x0a Input #1, MyString '读取文件内容\x0d\x0a Loop\x0d\x0a Close #1\x0d\x0aEnd Sub

调用API的功能实现,

因相应的API较复杂,不太好理解,我用子程序对它做了封装。

实际使用过程中你将下面这段代码Copy到程序模块中,然后调用SubOpenFile子程序就行了。

'注意在引用该FSO功能时先引用 Microsoft Scripting Runtime

Public ObjFso As New FileSystemObject

Declare Function shellExecute Lib "shell32.dll" Alias "ShellExecuteA" _

(ByVal hwnd As Long, ByVal lpOperation As String, ByVal lpFile As String, _

ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long

Public Sub SubOpenFile(ByVal FileSaveName As String, ByVal StrFrmName As Form)

'打开文件

'输入:sFileName 待打开文件的全路径加上文件名,如 "F:\VB\RunExe\Module1.bas"

'输入:调用该子程序的窗体名称

If Not ObjFso.FileExists(FileSaveName) Then

MsgBox ("没有找到要打开的文件")

Exit Sub

End If

sCorrectPath = ObjFso.GetParentFolderName(FileSaveName)

sFileName = ObjFso.GetFileName(FileSaveName)

'输入:调用该子程序的窗体名称

lHwnd = StrFrmName.hwnd

'lShellFile = shellExecute(lHwnd, "open", FileSaveName, vbNullString, sCorrectPath, SW_SHOWNORMAL)

lShellFile = shellExecute(lHwnd, "open", FileSaveName, vbNullString, sCorrectPath, 5)

'错误处理

If lShellFile >32 Then

Exit Sub

Else

Select Case lShellFile

Case 2

If Right(sFileName, 3) <>"htm" Then

MsgBox "File Not Found.", vbCritical + vbOKOnly, "X-File:"

End If

Exit Sub

Case 3

MsgBox "Path not Found.", vbCritical + vbOKOnly, "X-File:"

Exit Sub

Case 5

MsgBox "Access denied.", vbCritical + vbOKOnly, "X-File:"

Exit Sub

Case 8

MsgBox "Out of Memory.", vbCritical + vbOKOnly, "X-File:"

Exit Sub

Case 32

MsgBox "Shell32.dll not Found.", vbCritical + vbOKOnly, "X-File:"

Exit Sub

End Select

End If

End Sub

以下代码已经经过测试。主要演示了打开和写入 *** 作。

form1中添加text1和command1,粘贴如下代码

Private Sub Command1_Click()

Dim strName As String

strName = App.Path &"\" &Text1.Text &".txt"

WriteFile (strName)

Call RunFile(strName)

End Sub

'演示后台打开记事本,然后写入字符

Private Sub WriteFile(ByVal FilePath As String)

Open FilePath For Append As #1

Print #1, "这是我用VB写进去的字符"

Close #1

End Sub

'演示打开记事本,并最大化窗口

Private Sub RunFile(ByVal FilePath As String)

Shell "Notepad " &FilePath, vbMaximizedFocus

End Sub

Private Sub Form_Load()

Text1.Text = "在这里输入文件名"

End Sub

Private Sub Text1_Click()

Text1.Text = ""

End Sub

运行后,在vbp所在路径可以看到一个刚刚新建的文本。


欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/tougao/11448822.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-05-16
下一篇2023-05-16

发表评论

登录后才能评论

评论列表(0条)

    保存