更新:让我们在 VBE 中创建一个空白工作簿和一个新模块,然后粘贴代码,保存为启用宏的工作簿 (.xlsm),更改宏安全设置,重新打开这个 .xlsm 文件。
在 Excel 中按 Alt-F11 打开 Visual Basic
单击插入-> 模块
双击 Module1 或它刚刚创建的任何内容
粘贴下面的代码
Const ForReading = 1
' Change these two below to match your file path
Const KeyWordsFile = "C:\Test\keywordslist.txt"
Const PhrasesFile = "C:\Test\phrases.xlsx"
Sub SO_19150262()
Dim aKeywords As Variant, oWB As Workbook, oWS As Worksheet
Dim R As Long, i As Long, bDelete As Boolean, sTmp As String
Application.ScreenUpdating = False
' Read the Keywords file into aKeywords (array)
aKeywords = GetKeywords(KeyWordsFile)
Set oWB = Workbooks.Open(Filename:=PhrasesFile, ReadOnly:=False)
Set oWS = oWB.Worksheets("Sheet1") ' Change this to match yours
' Start comparing from bottom of used data
For R = oWS.UsedRange.Cells.SpecialCells(xlLastCell).Row To 1 Step -1
bDelete = True
sTmp = "Deleting Row " & R
For i = 0 To UBound(aKeywords)
If Len(aKeywords(i)) > 0 Then
Application.StatusBar = "Checking Row " & R & " for keyword """ & aKeywords(i) & """..."
If InStr(1, oWS.Cells(R, 1).Value, aKeywords(i), vbTextCompare) > 0 Then
sTmp = "Keeping Row " & R & ", Keyword(" & i & "):""" & aKeywords(i) & """"
bDelete = False
Exit For
End If
End If
Next
Debug.Print sTmp
If bDelete Then oWS.Rows(R).Delete
Next
oWB.Save
Set oWS = Nothing
Set oWB = Nothing
Application.StatusBar = False
Application.ScreenUpdating = True
End Sub
Private Function GetKeywords(sKeyFile As String) As Variant
Dim aKeys As Variant, oFSO As Variant, oFile As Variant
Set oFSO = CreateObject("Scripting.FileSystemObject")
Set oFile = oFSO.OpenTextFile(KeyWordsFile, ForReading)
If (oFile.AtEndOfStream) Then
aKeys = Array()
Else
aKeys = Split(oFile.ReadAll, vbCrLf) ' Might need to change to vbCr or vbLf if unix text file
End If
Set oFile = Nothing
Set oFSO = Nothing
GetKeywords = aKeys
End Function
然后在 Excel 中,另存为 ->“启用 Excel 宏的工作簿”
在“开发人员”选项卡中,单击“宏安全性”(我猜您不会对宏进行签名,因此请更改以为此启用所有宏)
选择启用所有宏...然后单击确定
关闭并重新打开此 .xlsm 并单击开发人员选项卡中的宏,选择 SO_19150262 并单击运行: