0

我有许多文本文件要导入到 excel 中。我希望我的宏打开一个文件,当它遇到“价格”这个词时,它会将该行放在 A1 中。之后的每一行都将放置在 b1、c1 等中。当再次找到单词 PRICE 时,将开始一个新行并将该行放置在 a2 中,然后是 b2、c2 等中的行。我想我应该使用 Instr。下面的代码似乎将带有 PRiCE 的行放在新行中,但文本文件中的以下行似乎没有跟随。我想我只需要在 DO 中进行细微调整,而不是循环。任何帮助都会很棒!

x = 1 'to offset rows for each file

' Loop thru all files in the folder
For Each file In folder.Files

' set the starting point to write the data to
Set cl = ActiveSheet.Cells(x, 1)

' Open the file
Set FileText = file.OpenAsTextStream(ForReading)



i = 0 'to offset columsn for each line
' Read the file one line at a time
Do While Not FileText.AtEndOfStream

    TextLine = FileText.ReadLine 'read line

    If InStr(TextLine, "FINEX") > 0 Then 'find text

    x = x + 1
    Set cl = ActiveSheet.Cells(x, 1)
    cl.Offset(, 0).Value = TextLine
    'i = i + 1
    'cl.Value = TextLine

    'MsgBox ("yes")
    Else
     cl.Offset(, i).Value = TextLine 'fill cell
    i = i + 1
    End If
Loop

' Clean up
FileText.Close

x = x + 1

Next file
4

2 回答 2

1

由于我昨天帮助您编写了这段代码并且碰巧看到了,所以我想我会采取行动:

看看下面的代码是否适合你。如果没有,请告诉我,我可以对其进行调整:

    x = 1 'to offset rows for each file and at price

' Loop thru all files in the folder
For Each file In folder.Files

    ' set the starting point to write the data to
    Set cl = ActiveSheet.Cells(x, 1)

    ' Open the file
    Set FileText = file.OpenAsTextStream(ForReading)

    i = 1 'to offset columsn for each line

    ' Read the file one line at a time
    Do While Not FileText.AtEndOfStream

        TextLine = FileText.ReadLine 'read line

        If InStr(TextLine, "PRICE") > 0 Then 'find text

            cl.Offset(x - 1, 0).Value = TextLine
            x = x + 1

        Else

            cl.Offset(x - 1, i).Value = TextLine 'fill cell
            i = i + 1

        End If

    Loop

Next
于 2012-10-26T16:24:26.023 回答
0

我的 2 美分

Dim f As File, fileStream As TextStream, filetext As String, NewLines() As String, Offset As Long

Offset = 1

Set fileStream = f.OpenAsTextStream(ForReading)
filetext = fileStream.ReadAll

filetext = Replace(filetext, vbCrLf, " ") 'make everything one line
NewLines = Split(filetext, "PRICE") 'make a new set of lines based on PRICE

For l = LBound(NewLines) To UBound(NewLines)

    ActiveSheet.Cells(l + Offset, 1) = NewLines(l)
Next l

fileStream.Close
Set fileStream = Nothing
于 2012-10-29T16:02:58.447 回答