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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

键盘上的舞指

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值