Я сейчас пишу макрос, который сравнивает содержимое документа word с файлом текстового словаря.Выделены все совпадения, чтобы человек мог внести соответствующие изменения.Я немного новичок в макросах, поэтому я использовал нечто подобное, которое я нашел в Интернете в качестве руководства, а также мои общие навыки кодирования, но я не знаю всех методов и объектов, которые мне нужны.
У меня естьустановите его, чтобы открыть общий диалог для выбора файла слова для сравнения (файл словаря жестко запрограммирован, потому что я не хочу, чтобы люди случайно выбирали его, поскольку он потенциально может использоваться многими людьми)
Для каждой строки в файле словаря макрос использует метод hithighlight, чтобы выделить любые вхождения этого слова в файле.Я должен был поставить пробелы вокруг слова, чтобы убедиться, что были сделаны только отдельные слова, так как словарь содержал много сокращений.
Проблема в том, что мне пришлось заполнять документ пробелами в начале и конце, чтобы первыйи последние слова также проверены, я не уверен, как это сделать, хотя.Я провел некоторый поиск, и я видел несколько вещей об использовании различных выборок, но я не знаю, есть ли метод клонирования для выборок, и я уверен, что если я установлю другой выбор как равный моему, он просто скопируетадрес объекта, который сделает его бессмысленным.
у меня есть такой код:
Documents(ActiveDocument.FullName).Close SaveChanges:=wdDoNotSaveChanges
'Values for objFSO
Const ForReading = 1
Const ColourYellow = 65535
Dim doc As Document
Dim DocRange As Range
'allows us to change the document in use
Set ObjCD = CreateObject("UserAccounts.CommonDialog")
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objShell = CreateObject("WScript.Shell")
'Relevant path to the Dictionary txt file, change this to point to the dictionary list if different to this
DicFilePath = "O:\IPS\PDU\KIS\Intranet\consistency-with-styleguide-project\styleguidelist.txt"
'Set the parameters for the Common Dialog
ObjCD.Filter = "Word Documents|*.docx" 'Filter only docx files
ObjCD.FilterIndex = 3
ObjCD.InitialDir = "" 'Set the initial path for the Common Dialog to the same folder as the script
'Display the File open dialog
InitFSO = ObjCD.ShowOpen
If InitFSO = False Then
'No file was selected so Error
MsgBox ("No file was selected")
Else
'ScanFilePath = the full path and filename if the file
ScanFilePath = ObjCD.FileName
Set doc = Documents.Open(ScanFilePath) 'store the document we want to check as doc
Set objDicFile = objFSO.OpenTextFile(DicFilePath, ForReading) 'open the dictionary file
With doc
MatchFound = False 'initially have no matches found as haven't searched yet
Set DocRange = .Range 'this represents the entire document
DicWordCount = 0
DocRange.InsertAfter (Space(1))
DocRange.InsertBefore (Space(1))
'do this to pad the start and end with spaces to allow matches for the first and last word
'this is done as it's easier than having it look for start and end of file markers and still only find
'whole words
'Loop though each word in the dictionary and check if that word exists in the word doc
Do While objDicFile.AtEndOfStream <> True
'reset so EACH word in dictionary is checked for
DicWordFound = False
'Read the next word from the dictionary
DicWord = objDicFile.ReadLine
DicWord = Space(1) & DicWord & Space(1) 'add a space to both sides to find whole words only
DicWordFound = DocRange.Find.HitHighlight(DicWord, ColourYellow)
'is true if it was found at least once, else false. If any are found they are highlighted in yellow
If DicWordFound Then
MatchFound = True 'MatchFound if used to check if any match was found for any words, only false if none are found
End If
Loop
'this is done to remove the superfluous space at the end.
End With
If MatchFound Then
'If a Match is found
'Display OK message
MsgBox ("Complete: MATCH FOUND!" & Chr(13) & Chr(10) & Chr(13) & Chr(10) & "Matches are highlighted in yellow.")
Else
'If a Match is NOT found
MsgBox ("No Match")
End If
End If
если кто-то знает, как я могу удалить заполнение, которое я добавил после завершения поискаэто было бы действительно полезно.В качестве альтернативы, если кто-то может предложить более эффективный способ, он будет очень признателен.(например, я уверен, что должен быть способ проверить целые слова только при поиске, но я не знаю его, так как я новичок в макросах)
Также, если кто-то точно знает,та же функциональность реплицирована в слове 97-2003 с использованием тех же методов и объектов, дайте мне знать, поэтому я могу просто расширить его на файлы .doc без лишних слов.
Спасибо за ваше время.