Word文件输出为Excel文件并排序
Word文件输出为Excel文件并排序
Private Function extractDataDictionary(docFile As String) As Boolean
Dim word As Object
Set word = Documents.Open(docFile, Visible:=False)
Dim ExcelSheet As Object
Set ExcelSheet = CreateObject("Excel.Sheet")
'设置 Application 对象使 Excel 可见
ExcelSheet.Application.Visible = True
Dim rowIdxOffset As Long
rowIdxOffset = 0
For Each Table In word.Tables
For Each Row In Table.Rows
If (1 <> Row.Index) Then
For Each Cell In Row.Cells
strLine = Cell.Range.Text
strLine = Replace(strLine, Chr(13) & Chr(7), "") 'replace cell ending symbol to null
strLine = Replace(strLine, Chr(13) & Chr(10), vbTab) 'replace cell return line to null
'write data to excel sheet
ExcelSheet.Application.Cells(Cell.RowIndex + rowIdxOffset, Cell.ColumnIndex).Value = strLine
Next
Else
End If
Next
rowIdxOffset = rowIdxOffset + Table.Rows.Count
Next
word.Close (wdDoNotSaveChanges)
ExcelSheet.SaveAs "C:\TEST2.xlsx"
'sort and clean repeat data
ExcelSheet.Application.Cells.Select
ExcelSheet.Application.Sheets(1).Sort.SortFields.Clear
ExcelSheet.Application.Sheets(1).Sort.SortFields.Add (ExcelSheet.Application.Sheets(1).Range("A2:A592"))
With ExcelSheet.Application.Sheets(1).Sort
.SetRange ExcelSheet.Application.Rows("2:592")
.Header = Excel.XlYesNoGuess.xlGuess
.MatchCase = False
.Orientation = Excel.Constants.xlTopToBottom
.SortMethod = XlSortMethod.xlPinYin
.Apply
End With
'使用应用程序对象的 Quit 方法关闭 Excel。
ExcelSheet.Application.Quit
'释放该对象变量
Set ExcelSheet = Nothing
End Function
上述为一段将word文件中的表格内容输出到excel文件,并进行排序的代码,但是排序的部分总是有问题,查了下应该是Sort方法设定的参数xlTopToBottom,xlGuess等无法识别的原因,可是我查了很久也没找到究竟如何在Word VBA中引用Excel中的Constants枚举或是XlYesNoGuess枚举
求指教,谢谢了...
[解决办法]
直接用值。
比如xlTopToBottom=6,就直接用6。
这些常量的值你应该能查到吧。
[解决办法]