VBA代码从文本文件中提取多个括号内的多个单词

时间:2016-12-23 06:52:41

标签: excel-vba vba excel

如何从文本文件中获取输入并将方括号内的每个单词(每个括号内的简单文本)提取到Excel工作表。

例如:

text file->(嗨这是[john doe],电话号码是[12345] ......)
输出 - > john doe
        12345

2 个答案:

答案 0 :(得分:0)

如果所有字符串都相同,最简单的方法是打开记事本文档,用逗号编辑,替换和替换所有括号,然后在内容写入标题之前。例如,您的文件看起来像:

删除,命名,删除,电话 嗨,这是john doe,电话号码是12345,

然后将其保存为file.csv,在excel中打开文件,然后删除说明删除的列

答案 1 :(得分:0)

你可以使用

Option Explicit

Sub main()
    Dim fileNr As Integer
    Dim lines() As String
    Dim iLine As Long
    Dim arr As Variant

    fileNr = FreeFile '<--| get a free file index for subsequent `Open` statement
    Open "C:\Users\Luvish\Data\Test.txt" For Input As #fileNr '<--| open your file (change path and name as per your actual needs
        lines = Split(Input$(LOF(fileNr), fileNr), vbNewLine) '<-- read all lines
    Close fileNr '<--| close text file

    For iLine = 0 To UBound(lines) '<--| loop through all read lines
        If InStr(lines(iLine), "]") > 0 Then '<--| if current line has a "]" character
            arr = Split(Replace(lines(iLine), "]", "]["), "[") '<--| split current line and collect wanted data in even index elements
            MsgBox Left(arr(1), Len(arr(1)) - 1) & " " & Left(arr(3), Len(arr(3)) - 1) '<--| build your current line data
        End If
    Next
End Sub
相关问题