Word deleting tabe column via vba macros gives an error

允我心安 提交于 2019-12-20 04:50:43

问题


I want to copy data from excel to the word table and then delete some columns from table. I can copy data to table, but when I delete column it gives error:

Cannot access individual columns in this collection because the table has mixed cell widths.

My code:

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

回答1:


Try to change this line:

Tbl1.Range.Paste

into the following one:

tbl1.Range.PasteAppendTable

EDIT It seems that .PasteAppendTable requires some time to be invoked. Therefore try to add this additional section:

'...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



回答2:


Sleep function might work.

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

Sub Sleep()

Sleep 1000   'Implements a 1 second delay

End Sub


来源:https://stackoverflow.com/questions/16443655/word-deleting-tabe-column-via-vba-macros-gives-an-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!