如何使用vba

时间:2019-07-29 12:57:25

标签: excel vba

Data I am trying to read from我正在尝试将文本文件中的特定数据提取到excel工作表中,我可以将数据作为一个整体导入,但只希望根据某些条件提取某些数据行。

Sub ReadText()
    Dim myFile As String

    myFile = Application.GetOpenFilename()

    Open myFile For Input As #1

    row_number = 0

    Do Until EOF(1) ' Check for end of file.
        Line Input #1, LineFromFile

        LineItems = Split(LineFromFile, ",")

        ActiveCell.Offset(row_number, 0).Value = LineItems(0)
        ActiveCell.Offset(row_number, 1).Value = LineItems(1)
        ActiveCell.Offset(row_number, 2).Value = LineItems(2)
        ActiveCell.Offset(row_number, 3).Value = LineItems(3)

        row_number = row_number + 1
    Loop

    Close #1 ' Close file.
End Sub

编辑 我要查找的条件是“ Ana_Input_Data”,“ Alarms_From_Analogue_SP”和“ Motor_Type_1_SCADA_DATA”。

1 个答案:

答案 0 :(得分:0)

也许您可以添加如下的if语句。

Sub ReadText()
    Dim myFile As String

    myFile = Application.GetOpenFilename()

    Open myFile For Input As #1

    row_number = 1

    Do Until EOF(1) ' Check for end of file.
        Line Input #1, LineFromFile

        LineItems = Split(LineFromFile, ",")

If ActiveCell.Offset(row_number, 3).Value = "Ana_Input_Data" And ActiveCell.Offset(row_number, 3).Value = "Alarms_From_Analogue_SP" And ActiveCell.Offset(row_number, 3).Value = "Motor_Type_1_SCADA_DATA" Then
        ActiveCell.Offset(row_number, 0).Value = LineItems(0)
        ActiveCell.Offset(row_number, 1).Value = LineItems(1)
        ActiveCell.Offset(row_number, 2).Value = LineItems(2)
        ActiveCell.Offset(row_number, 3).Value = LineItems(3)
    End If
        row_number = row_number + 1

    Loop

    Close #1 ' Close file.
End Sub