[英]Copy and Paste Row and Columns(with formulas) and Paste down to the last row in VBA
[英]VBA: Identify Last row of formulas (or data) in sheet, copy that row, and then paste one row right below it
我想確定標題為“定期貸款”的表格上的最后一行公式。 然后我想復制所有這些公式並將它們粘貼到下面一行。 例如,如果公式的最后一行是第 15 行,我想復制第 15 行並將公式粘貼到第 16 行。在下面的代碼中,我在Worksheets("Term Loans").Range(Worksheets("Term Loans").Cells(lRow, 1)).EntireRow.Copy
。任何有關如何解決此問題的建議將不勝感激。 錯誤是“應用程序定義的或 object 定義的錯誤”
Dim lRow As Long
Sheets("Term Loans").Select
'Find the last non-blank cell in column A(1)
lRow = Cells(Rows.Count, 1).End(xlUp).Row
' Now Copy the range:
Worksheets("Term Loans").Range(Worksheets("Term Loans").Cells(lRow, 1)).EntireRow.Copy
' And paste to first empty row
Worksheets("Term Loans").Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).PasteSpecial xlPasteFormulas
Application.CutCopyMode = False
你的錯誤是由
Worksheets("Term Loans").Range(Worksheets("Term Loans").Cells(lRow, 1))
當您將單個參數傳遞給Range(...)
時,它將被解釋為地址字符串。 當該參數本身是一個范圍時,( Worksheets("Term Loans").Cells(lRow, 1)
在這種情況下)該范圍的值被傳遞給Range
(so ... .Cells(lRow, 1).Value
是這種情況)
因此,除非... .Cells(lRow, 1).Value
返回 A1 樣式的有效地址(或命名范圍的名稱),否則您將收到錯誤消息。
這是正確引用范圍的方法
Sub Demo
Dim lRow As Long
Dim ws As Worksheet
Set ws = Sheets("Term Loans")
'Find the last non-blank cell in column A(1)
lRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row
' Now Copy the range:
ws.Cells(lRow, 1).EntireRow.Copy
' And paste to first empty row
ws.Cells(ws.Rows.Count, 1).End(xlUp).Offset(1, 0).PasteSpecial xlPasteFormulas
Application.CutCopyMode = False
End Sub
和一個改進的版本
Sub Demo2
Dim wb as Workbook
Dim ws As Worksheet
Dim rng as Range
Set wb = Thisworkbook 'or Activeworkbook, or some other book you specify
Set ws = wb.Worksheets("Term Loans")
With ws
'Find the last non-blank cell in column A(1)
Set rng = .Cells(.Rows.Count, 1).End(xlUp).EntireRow
End With
' Now Copy the range:
rng.Copy
' And paste to first empty row
rng.Offset(1, 0).PasteSpecial xlPasteFormulas
Application.CutCopyMode = False
' To set a specific cell in the new row to a value
Dim MyVal as Long
MyVal = 42
rng.Offset(1, 0).Cells(1, 3) = MyVal
End Sub
您在將lrow
聲明為Long
之后嘗試將其引用為范圍,這就是錯誤的來源。 試試這個,我聲明了一些其他變量以使代碼更簡單。 希望這可以幫助:
Sub copypaste1rowdown()
Dim ws As Worksheet
Set ws = ActiveSheet
Dim lRow As Long
lRow = ws.Range("A3:Q3").CurrentRegion.Rows.Count
Dim lCol As Long
lCol = ws.Range("A3:Q3").CurrentRegion.Columns.Count
Dim i As Long
For i = 1 To lCol
Cells(lRow + 2, i).Copy
Cells(lRow + 2, i).Offset(1, 0).PasteSpecial xlPasteAll
Next i
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.