2017-10-06 141 views
0

我有一個Excel加載項,我開發了一個電子數據交換文件並將這些文件中的特定字段導入到Excel中。某些文件包含無法處理的數據類型。我目前的工作流程是搜索這些文件並將其刪除。但是,某些文件包含應該處理的數據。我正在尋找解決方案來遍歷每個文件,搜索特定的數據類型,並從文本文件中刪除整個部分。Excel VBA:通過文本文件循環刪除文件中的字符串

數據舉例:

2FRM的Hello World! 5DEL錯誤數據類型6OTH其他數據2FRM插入我5FOR有效數據類型

在此示例中,2FRM將作爲節的開始。我想找到5DEL組,然後刪除它所包含的整個字符串/部分。這意味着從2FRM直到下一個2FRM。

數據實例修復後:

2FRM插入我5因爲有效的數據類型

我如何能做到這一點任何想法?

+0

到目前爲止,您對此次嘗試有哪些代碼?看看使用'Instr'和'Mid'只是爲了初學者。 –

回答

0

我會推薦使用InStr函數。我用這種方法取得了巨大的成功。

Public Function FileImport() 

    Dim searchStart As String, searchEnd As String, fullString As String, stringEnd As Long, startLoc As Long, endLoc As Long 

    searchStart = "5DEL" 
    searchEnd = "2FRM" 
    'File open/loop code goes somewhere and fullString is set to the data contained within. I'm manually setting this as an example below: 

    fullString = "2FRM Hello World! 5DEL Bad Datatype 6OTH Other Data 2FRM Insert Me 5FOR Valid Datatype" 

    stringEnd = Len(fullString) 

    If stringEnd > 0 Then 'Skip the section if the string blank. 
     Do 
      startLoc = InStr(1, fullString, searchStart, vbTextCompare) 'Find the piece of text we are looking for. 
      If startLoc > 0 Then 'We have found the starting location of 5DEL in the string. 
       endLoc = InStr(startLoc, fullString, searchEnd, vbTextCompare) 'Find end of the bad string, starting from the starting location. 
       If endLoc > 0 Then 'A starting and ending location were found. 
        fullString = Left(fullString, startLoc - 1) & Mid(fullString, endLoc, Len(fullString)) 
       Else 'No ending location was found, thus we only need the left part of the string. 
        fullString = Left(fullString, startLoc - 1) 
        Exit Do 
       End If 
      Else 
       Exit Do 'The bad string was not found, exit. 
      End If 
      DoEvents 'Just so that the application does not become non-responsive. Can be removed. 
     Loop 
    End If 

    Debug.Print fullString 
    'Output is 2FRM Hello World! 2FRM Insert Me 5FOR Valid Datatype 

    'File open/loop code ends. 

End Function 
0

如果你只是需要一個Excel公式,你可以使用

=RIGHT(A1,LEN(A1)-FIND("2FRM",A1,5)+1) 

假定數據「2FRM的Hello World!5DEL壞數據類型6OTH其他數據2FRM插入我5因爲有效的數據類型」是在單元格A1

還是在VBA

Public Function CleanData(sData As String) As String 
Dim sFind As String, iLen As Integer 

    sFind = "2FRM" 
    iLen = Len(sFind) 
    If Left(sData, iLen) = sFind Then CleanData = Right(sData, Len(sData) - InStr(iLen + 1, sData, sFind) + 1) 

End Function 
0

使用INSTR找到第一個5DEL。然後使用Instr查找後面的第一個2FRM,並使用InStrRev查找前面的2FRM。

f = "2FRM KeepMe1 4DEL KeepMe2 2FRM dontKeepMe3 5DEL dontKeepMe4 2FRM dontKeepMe5 5DEL dontKeepMe6 2FRM KeepMe7 4DEL KeepMe8 " 
a2 = InStr(f, "5DEL") 
Do While a2 <> 0 
a1 = InStrRev(f, "2FRM", a2) 
a3 = InStr(a2, f, "2FRM") 
If a3 = 0 Then a3 = Len(f) + 1 
f = Mid(f, 1, a1 - 1) & Mid(f, a3) 
a2 = InStr(f, "5DEL") 
Loop