[英]Select a range, avoiding hidden cells, using ActiveCell.Offset()
[英]excel VBA using Range() and ActiveCell.Offset()
我正在使用Excel VBA,并且试图在循环中增加范围选择。
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返回的数据类型上。 谁能告诉我应该使用什么? 谢谢!
在上面扩展我的评论。 “范围”是一种对象类型。 因此,您想将变量变暗为“ Range”而不是字符串:
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
或遍历范围的“单元”集合中的所有单元:
Dim rngCell as Range
For each rngCell in Range("A1:C50").cells
'do something to the cell
Next rngCell
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.