简体   繁体   中英

VBA: Copy last row from table cause error

I have two tables. First is a list of rows where user needs to put comment in proper column. Second is database.

If user inserts anything to comment column then that row is copied to another sheet (database).

My code works good until user inserts comment in last row user table. Then he gets error message: "Method ShowAllData of object '_Worksheet' failed.

In fact row is copied to another sheet but the table in another sheet increases its range to hundred thousands of empty lines.

Below you can see my code. Please, advise me what can I fix here.

Dim ws1 As Worksheet
Dim ws2 As Worksheet

Set ws1 = Worksheets("Comments_database")
Set ws2 = Worksheets("PO'sDailyMonitor")

Application.ScreenUpdating = False

Worksheets("PO'sDailyMonitor").Range("P9").AutoFilter Field:=16, Criteria1:="<>"
ws2.Range("A10:Q10", Selection.End(xlDown)).SpecialCells(xlCellTypeVisible).Copy
ws1.Range("A" & Rows.Count).End(xlUp).Offset(1, 0).PasteSpecial xlPasteValues

Application.CutCopyMode = False

ws2.ShowAllData
ws2.Range("P10:P10000").ClearContents

Application.ScreenUpdating = True

MsgBox ("Database updated")

I solved it.

Just replaced this:

ws2.Range("A10:Q10", Selection.End(xlDown)).SpecialCells(xlCellTypeVisible).Copy

with:

ws2.ListObjects("PO_Query4").ListColumns(1).DataBodyRange.Resize(, 17).Select

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM