我想创建一个VBA代码,它将从ListObject中选择前10行,然后将它们粘贴到另一个ListObject中。将行集合复制到新工作表后,将对其进行处理,然后将选择并处理接下来的10行,依此类推。
我可以使用标准VBA函数实现这一点,但我想使用ListObject实现这一点,即
Sub PopulateSectionOfData()
Dim loInput As ListObject
Dim loOutput As ListObject
Dim intNumOfColumns As Integer
Dim rngToCopy As Range
Dim intRowsInFile As Integer
' Create the inout and output ListObjects
Set loInput = Worksheets(WS_INPUT).ListObjects(LO_INPUT)
Set loOutput = Worksheets(WS_OUTPUT).ListObjects(LO_OUTPUT)
' Delete all the current rows from the output table
Worksheets(WS_OUTPUT).ListObjects(LO_OUTPUT).DataBodyRange.Delete
' Set variables
intNumOfColumns = loInput.ListColumns.Count
WorkbookCounter = 1
intRowsInFile = 10 ' Select 10 records at a time
' Get 10 records at a time from the input file
For i = 1 To loInput.DataBodyRange.Rows.Count Step intRowsInFile - 1
'???? - This is the area that i am unsure on
Set rngToCopy = loInput.DataBodyRange(p, 1)
rngToCopy.Copy loOutput
'????
' TODO - Add further processing here
Next i
' Clear used objects
Set loInput = Nothing
Set loOutput = Nothing
End Sub
因为我想使用ListObjects
,所以对此问题的任何帮助都会非常感激提前谢谢
答案 0 :(得分:1)
DataBodyRange
指的是表中实际的行和列范围。如果表中没有行(这是执行DataBodyRange.Delete
后的条件),则需要先向表中添加一行;然后,您可以将数据复制并粘贴到该行中,并使用Excel扩展相应的表
您的for
循环可以更新为如下所示:
For i = 1 To loInput.DataBodyRange.Rows.Count Step intRowsInFile - 1
' First add a blank row to the table
loOutput.ListRows.Add
' Check that 10 rows are available in the input table
' (Done to avoid adding blank rows to the output table)
If i + 9 > loInput.DataBodyRange.Rows.Count Then
loInput.DataBodyRange.Rows(i & ":" & loInput.DataBodyRange.Rows.Count) _
.Copy loOutput.DataBodyRange.Rows(i)
Else
loInput.DataBodyRange.Rows(i & ":" & i + 9).Copy loOutput
End If
Next i
答案 1 :(得分:0)
Remember that "DataBodyRange" returns a Range. So do this:
'copies entire line 1 from "loInput" to "loOutput" on line 2
loOutput.DataBodyRange.Rows(2) = loInput.DataBodyRange.Rows(1)
In addition, just make a FOR to process the rest