龙空技术网

ExcelVBA:读取txt文件内容并保存到数组,将数组添加到ListView

KNAB单人乐队 407

前言:

眼前朋友们对“vbnet如何按行读取txt中的数据”大致比较看重,看官们都想要分析一些“vbnet如何按行读取txt中的数据”的相关资讯。那么小编也在网络上网罗了一些有关“vbnet如何按行读取txt中的数据””的相关资讯,希望兄弟们能喜欢,兄弟们快快来学习一下吧!

添加后的结果是:

主要涉及两个函数。

以下是:读取文本文件,并赋值给数组

Function ReadTextFileToArray(strFileName As String) As Variant    Dim strText As String    Dim lines() As String    Dim dataArray() As Variant    Dim i As Long, j As Long        ' 使用 ReadTextFromFullFile 函数读取整个文件内容    strText = ReadTextFromFullFile(strFileName)         If Trim(strText) = "" Then        ReadTextFileToArray = Array()        Exit Function    End If     lines = Split(strText, vbCrLf)         Dim columns() As String    columns = Split(lines(0), "|")        ReDim dataArray(0 To UBound(lines), 0 To UBound(columns))     For i = LBound(lines) To UBound(lines)        ' 使用 | 分割每一行,得到列值数组        columns = Split(lines(i), "|")                For j = LBound(columns) To UBound(columns)            dataArray(i, j) = columns(j)        Next j    Next i        ReadTextFileToArray = dataArrayEnd Function
以下是:将数组添加到 ListView控件
Sub addArrayToListView(dataArray As Variant, objListView As listView)    Dim i As Long, j As Long    Dim listItem As listItem    Dim rowCounter As Long     If UBound(dataArray, 2) <> 2 Then        Exit Sub    End If     rowCounter = 1         For i = LBound(dataArray, 1) + 1 To UBound(dataArray, 1)         Set listItem = objListView.ListItems.Add()                ' 序号,格式为:000        listItem.text = Format(rowCounter, "000")        ' 添加子项,列数据        For j = LBound(dataArray, 2) To UBound(dataArray, 2)            listItem.SubItems(j + 1) = dataArray(i, j)        Next j                rowCounter = rowCounter + 1    Next i    End Sub

标签: #vbnet如何按行读取txt中的数据