如何保持选定的单词形式excel,并删除其余的

时间:2014-06-08 15:33:00

标签: excel vba excel-vba

我需要在Excel中处理14K行数据 我有一个需要保留的单词列表,需要删除其余的单词。由于数据量很大,很难一个一个地找到并替换这个词。我对将单词列表放入另一个excel文件并加载它以检查每列数据文件(与excel相同)有所了解。 vba是正确的方法还是可以使用Excel开箱即可解决?

1 个答案:

答案 0 :(得分:1)

这应该可以帮到你!

Sub CutWords() 'Cuts specific strings out from a specified sheet.

'---Variables---
Dim pos As Integer
Dim val As String
Dim word As String
Dim source As Worksheet
Dim target As Worksheet
Dim list As Worksheet
Dim startRow As Integer
Dim columns As Integer
Dim i As Long
Dim j As Long
Dim k As Long
Dim l As Long


'---Customize---
Set source = ThisWorkbook.Sheets(1) 'This sheet contains the data
Set target = ThisWorkbook.Sheets(2) 'Trimmed data will end up here
Set list = ThisWorkbook.Sheets(3)   'List of words to look for
startRow = 2                        'The first row to be trimmed in data
columns = 2                         'The number of columns to be trimmed in data


'---Logic---
Application.ScreenUpdating = False 'Saves us a bit of time
target.Cells.ClearContents 'Clearing the target sheet

i = startRow 'i will act as the "row counter" for our source sheet
l = 1 'l will act as the "row counter" for our target sheet

Do While i <= source.Range("A" & source.Rows.Count).End(xlUp).Row 'Looping until
'we hit the last row with data in "A" column.
    j = 1 'j will act as the "column counter" for our source sheet

    Do While j <= columns 'Checking all columns
        k = 1 'k will act as the "row counter" for our word list sheet

        Do While k <= list.Range("A" & list.Rows.Count).End(xlUp).Row 'Looping
        'until we hit the last row with data in "A" column - these are the words
            word = list.Range("A" & k).Value 'Get the word.
            val = source.Cells(i, j).Value 'Get the value to check.
            pos = InStr(val, word) 'Check for match, 0 = no match

            If pos > 0 Then 'Match found
                target.Cells(l, j).Value = val 'The values will be in the same
                'position as they were in the source (minus the ignored rows).

                'It should be quite simple to remove the empty space if needed.

            End If
            k = k + 1 'Next word

        Loop
        j = j + 1 'Next column

    Loop
    l = l + 1 'Next target row
    i = i + 1 'Next source row

Loop
Application.ScreenUpdating = True 'Make sure to restore the value

End Sub

将代码插入到新的代码模块中,应该可以随时使用,但我承认我没有做太多的测试。当然不是最快或最狂热的方法 - 而是一个简单的方法。

编辑:即使部分匹配也会被视为匹配。单词列表中的单词可以是&#34; Hello&#34;还有一个像&#34; Hello World!&#34;仍然会被认为是一场比赛。如果您只想要完全匹配,则需要直接比较字符串,而不是使用InStr

If val = word Then 'Match found

默认情况下,第一张工作表应包含您的数据,从列&#34; A&#34;开始。它可能有标题。运行宏后,第二个工作表将位于剪切列表的位置。第三张表格将包含您要剪切的单词列表。单词必须在#34; A&#34;。

列中

HTH