Может ли кто-нибудь просмотреть и скорректировать скрипт с учетом заданного мной условия? Единственное изменение, которое мне нужно, — это отсортировать все таблицы, в первой строке которых есть «xyz».
«xyz» будет использоваться для обнаружения таблиц, которые мы хотим отсортировать.
Код: Выделить всё
Sub SortTableColumnAUsingExcelOrder()
Dim wdDoc As Document
Dim wdTable As Table
Dim excelApp As Object
Dim excelWorkbook As Object
Dim excelSheet As Object
Dim sortOrder() As String
Dim i As Long, j As Long
Dim cellValue As String
Dim rowNum As Long
Dim tempRow As Range
Dim lastRow As Long
Dim rowText As String
Dim rowIndex As Long
Dim newRow As Row
Dim colCount As Long
Dim fileDialog As FileDialog
Dim filePath As String
Set wdDoc = ActiveDocument
Set fileDialog = Application.FileDialog(msoFileDialogFilePicker)
With fileDialog
.Title = "Select the Excel File"
.Filters.Clear
.Filters.Add "Excel Files", "*.xls; *.xlsx; *.xlsm", 1
.AllowMultiSelect = False
If .Show = -1 Then
filePath = .SelectedItems(1)
Else
MsgBox "No file selected. Exiting.", vbExclamation
Exit Sub
End If
End With
Set excelApp = CreateObject("Excel.Application")
excelApp.Visible = False
Set excelWorkbook = excelApp.Workbooks.Open(filePath)
Set excelSheet = excelWorkbook.Sheets(2)
lastRow = excelSheet.Cells(excelSheet.Rows.Count, 1).End(-4162).Row
ReDim sortOrder(1 To lastRow)
For i = 1 To lastRow
sortOrder(i) = excelSheet.Cells(i, 1).Value
Next i
Set wdTable = wdDoc.Tables(3)
colCount = wdTable.Columns.Count
For i = 1 To lastRow
cellValue = sortOrder(i)
For rowIndex = 3 To wdTable.Rows.Count
Dim tableCellValue As String
tableCellValue = wdTable.Cell(rowIndex, 1).Range.Text
tableCellValue = Left(tableCellValue, Len(tableCellValue) - 2)
If tableCellValue = cellValue Then
Set tempRow = wdTable.Rows(rowIndex).Range
rowText = ""
For j = 1 To colCount
rowText = rowText & wdTable.Cell(rowIndex, j).Range.Text & vbTab
Next j
rowText = Left(rowText, Len(rowText) - 1)
wdTable.Rows(rowIndex).Delete
Set newRow = wdTable.Rows.Add
Dim rowData() As String
rowData = Split(rowText, vbTab)
For j = 1 To colCount
newRow.Cells(j).Range.Text = rowData(j - 1)
Next j
If i = 1 Then
newRow.Select
Selection.MoveUp Unit:=wdLine, Count:=1
Else
For j = 1 To i - 1
newRow.Select
Selection.MoveUp Unit:=wdLine, Count:=1
Next j
End If
Exit For
End If
Next rowIndex
Next i
Dim tableCell As Cell
For Each tableCell In wdTable.Range.Cells
tableCell.Range.Text = Replace(tableCell.Range.Text, vbCr, "")
Next tableCell
excelWorkbook.Close SaveChanges:=False
excelApp.Quit
Set excelApp = Nothing
Set excelWorkbook = Nothing
Set excelSheet = Nothing
Set wdTable = Nothing
Set wdDoc = Nothing
MsgBox "Sorting and cleanup completed!", vbInformation
End SubПодробнее здесь: https://stackoverflow.com/questions/792 ... -first-row
Мобильная версия