从不同 sheet 复制选区

Copying a selection from different sheet

我正在尝试在 Sheet 1 上设置宏以从 Sheet 2 复制一列数据,但列号基于 Sheet 1 上的数值.

这是我目前的情况:

bent = Cells(2, 2)                               'this variable is defined in Sheet1.
           
                        With Sheets("Sheet2")    'This information is on Sheet2.
                                 Range(.Cells(7, bent - 1), .Cells(7, bent - 1).end(xldown)).select
                                 Selection.Copy
                        End With

我收到“对象不支持此 属性 或方法”的消息。

当我 运行 使用相同的代码清除内容时,它完美地工作:

bent = Cells(2, 2) ' this cell is on sheet 1, where the macro button is located.
           
                        With Sheets("MCT") 'this selection to be cleared is on another sheet
                                    Range(.Cells(2, bent - 1), .Cells(4999, bent - 1)).ClearContents
                        End With

所以我有点困惑,为什么我对它的修改对 select Sheet2 上基于 Sheet1 上的数字的单元格不起作用并使用“ xlDown" 以选择从该起始单元格到其底部的所有信息并将其复制到剪贴板。

感谢任何帮助。

语法无效。此外,如果您说变量 bentSheet1 上,那么您应该通过在引用时包含该信息来限定它。您需要先找到该列的最后一行,然后指定范围。此外,您应该避免使用 SelectSelection.

bent = Sheets("Sheet1").Cells(2, 2) 'this variable is defined in Sheet1.
       
With Sheets("Sheet2")    'This information is on Sheet2.
    LR = .Cells(Rows.Count, bent - 1).End(xlUp).Row
    Range(.Cells(7, bent - 1), .Cells(LR, bent - 1)).Copy
End With

复制范围

  • 使用 Option Explicit 强制您声明所有变量。
  • 限定您的对象:带有相应工作簿(对象)的工作表,例如ThisWorkbook.,以及范围、单元格、行和列及其对应的工作表(对象),例如wb.Worksheets("Sheet1")..
  • 不需要select任何东西。
Option Explicit

Sub Test()
    
    Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
    
    Dim bent As Variant: bent = wb.Worksheets("Sheet1").Range("B2").Value
    If VarType(bent) <> vbDouble Then Exit Sub ' not a number
           
    With wb.Worksheets("Sheet2")
        Dim LR As Long: LR = .Cells(.Rows.Count, bent - 1).End(xlUp).Row
        If LR < 7 Then Exit Sub ' no data in column range
        .Range(.Cells(7, bent - 1), .Cells(LR, bent - 1)).Copy
    End With

End Sub