excel 试图使用按钮从另一个工作表复制单元格,未知错误[重复]

q5lcpyga  于 2023-03-09  发布在  其他
关注(0)|答案(1)|浏览(130)

此问题在此处已有答案

Excel VBA, getting range from an inactive sheet(3个答案)
9天前关闭。
运行时间错误1004
调试器将显示如下所示的最后一行作为错误

Sub Store_New_Food_Record()

Dim nextEmptyFoodRow As Range
Set nextEmptyFoodRow = Worksheets("Calculator").Cells(Rows.Count, 8).End(xlUp).Offset(1)

MsgBox nextEmptyFoodRow.Row

Worksheets("Details").Range("E12:G12").Copy Destination:=Worksheets("Calculator").Range(Cells(8, nextEmptyFoodRow.Row), Cells(10, nextEmptyFoodRow.Row))

End Sub

任何帮助将是伟大的。让我知道,如果你需要更多的信息,我会很乐意提供它

lymnna71

lymnna711#

复制单行范围

  • 限定所有对象:Workbook - Worksheet - Range .
  • 使用变量来避免长的不可读的行。
  • 注意不要混淆行和列:

单个细胞的.Cells(RowNum, ColStr).Range(ColStr & RowNum)

Sub StoreNewFoodRecord()
    
    Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
    
    Dim sws As Worksheet: Set sws = wb.Sheets("Details")
    Dim srg As Range: Set srg = sws.Range("E12:G12") ' single row
    
    Dim dws As Worksheet: Set dws = wb.Sheets("Calculator")
    Dim dfCell As Range
    Set dfCell = dws.Cells(dws.Rows.Count, "H").End(xlUp).Offset(1)
    Dim drg As Range: Set drg = dfCell.Resize(, srg.Columns.Count) ' single row

    ' Either copy only values (most efficient)...        
    drg.Value = srg.Value ' same sized ranges are necessary
    ' ... or copy values, formulas, and formats:
    'srg.Copy dfCell ' you don't need the range, the first cell is enough

End Sub

相关问题