如何用VBA将文本文件每行内容分别赋值给独立变量?
VBA读取多行登录信息拆分到变量的解决方案
方法一:逐行读取(适合固定行数的小文件)
直接通过Line Input语句逐行读取文件内容,分别赋值给对应变量,逻辑简单直观:
Sub ReadLogonInfo() Dim strFile As String Dim strUsername As String Dim strPassword As String Dim iTxtFile As Integer strFile = "C:\temp\logon.txt" iTxtFile = FreeFile Open strFile For Input As iTxtFile Line Input #iTxtFile, strUsername '读取第一行到用户名变量 Line Input #iTxtFile, strPassword '读取第二行到密码变量 Close iTxtFile '测试输出(可根据需求删除) Debug.Print "用户名:" & strUsername Debug.Print "密码:" & strPassword End Sub
方法二:拆分整体字符串(适合行数不固定的场景)
如果已经读取了整个文件的字符串内容,可以用Split函数按换行符拆分出每行内容,再提取到变量:
Sub ReadFileAndSplit() Dim iTxtFile As Integer Dim strFile As String Dim strFileText As String Dim arrLines As Variant Dim strUsername As String Dim strPassword As String strFile = "C:\temp\logon.txt" iTxtFile = FreeFile Open strFile For Input As iTxtFile strFileText = Input(LOF(iTxtFile), iTxtFile) Close iTxtFile '按Windows换行符(vbCrLf)拆分,若文件是Unix格式可改为vbLf arrLines = Split(strFileText, vbCrLf) '提取数组中对应行的内容 strUsername = arrLines(0) strPassword = arrLines(1) '测试输出(可根据需求删除) Debug.Print "用户名:" & strUsername Debug.Print "密码:" & strPassword End Sub
两种方法都能实现需求,可根据文件行数是否固定选择:逐行读取适合明确知道行数的情况,拆分字符串则更灵活,适合需要批量处理多行内容的场景。
内容的提问来源于stack exchange,提问作者Jonnyboi
相关产品推荐
相关产品推荐

