简体   繁体   English

Excel:使用VBA将行复制到另一个工作表中的表

[英]Excel: Copying rows to table in another sheet using VBA

I'm currently working on a spreadsheet in Excel. 我目前正在使用Excel中的电子表格。

My aim is to create a VBA that copies rows with specific criteria to the next sheet in my workbook and to a "log sheet". 我的目的是创建一个VBA,将具有特定条件的行复制到工作簿的下一个工作表和“日志工作表”中。

My VBA looks like this: 我的VBA如下所示:

Sub ImportRows()

    Dim xRg As Range
    Dim xCell As Range
    Dim I As Long
    Dim J As Long
    Dim K As Long
    I = Worksheets("Print").UsedRange.Rows.Count
    J = Worksheets("Store").UsedRange.Rows.Count
    If J = 1 Then
       If Application.WorksheetFunction.CountA(Worksheets("Store").UsedRange) = 0 Then J = 0
    End If
    Set xRg = Worksheets("Print").Range("I2:I" & I)
    On Error Resume Next
    Application.ScreenUpdating = False
    For K = 1 To xRg.Count
        If CStr(xRg(K).Value) = "Print" Then

            xRg(K).EntireRow.Copy Destination:=Worksheets("Store").Range("A" & J +1) 
            xRg(K).EntireRow.Copy Destination:=Worksheets("Log").Range("A" & J +1) 
            xRg(K).EntireRow.Delete
            If CStr(xRg(K).Value) = "Print" Then
                K = K - 1
            End If
            J = J + 1
        End If
    Next
    Application.ScreenUpdating = True
End Sub

The problem is when I am copying from Sheet1 called Print the data is in a table, but when I copy into the next sheet called "store" (or Log) - The data doesn't go into to table but appears in the first row beneath the table making it impossible to sort the data. 问题是当我从名为Print的Sheet1复制数据时,该数据位于表中,但是当我复制至称为“存储”(或日志)的下一张表时,该数据不会进入表,而是出现在第一行中在表格下方无法对数据进行排序。

Any suggestions on how to fix this? 对于如何解决这个问题,有任何的建议吗? I think, that it might have something to do with the destination range, but I'm not sure. 我认为,这可能与目标范围有关,但我不确定。


I'm also struggling with the amount of data that I'm copying - When copying from "Print" to "store" I only wish to copy cell "A:H" and not "EntireRow". 我还在为复制的数据量而苦苦挣扎-从“打印”复制到“存储”时,我只希望复制单元格“ A:H”,而不是“ EntireRow”。


I'm fairly new to Excel! 我对Excel还是很陌生! I appreciate any help! 感谢您的帮助!

Thank you! 谢谢!


I have uploaded a screenshot that shows what the "Store" looks like after I have run the macro. 我上传了一个屏幕截图,显示了运行宏后“商店”的外观。

在此处输入图片说明

http://imageshack.com/a/img922/9446/gpL9Ov.png http://imageshack.com/a/img922/9446/gpL9Ov.png

Since you have a list object table, it would be much easier. 由于您有一个列表对象表,因此会容易得多。

To copy from A:H columns of the row only, use Intersect() to crop for A:H column. 若要仅从该行的A:H列进行复制,请使用Intersect()裁剪A:H列。

Then to copy into a list object table, set the destination to a new list row : 然后要将其复制到列表对象表中,请将目标设置为新的列表行

Intersect(xRg(K).EntireRow, Range("A:H")).Copy _
    Destination:=range("Table1").ListObject.ListRows.Add.Range

The table name can be found below, which is defaulted to Table#: 表名可以在下面找到,默认为表号:

菜单

表名

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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