在 VBA Excel 中难以找到行尾

Posted

技术标签:

【中文标题】在 VBA Excel 中难以找到行尾【英文标题】:Difficulty in finding end of row in VB Excel 【发布时间】:2013-07-23 06:26:34 【问题描述】:

我正在从 .txt 文件中读取信息,该文本文件有 2 行和 6 列;每个元素由空格或制表符分隔。我有数据可以读取所有字符串,但我发现很难将数据放入单元格。如何找到第一行的结尾。

文本文件:

$SUBCASE       1                             1
$DISP          0     509       5       1     2

下面是完整的代码,我只得到第一个字符串,其余的没有......

Private Sub PCH_Click()
Dim arTemp() As Variant
Dim lRet As String
Dim sVal As String
Dim Row As Long
Dim Col As Long
Dim ws As Worksheet
Set ws = Worksheets("Sheet1")
'Default method Uses Open Dialog To Show the Files
lRet = Application.GetOpenFilename("PCH files (*.pch), *.*")
'Reads the file into characters
sVal = OpenTextFileToString2(lRet)
Dim tmp As Variant
    tmp = SplitMultiDelims(sVal, ",;$ ", True)   ' Place the 2nd argument with the list of delimiter you need to use
    Row = 0
    For i = LBound(tmp, 1) To UBound(tmp, 1)
        Row = Row + 1
        Col = 1
        While Not vbNewLine = ""
            ws.Cells(Row, Col) = tmp(i)  'output on the first column
            MsgBox (tmp(i))
            Col = Col + 1
        Wend
    Next i
End Sub
Function OpenTextFileToString2(ByVal strFile As String) As String
' RB Smissaert - Author
Dim hFile As Long
hFile = FreeFile
Open strFile For Input As #hFile
OpenTextFileToString2 = Input$(LOF(hFile), hFile)
Close #hFile
End Function
Function SplitMultiDelims(ByRef Text As String, ByRef DelimChars As String, _
        Optional ByVal IgnoreConsecutiveDelimiters As Boolean = False, _
        Optional ByVal Limit As Long = -1) As String()
    Dim ElemStart As Long, N As Long, M As Long, Elements As Long
    Dim lDelims As Long, lText As Long
    Dim Arr() As String

    lText = Len(Text)
    lDelims = Len(DelimChars)
    If lDelims = 0 Or lText = 0 Or Limit = 1 Then
        ReDim Arr(0 To 0)
        Arr(0) = Text
        SplitMultiDelims = Arr
        Exit Function
    End If
    ReDim Arr(0 To IIf(Limit = -1, lText - 1, Limit))

    Elements = 0: ElemStart = 1
    For N = 1 To lText
        If InStr(DelimChars, Mid(Text, N, 1)) Then
            Arr(Elements) = Mid(Text, ElemStart, N - ElemStart)
            If IgnoreConsecutiveDelimiters Then
                If Len(Arr(Elements)) > 0 Then Elements = Elements + 1
            Else
                Elements = Elements + 1
            End If
            ElemStart = N + 1
            If Elements + 1 = Limit Then Exit For
        End If
    Next N
    'Get the last token terminated by the end of the string into the array
    If ElemStart <= lText Then Arr(Elements) = Mid(Text, ElemStart)
    'Since the end of string counts as the terminating delimiter, if the last character
    'was also a delimiter, we treat the two as consecutive, and so ignore the last elemnent
    If IgnoreConsecutiveDelimiters Then If Len(Arr(Elements)) = 0 Then Elements = Elements - 1
    ReDim Preserve Arr(0 To Elements) 'Chop off unused array elements
    SplitMultiDelims = Arr
End Function

【问题讨论】:

什么是EOF(l0)?您应该能够检查行尾。尝试而不是 vbNewLine 我尝试使用“虽然不是 vbNewLine”,但仍然有错误... 这是我的完整代码: 您不能像this link 所建议的那样,使用内置的 VBA 函数将文本文件导入 Excel 吗? 【参考方案1】:

您可以使用以下代码逐行读取文件

Sub IOTest()
    Dim fnum, i As Integer, j As Integer
    Dim line    As String
    Dim lines   As Variant

    Dim regEx   As Object
    Set regEx = CreateObject("vbscript.regexp")

    With regEx
        .Pattern = "\s1"  'only one whitespace
        .Global = True      'find all occurrences
    End With

    fnum = FreeFile()
    Open ThisWorkbook.Path & "\IO_Test.txt" For Input As #fnum

    Do Until EOF(fnum)      'until End of file
        i = i + 1
        Input #fnum, line   'load row into line

        'First replace found sole whitespaces with ","
        'Then split on the ","s
        lines = Split(regEx.Replace(line, ","), ",")
        For j = LBound(lines) To UBound(lines)
            Cells(i, j + 1) = lines(j)
        Next j
    Loop
    Close #fnum
End Sub

我用字符串测试了这个

"$SUBCASE" & vbTab & "1" & vbTab & vbTab & vbTab & vbTab & "1"
"$DISP" & vbTab & "0" & vbTab & "509" & vbTab & "5" & vbTab & "1" & vbTab & "2"

只有当您有一个空格(例如空格、制表符、...)分隔数据时,它才有效。如果数据之间有多个空格,则会变得更加棘手。但是,如果您可以提供有关如何分离数据的示例,我可以看一下。

希望对您有所帮助,无论哪种方式都可以告诉我;)

【讨论】:

以上是关于在 VBA Excel 中难以找到行尾的主要内容,如果未能解决你的问题,请参考以下文章

如何使用 vba 在 Excel 2007 中找到条件格式单元格的填充颜色值?

excel2013使用vba代码提示未找到提供程序,改程序可能未正确安装怎么处理

EXCEL VBA 如何找到某一数据的行号和列号?

请教,在Excel 中使用VBA查找问题。

Excel VBA实例

excel vba数据比较?