我有一个Excel宏,它会打开一个模板文件,并在完成所有操作后以不同的名称保存它。
我的VBA将一些数据从数据库加载(Sub Loading)到INPUT表。还有另一张表,它使用hlookup table5在INPUT表中查找行并进行一些计算。
我需要扩展此Table5并且具有与INPUT表中相同的行数,但它不起作用。你知道我怎么能实现这个目标吗?
StrSQL = "select * from mytable"
Set targetSh = owb.Sheets("INPUT")
Call Loading(targetSh, StrSQL)
Last = targetSh.Cells(Rows.count, "A").End(xlUp).Row
ActiveSheet.Range("Table5").Offset(14, 0).EntireRow.Insert Shift:=xlDown
答案 0 :(得分:0)
这将确保您已插入足够的行,表格总共为20:
Sub TestMe()
Dim listObj As ListObject
Set listObj = Worksheets(1).ListObjects("Table5")
With listObj
.Resize listObj.Range.Resize(20)
End With
End Sub
如果要将20
行插入到表已有的行中,则首先应将行保存到变量rowsTotal
。然后,插入的行应该等于rowsTotal+20
:
Option Explicit
Sub TestMe()
Dim listObj As ListObject
Dim rowsTotal As Long
Set listObj = Worksheets(1).ListObjects("Table5")
rowsTotal = listObj.Range.Rows.Count
With listObj
.Resize listObj.Range.Resize(rowsTotal + 20)
End With
End Sub
关于公式的插入,你不应该担心。 Excel会在每个新插入的行上自动写入上一行的公式。
答案 1 :(得分:0)
我用这个解决了它:
Sub RowsAction(ByRef targetSh As Worksheet, resizeSh As Worksheet, tablename
As String)
Dim i, iLastRow As Integer, oLastRow As ListRow, srcRow As Range
Last = targetSh.Range("A1", targetSh.Cells(Rows.count, "A").End(xlUp)).count - 2
For i = 1 To Last
Set srcRow = resizeSh.ListObjects(tablename).ListRows(i).Range
Set oLastRow = resizeSh.ListObjects(tablename).ListRows.Add
srcRow.Copy
oLastRow.Range.PasteSpecial
Application.CutCopyMode = False
Next
End Sub