我有一個帶有動態日志表的作業簿,可以對用戶輸入的資料執行計算。我希望將此日志表中的特定動態列復制到作業簿中的另一個表以用于繪圖目的。此副本僅用于值,主要是為了更容易運行最終宏以生成 XY 散點圖。但是,我收到一個物件錯誤,不知道為什么會這樣。預先感謝您的任何幫助。你能幫我找出完成這項任務的最佳方法嗎?這是我當前的 VBA:
Sub UpdateCharts()
Dim sourceSheet As Worksheet
Dim targetSheet As Worksheet
Dim sourcelRow As Long
Dim targetlRow As Long
Set sourceSheet = ThisWorkbook.Worksheets("Inventory Log")
Set targetSheet = ThisWorkbook.Worksheets("Tables")
sourcelRow = sourceSheet.Cells(Rows.Count, 1).End(xlUp).Offset(-1, 0).Row
targetlRow = targetSheet.Cells(Row.Count, 6).End(xlDown).Offset(1, 0).Row
sourceSheet.Cells(sourcelRow, 1).Copy
targetSheet.Cells(targetSheet, 6).PasteSpecial xlPasteValues
End Sub
uj5u.com熱心網友回復:
您的代碼中有幾個錯誤/錯別字:
- 您應該始終使用顯式參考
Row并且Rows是兩個不同的命令- 要檢索最后一行,您應該始終使用相同的功能
- 您不需要復制/粘貼值 - 您可以將它們直接寫入
例如,您可以使用此函式來檢索作業表的最后一行和 columnIndex:
Public Function getLastRow(ws As Worksheet, columnIndex As Long) As Long
With ws
getLastRow = .Cells(.Rows.Count, columnIndex).End(xlUp).Row
End With
End Function
然后你的代碼看起來像這樣
Sub UpdateCharts()
Dim sourceSheet As Worksheet
Dim targetSheet As Worksheet
Dim sourcelRow As Long
Dim targetlRow As Long
Set sourceSheet = ThisWorkbook.Worksheets("Inventory Log")
Set targetSheet = ThisWorkbook.Worksheets("Tables")
sourcelRow = getLastRow(sourceSheet, 1)
targetlRow = getLastRow(targetSheet, 6) 1 'adding 1 row to have the next empty row
targetSheet.Cells(targetlRow, 6).Value = sourceSheet.Cells(sourcelRow, 1).Value
End Sub
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/504055.html
