通过vba宏删除tabe列的Word会出错

时间:2013-05-08 14:43:31

标签: vba ms-word word-vba

我想将数据从excel复制到word表,然后从表中删除一些列。我可以将数据复制到表中,但是当我删除列时会出现错误:

  

无法访问此集合中的各个列,因为该表具有混合的单元格宽度。

我的代码:

Public Tbl1 As Table
Sub callExcel()

Dim objExcel As New Excel.Application
Dim exWb As Excel.Workbook

Set exWb = objExcel.Workbooks.Open("C:\Users\ismayilov\Desktop\test")

roomNumber = InputBox("Enter the room number to copy word:", "Room Number")
ActiveDocument.FormFields("Text1").Result = roomNumber
exWb.Sheets("Sheet1").Range("$A:$H").AutoFilter Field:=8, Criteria1:=roomNumber
Dim rVis As Range, rData As Range
exWb.Sheets("Sheet1").Range("$A1:$H600").Copy

Set Tbl1 = ActiveDocument.Tables.Add _
(Range:=Selection.Range, numRows:=1, NumColumns:=8)

Tbl1.Range.Paste
Tbl1.Columns(1).Delete

exWb.Close SaveChanges:=True
Set exWb = Nothing
Set Tbl1 = Nothing

End Sub

2 个答案:

答案 0 :(得分:3)

尝试更改此行:

Tbl1.Range.Paste

进入以下一个:

tbl1.Range.PasteAppendTable

编辑 .PasteAppendTable似乎需要一些时间来调用。因此,请尝试添加此附加部分:

'...your code

'let's wait a second before pasting (could be cut to 0.5 sec)
Dim tmpStart
tmpStart = Timer
Do
    DoEvents
Loop While (tmpStart + 1) > Timer

tbl1.Range.PasteAppendTable

'...your code

答案 1 :(得分:0)

睡眠功能可能有效。

Declare Sub Sleep Lib "kernel32" Alias "Sleep" _
   (ByVal dwMilliseconds As Long)

Sub Sleep()

Sleep 1000   'Implements a 1 second delay

End Sub