UPDATE:讓我們創建一個空白工作簿,並在一個新的模塊VBE然後粘貼代碼,保存爲啓用宏的工作簿(.xlsm),更改宏安全設置,重新打開這個.xlsm文件。
按Alt-F11在Excel中打開Visual Basic中
單擊插入 - >模塊
鼠標雙擊模塊1或不管它剛剛創建
粘貼在下面的代碼中
在Excel
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宏-Enabled工作簿」
在開發選項卡,單擊宏安全(我猜你會不會簽署您的宏,以便改變使這一切宏)
選擇啓用所有宏...然後單擊確定
關閉並重新打開此.XLSM然後單擊宏在開發人員選項卡,選擇SO_19150262並單擊運行:
我認爲你將不得不走VBA的方式。您的關鍵字是放在單獨的文件中,還是將它們放在工作簿中的單獨工作表上?編寫VBA時有所不同。 –