Столбец 1 таблиц Excel и Word имеет одинаковые совпадения, и я хочу отсортировать таблицы Word по порядку в Excel.
Я постоянно получаю проблемы, проблема, которую я сейчас получаю: «Не найдено совпадений для текста Word: ' Word'.
Таблицы, над которыми я работаю with имеет первую строку как «Требуемые детали».
Пожалуйста, просмотрите код. Если у кого-нибудь есть решение для этой проблемы, я буду очень признателен.
Код: Выделить всё
Sub RearrangeWordTableRowsBasedOnExcel()
Dim wordTable As Table
Dim wordRow As Row
Dim wordText As String
Dim excelApp As Object
Dim excelWorkbook As Object
Dim excelSheet As Object
Dim excelRange As Object
Dim matchRow As Long
Dim wordDoc As Document
Dim userExcelFile As Variant
Dim sheetName As String
Dim sheetExists As Boolean
Dim targetRow As Long
Dim excelText As String
Dim foundTable As Boolean
foundTable = False
' Create an instance of Excel Application
Set excelApp = CreateObject("Excel.Application")
' Ask user to select the Excel file
userExcelFile = excelApp.GetOpenFilename("Excel Files (*.xls; *.xlsx), *.xls; *.xlsx", , "Select Excel File")
' Exit if no file selected
If userExcelFile = False Then
MsgBox "No file selected. Exiting."
Exit Sub
End If
' Open the selected Excel file
Set excelWorkbook = excelApp.Workbooks.Open(userExcelFile)
' Check if "Sheet2" exists in the workbook
sheetName = "Sheet2" ' Modify this name if necessary
On Error Resume Next
Set excelSheet = excelWorkbook.Sheets(sheetName)
On Error GoTo 0
If excelSheet Is Nothing Then
MsgBox "Sheet2 does not exist in the selected Excel file. Exiting."
excelWorkbook.Close False
excelApp.Quit
Set excelSheet = Nothing
Set excelWorkbook = Nothing
Set excelApp = Nothing
Exit Sub
End If
' Set Word document
Set wordDoc = ActiveDocument
' Loop through the tables in the Word document
For Each wordTable In wordDoc.Tables
' Check if the first cell in the first row contains "Parts Required"
If wordTable.cell(1, 1).Range.text Like "*Parts Required*" Then
' Found the correct table
foundTable = True
Exit For
End If
Next wordTable
' If no table with "Parts Required" is found, exit
If Not foundTable Then
MsgBox "No table with 'Parts Required' found in the Word document. Exiting."
Exit Sub
End If
' Loop through the rows in the found Word table starting from row 3 (index 3)
For Each wordRow In wordTable.Rows
If wordRow.Index >= 3 Then ' Start from row 3
wordText = wordRow.Cells(1).Range.text
wordText = Left(wordText, Len(wordText) - 2) ' Remove end of cell markers (Chr(13) and Chr(7))
wordText = CleanText(wordText) ' Clean Word text
' Debugging: Show Word text details and character codes
Debug.Print "Word Text (Before Clean): '" & wordRow.Cells(1).Range.text & "'"
Debug.Print "Word Text (After Clean): '" & wordText & "'"
Debug.Print "Word Text (Character Codes): " & GetCharacterCodes(wordText)
' Skip if Word row is empty
If Len(wordText) = 0 Then
Debug.Print "Skipping empty Word row."
GoTo SkipRow
End If
' Find the match in Excel (Column 1)
On Error Resume Next ' Ignore errors temporarily
Set excelRange = excelSheet.Range("A:A").Find(wordText, , xlValues, xlWhole)
On Error GoTo 0 ' Turn off error ignoring
' Debugging: Show Excel value being compared
If Not excelRange Is Nothing Then
Debug.Print "Excel Row (" & excelRange.Row & "): " & excelRange.Value
' Clean the Excel text
excelText = CleanText(excelRange.Value)
' Debugging: Show cleaned Excel text and character codes
Debug.Print "Excel Text (Cleaned): '" & excelText & "'"
Debug.Print "Excel Text (Character Codes): " & GetCharacterCodes(excelText)
' Compare Word and Excel texts (strict and fuzzy)
If StrComp(LCase(wordText), LCase(excelText), vbTextCompare) = 0 Then ' Case insensitive comparison
MsgBox "Exact Match found for '" & wordText & "' in Excel at row " & excelRange.Row & " with text: '" & excelText & "'"
' Calculate the target row in Word (Excel's row number minus 1)
targetRow = excelRange.Row
' Ensure the target row is within the bounds of the Word table
If targetRow
Подробнее здесь: [url]https://stackoverflow.com/questions/79234686/sorting-tables-in-word-based-on-order-set-in-excel-sheet-2[/url]