为单元格位置创建变量

时间:2012-12-31 20:41:22

标签: excel vba excel-vba

我需要为此单元格复制/粘贴的起始位置创建一个变量,因此我可以将其用作其他数据的参考点。那可能吗?我不确定语法。

wbkCS.Worksheets("Cut Sheet").Range("S4:S2000").Copy

With wbkVer.Worksheets("Cutsheets")
   .Range("A" & .Rows.Count).End(xlUp).Offset(1).PasteSpecial xlPasteValues
End With

2 个答案:

答案 0 :(得分:9)

以下是将这些范围保存为Range个对象的语法。

dim firstRange as Range, secondRange as Range

set firstRange = wbkCS.Worksheets("Cut Sheet").Range("S4:S2000")

firstRange.copy

With wbkVer.Worksheets("Cutsheets")
    set secondRange = .Range("A" & .Rows.Count).End(xlUp).Offset(1)
    secondRange.PasteSpecial xlPasteValues
End With

如果您想要其中一个范围的第一个单元格,它将是这样的:

firstRange.Cells(1,1)

答案 1 :(得分:2)

你已经有了答案,但最好的方法就是完全避免剪贴板:

Sub WithoutClipboard()

'define the two ranges variables
Dim firstRange As Range
Dim secondRange As Range

'set the range variables to specific ranges
Set firstRange = wbkCS.Worksheets("Cut Sheet").Range("S4:S2000")
With wbkVer.Worksheets("Cutsheets")
    Set secondRange = .Range("A" & .Rows.Count).End(xlUp).Offset(1)
End With

'resize the second range so it exactly the same size as the first range
With firstRange
      Set secondRange = secondRange.Resize(.Rows.Count, .Columns.Count)
End With

'move the data without having to use copy/paste
secondRange.Value = firstRange.Value

End Sub