excel vba:查找文本文件的第二行并更新电子表格,其中cell = value并使用文本文件中的值更新同一行中的其他单元格

时间:2015-05-29 08:01:06

标签: excel vba excel-vba text-files

我有以下代码,我正在努力改进。 首先,它扫描文本文件并从文件中的第二个文本行获取文本。

我想要更改它,以便它只扫描文件夹中所有.txt文件的第二行而不是一个文件,并检查每个文本文件是否第二行文本="批准"或"拒绝"。

然后,如果它="批准",我希望我在S列中的单元格在文本文件中第一个文本行与C列中的参考编号匹配的行中更新此值。 / p>

一个例子:

Text File - NS123.txt:
NS123
Approve

在我的电子表格中:

第1行:

C            F                R                           S
NS123     Cell Value       Cell Value       Update Cell with Approve/Reject

第2行:

C            F                R                           S
NS564     Cell Value       Cell Value       Wont be updated because doesn't match value in column c

请有人告诉我如何做到这一点?感谢

代码:

Public Sub test()
    Dim fn As Integer
    fn = FreeFile
    Open "Z:\NS\Approval\NS32D1QR.txt" For Input As fn

    Dim wholeFile As String
    wholeFile = Input(LOF(fn), #fn)

    Close #fn

    Dim splitArray
    splitArray = Split(wholeFile, vbCrLf)

    Dim lineNum As Integer
    lineNum = 2


    Dim i As Integer, intValueToFind As Integer
    intValueToFind = NS32D1QR
    For i = 1 To 500    ' Revise the 500 to include all of your values
        If Cells(i, 1).Value = intValueToFind And splitArray(lineNum - 1) = "Approve" Then
    Range("S" & ActiveCell.Row).Value = "Approve"
    End If

    Next i



End Sub

1 个答案:

答案 0 :(得分:0)

以下是指南:

扫描文件夹中的所有文本文件:

使用Dir功能

directory = Dir("*.txt")
Do While directory <> ""
  'Your code
  directory = Dir()
Loop

检查第二行:

与我的Tutorial on how to read from files in VBA

一样
fileNo = FreeFile
Open fileName For Input As #fileNo
Line Input #fileNo, textRow: Line Input #fileNo, textRow 
'Now textRow contains the second row of the file
Close #fileNo