vba中如何读取文件中的数据,并赋值给一个二维数组

2025年03月25日 04:22
有2个网友回答
网友(1):

Public Function readFileToVariable(strFileName)
'===============================================
' 读取文本文件到一个变量
' @Param strFileName String 文件路径
' @Retrun String 文本文件的内容
' @Ver 0.1
' @Date 2015.9.25

'===============================================
Const ForReading = 1 '文件只读常量
Dim objFso, objFile 'FSO,文件
Dim strFile '文件内容
Set objFso = CreateObject("Scripting.FileSystemObject")
Set objFile = objFso.OpenTextFile(strFileName, ForReading)
readFileToVariable = objFile.ReadAll
objFile.Close
End Function

Public Function readFileToArray(strFileName)
'===============================================
' 读取文本文件到一个数组
' @Param strFileName String 文件路径
' @Retrun Array 文本文件的内容
' @Ver 0.3
' @Date 2015.9.29
' @Comment
' 修正函数名拼写错误的Bug
' By klsjnh@qq.com
'===============================================
Dim strFile
strFile = readFileToVariable(strFileName)
readFileToArray = Split(strFile, vbCrLf)
End Function

网友(2):

首先导入到一个表格(分隔符为空格)

添加代码:

Private a() As Long
Public Sub ReadCells()
    ReDim a(5, 30)
    Dim x As Long, y As Long
    For x = 1 To 5
        For y = 1 To 30
            a(x, y) = Sheet1.Cells(y, x)
        Next
    Next
End Sub

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    ReadCells
    MsgBox a(3, 3)
End Sub

(下面的是一个测试,代码定义在Sheet1里)