我正在使用此VBA脚本将Word文档中的所有表插入单独的Excel工作表中。由于这些表均未命名,因此我想用在该表上找到的页码标记工作表。
错误是它不知道变量wdActiveEndPageNumber是什么。 如果我将tableNo更改为PageNo,它也不会重命名工作表。它仅使用默认的Sheet1,Sheet2,Sheet3等。
每张纸最好的名字是,如果可能的话,在表格所在的每个页面的顶部使用“ Header 3”值。
这是我的代码:
Option Explicit
Sub ImportWordTable()
Dim wdDoc As Object
Dim wdFileName As Variant
Dim tableNo As Integer 'table number in Word
Dim iRow As Long 'row index in Excel
Dim iCol As Integer 'column index in Excel
Dim resultRow As Long
Dim tableStart As Integer
Dim tableTot As Integer
Dim sheet_i As Worksheet
Dim PageNo As Integer
On Error Resume Next
ActiveSheet.Range("A:AZ").ClearContents
wdFileName = Application.GetOpenFilename("Word files (*.docx),*.docx", , _
"Browse for file containing table to be imported")
If wdFileName = False Then Exit Sub
Set wdDoc = GetObject(wdFileName) 'open Word file
With wdDoc
tableNo = wdDoc.Tables.Count
tableTot = wdDoc.Tables.Count
If tableNo = 0 Then
MsgBox "This document contains no tables", _
vbExclamation, "Import Word Table"
ElseIf tableNo > 1 Then
tableNo = InputBox("This Word document contains " & tableNo & " tables." & vbCrLf & _
"Enter the table to start from", "Import Word Table", "1")
End If
For tableStart = tableNo To tableTot
resultRow = 1
With .Tables(tableStart)
PageNo = .Range.Information(wdActiveEndPageNumber)
Set sheet_i = Sheets.Add(after:=Sheets(Worksheets.Count)).Name = "Page_No_" & CStr(PageNo)
sheet_i.Activate
'copy cell contents from Word table cells to Excel cells
For iRow = 1 To .Rows.Count
For iCol = 1 To .Columns.Count
Cells(resultRow, iCol) = WorksheetFunction.Clean(.cell(iRow, iCol).Range.Text)
Next iCol
resultRow = resultRow + 1
Next iRow
End With
Next tableStart
End With
End Sub
谢谢
答案 0 :(得分:1)
Set sheet_i = Sheets.Add(after:=Sheets(Worksheets.Count)).Name = "Page_No_" & CStr(PageNo)
Name
属性不会返回工作表,因此您需要分两个步骤进行操作:
With ThisWorkbook
Set sheet_i = .Sheets.Add(after:=.Sheets(.Worksheets.Count))
sheet_i.Name = "Page_No_" & CStr(PageNo)
End With