在另一篇文章中,我终于可以从Word文件中选择一个表,并把它弄到Excel文件中。我在Word VBA中有以下代码。
Dim wrdTbl As Table
Dim RowCount As Long, ColCount As Long, i As Long, j As Long
'Excel Objects
Dim oXLApp As Object, oXLwb As Object, oXLws As Object
'Set your table
Set wrdTbl = ActiveDocument.Tables(InputBox("Table # to copy? There are " & ActiveDocument.Tables.Count & " tables to choose from."))
'If ActiveDocument.Tables.Count = 0 Then MsgBox "There are no tables in word document"
'Exit Sub
'Get the word table Row and Column counts
ColCount = wrdTbl.Columns.Count
RowCount = wrdTbl.Rows.Count
'Create a new Excel Application
Set oXLApp = CreateObject("Excel.Application")
'Hide Excel
oXLApp.Visible = False
'Open the relevant Excel file
Set oXLwb = oXLApp.Workbooks.Open("C:\Users\" & Environ("Username") & "\Desktop\ExcelEx.xlsx")
'Work with Sheet1. Change as applicable
Set oXLws = oXLwb.Sheets(1)
'Loop through each row of the table
For i = 1 To RowCount
'Loop through each cell of the row
For j = 1 To ColCount
'This gives you the cell contents
wrdTbl.Cell(i, j).Range.Copy
With oXLws
.Range("A1").Activate
.Cells(i, j).Select
.PasteSpecial (wdPasteText)
.Range("A1").CurrentRegion.Style = "Normal"
End With
Next
Next
'Close and save Excel file
oXLwb.Close savechanges:=True
'Cleanup (VERY IMPORTANT)
Set oXLws = Nothing
Set oXLwb = Nothing
oXLApp.Quit
Set oXLApp = Nothing
MsgBox "Done"
End Sub
我的问题是,如果我有一个合并单元格的表格,它就会抛出错误:"5941 "请求的集合成员不存在于行: "5941 "请求的集合成员不存在于该行。
wrdTbl.Cell(i, j).Range.Copy
我怎样才能让代码也复制合并单元格?
另一个问题是,当我有一个单元格有多行,因为在Excel文件中,它复制这些单元格行在Excel的不同单元格。我怎么也能解决这个问题呢,非常感谢您的解答!
你需要单独循环浏览单元格,而不是按行和列循环。例如:如果你想复制Word,那么你就需要在单元格中单独循环,而不是按行和列循环。
Dim wrdTbl As Table, c As Long
'Excel Objects
Dim oXLApp As Object, oXLwb As Object, oXLws As Object
'Set your table
With ActiveDocument
If ActiveDocument.Tables.Count = 0 Then MsgBox "There are no tables in word document"
Exit Sub
Else
Set wrdTbl = .Tables(InputBox("Table # to copy? There are " & .Tables.Count & " tables to choose from."))
End If
End With
'Create a new Excel Application
Set oXLApp = CreateObject("Excel.Application")
With oXLApp
'Hide Excel
.Visible = False
'Open the relevant Excel file
Set oXLwb = oXLApp.Workbooks.Open("C:\Users\" & Environ("Username") & "\Desktop\ExcelEx.xlsx")
End With
'Loop through each row of the table
With wrdTbl.Range
For c = 1 To .Cells.Count
With .Cells(c)
'Work with Sheet1. Change as applicable
oXLwb.Sheets(1).Cells(.RowIndex, .ColumnIndex).Value = Split(.Range.Text, vbCr)(0)
End With
Next
End With
'Close and save Excel file
oXLwb.Close True
'Cleanup (VERY IMPORTANT)
oXLApp.Quit
Set oXLwb = Nothing: Set oXLApp = Nothing
MsgBox "Done"
如果你想在Excel中复制Word表格,将其替换为:
'Loop through each row of the table
With wrdTbl.Range
For c = 1 To .Cells.Count
With .Cells(c)
'Work with Sheet1. Change as applicable
oXLwb.Sheets(1).Cells(.RowIndex, .ColumnIndex).Value = Split(.Range.Text, vbCr)(0)
End With
Next
End With
替换为:
wrdTbl.Range.Copy
With oXLwb.Sheets(1)
.Paste .Range("A1")
End With