excel VBA使用Range()和ActiveCell.Offset()

时间:2017-07-25 20:52:44

标签: excel-vba vba excel

我正在使用excel VBA而我试图在循环中增加Range选择。

Sub sorter()
Dim i As Integer
Dim copyLoc As String = "E1"

For i = 0 To 5
Range(copyLoc).Select '//what type is Range() supposed to take?
Selection.Copy
copyLoc = ActiveCell.Offset(0, 6) '//what type does ActiveCell.Offset return?
Next i
End Sub

我确定问题出在ActiveCell.Offset返回的数据类型上。谁能告诉我应该用什么呢?谢天谢地!

1 个答案:

答案 0 :(得分:0)

扩展我的评论。 “范围”是对象类型。因此,您希望将变量调暗为“范围”而不是字符串:

Sub sorter()
Dim i As Integer
Dim copyLoc As Range

Set copyloc = Range("E1")

For i = 0 To 5
    'copy from copyloc and stick it in a cell offset 6 columns to the right
    copyLoc.Copy Destination:=copyLoc.Offset(0,6)     

    'Increment to the next row?
    Set copyLoc = copyLoc.Offset(1)
Next i
End Sub

我只是在猜测你想要完成什么,但无论哪种方式,我认为这会让你进入球场。如果从E1开始递增6行,您还可以使用以下内容:

Sub sorter()
    Dim rngRow as Range
    Dim copyRange as Range

    Set copyRange = Range("E1:E6")

    'Loop through each row in the range's "Rows" collection
    For each rngRow in copyRange.Rows
         'Copy the value from the "E" column to the "K" column in this row
         rngRow.Cells(1,11).value = rngRow.cells(1,5).value
    Next rngRow
End Sub

能够循环/遍历集合中的每个项目,并了解VBA中的大多数对象是集合的一部分,这非常强大。

例如,循环遍历ThisWorkbook.Worksheets集合中的所有工作表:

Dim ws as worksheet
For each ws in ThisWorkbook.Sheets
    'print the name of the worksheet to the "immediate" pane
    debug.print ws.name
Next ws

或循环遍历范围的“Cells”集合中的所有单元格:

Dim rngCell as Range
For each rngCell in Range("A1:C50").cells
    'do something to the cell
Next rngCell