首页 > 解决方案 > 如何检查由 VBA 中的制表符分隔的文本文件行中的条件?

问题描述

在 VBA 中,如何读取文本文件中的一行并检查某些值?我有一个类似于此的文本文件:

a     b     c     d     e     f     g [this line is not in the code]  
1[tab]2[tab]3[tab]4[tab]5[tab]6[tab]7
8[tab]9[tab]10[tab]11[tab]12[tab]13[tab]14
…

数字代表与不同参数相关联的值,这些参数由制表符分隔。每行对应一组新数据。所以在上面的例子中,1 和 8 是两个不同实验的相同参数(在本例中为“a”)。如果 b、c、d 和 f 等于某些值,我希望我的代码读取每一行并将整行打印到一个新的文本文档中。如果有人可以就此给我一些建议,我已经弄清楚了其余的代码。

Private Sub SingleRun_button_Click()

myFile = Application.GetOpenFilename()
Delimiter = vbTab
Dim intDialogResult As Integer, _
    strPath, strLine, arrString() As String, _
    i, j, intCurrColumn, D, B, DischMod, T As Integer, _
    fso, ofile As Object

D = Me.D_CB.Value
B = Me.B_CB.Value
DischMod = Me.DischMod_CB.Value
T = Me.T_CB.Value

Application.FileDialog(msoFileDialogOpen).AllowMultiSelect = False
Call Application.FileDialog(msoFileDialogOpen).Filters.Clear
Call Application.FileDialog(msoFileDialogOpen).Filters.Add("Text Files", "*.txt")
intDialogResult = Application.FileDialog(msoFileDialogOpen).Show
strPath = Application.FileDialog(msoFileDialogOpen).SelectedItems(1)
Set fso = CreateObject("scripting.filesystemobject")
Set ofile = fs.createtextfile(strPath)

Close #1
Open strPath For Input As #1
i = 1
While EOF(1) = False
    Line Input #1, strLine
    arrString = Split(strLine, vbTab)
    intCurrColumn = 1
    For j = LBound(arrString) To UBound(arrString)
    If arrString(j) <> vbTab Then
        'Code as described below
    End If
Next
i = i + 1
Wend
Close #1

Unload Me

End Sub

标签: excelvba

解决方案


这应该可以帮助你。只需逐行读取您的输入文件,SPLI按分隔符 (TAB) 读取,您可以随心所欲地使用它。

Private Sub ReadCSV()

    Dim str As String
    Dim arr As Variant

        Open ("your_file_path") For Input As #1
            While Not EOF(1)
                Line Input #1, str
                arr = Split(str, vbTab)

                For a = 1 To UBound(arr)
                    Debug.Print arr(a)
                Next
            Wend
        Close #2

End Sub

推荐阅读