VB读取txt文件的方法

'第一种方法:
Public Function ByteOpenFile(FilePath As String) As String
Dim tmp() As Byte
Open FilePath For Binary As #1
ReDim tmp(LOF(1) - 1)
Get #1, , tmp
ByteOpenFile = StrConv(tmp, vbUnicode)
Close #1
End Function


'第二种方法:
Private Sub Command4_Click() '读取整个TXT文件
Dim fso As Object, ts As Object
Text1 = “”
Set fso = CreateObject(“Scripting.FileSystemObject”)
Set ts = fso.opentextfile(App.Path & “\test.txt”, 1)
Do While ts.AtEndofStream <> True
Text1 = Text1 & ts.ReadLine & vbCrLf
Loop
ts.Close
Set ts = Nothing
Set fso = Nothing
End Sub


'第三种方法:
Private Sub Command1_Click()
Dim txt As String
Close #1
Text1.Text = “”
Open “D:\gfhgfh.bmp” For Input As #1
Do While Not EOF(1)
Input #1, txt
Text1.Text = Text1.Text & txt & Chr(13) & Chr(10)
Loop
End Sub


'第四种方法:
快速读写
Option Explicit
Private Sub Command1_Click()'读
Text1.Text = CreateObject(“scripting.filesystemobject”).opentextfile(“c:\1.txt”).readall '这句用来读取制定TXT,会返回内容
End Sub

Private Sub Command2_Click()'存
Call CreateObject(“Scripting.FileSystemObject”).createtextfile(“c:\1.txt”).writeline(Text1.Text)
End Sub


'第五种方法:
Private Sub Command2_Click()
Open “C:\Documents and Settings\Administrator\桌面\5笔\TANYITXT32\2512.txt” For Binary As #1
Text1 = StrConv(InputB$(LOF(1), 1), vbUnicode)
Close #1
End Sub


'第六种方法:
读取到数组变量里

Dim Txt() As String
Private Sub Form_Load()
Dim arr, i As Long
arr = Split(CreateObject(“scripting.filesystemobject”).opentextfile(“c:\123.txt”).readall, vbNewLine)
For i = 0 To UBound(arr)
ReDim Preserve Txt(i)
Txt(i) = arr(i)
List1.AddItem Txt(i)
Next
End Sub

获得总行
Private Declare Function SendMessage Lib “user32” Alias “SendMessageA” (ByVal hwnd As Long, ByVal wMsg As Long, ByVal wParam As Long, lParam As Any) As Long
Private Const EM_GETLINECOUNT = &HBA
Private Sub Command1_Click()
s = SendMessage(Text1.hwnd, EM_GETLINECOUNT, 0, 0)
Text2 = s
End Sub


'第七种方法:其他

清空一个TXT文件内容
Private Sub Command1_Click()
Shell “cmd /c echo off>e:\xixihaha1.txt”, 0
End Sub


指定读取某行的数据:
1、自己定义一个函数:
Private Function GetTxt(TxtPath As String)
Dim i%
i = FreeFile
Open TxtPath For Input As #i
GetTxt = StrConv(InputB(LOF(i), i), vbUnicode)
Close #i
End Function

2、调用:
Private Sub Command1_Click()
MsgBox Split(GetTxt(App.Path & “\test.txt”), vbCrLf)(1)
End Sub

你可能感兴趣的:(VisualBasic编程源码,VB读取TXT文件的方法)