Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/vba/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Vba 在For循环中设置范围_Vba_Excel_Excel 2003 - Fatal编程技术网

Vba 在For循环中设置范围

Vba 在For循环中设置范围,vba,excel,excel-2003,Vba,Excel,Excel 2003,我正在尝试为循环设置范围。执行以下操作时,我的代码工作正常: For Each i in Range("A1":"A5") 'Some process code Next i For Each i in Range("A1").End(xlDown) 'Some Process Next i 但当我这样做时,我不会得到相同的结果: For Each i in Range("A1":"A5") 'Some process code Next i For Each i in

我正在尝试为循环设置范围。执行以下操作时,我的代码工作正常:

For Each i in Range("A1":"A5")
   'Some process code
Next i
For Each i in Range("A1").End(xlDown)
    'Some Process
Next i
但当我这样做时,我不会得到相同的结果:

For Each i in Range("A1":"A5")
   'Some process code
Next i
For Each i in Range("A1").End(xlDown)
    'Some Process
Next i

这两种代码不是等价的吗?我应该对第二个单元格进行哪些更改,使其与第一个单元格的执行方式相同,但不会使我硬编码代码中的范围?

您拥有的第二个单元格仅获取范围中的最后一个单元格,我相信这将是第一个示例中的A5。相反,你需要这样做

我将其结构化为一个小测试,以便您可以看到第一个选项,第二个选项,以及我希望如何执行此操作的示例

Option Explicit

Sub test()

  Dim r As Range
  Dim x As Range

  ' Make sure there is stuff in Range("A1:A5")
  Range("A1") = 1
  Range("A2") = 2
  Range("A3") = 3
  Range("A4") = 4
  Range("A5") = 5

  ' Your first option
  For Each x In Range("A1:A5")
    Debug.Print x.Address & ", " & x
  Next

  ' What you need to do to get the full range
  For Each x In Range("A1", Range("A1").End(xlDown))
    Debug.Print x.Address & ", " & x
  Next

  ' My preferred method
  Set r = Range("A1").End(xlDown)
  For Each x In Range("A1", r)
    Debug.Print x.Address & ", " & x
  Next

End Sub

最干净的方法可能是将lastRow编号存储在这样一个变量中。您可以在中为每行执行串联:

Dim cell as range
Dim lastRow As Long
lastRow = Range("A" & Rows.Count).End(xlUp).row

For Each cell In Range("A1:A" & lastRow)
请注意,使用xlUpxlDown之间存在差异

  • xlUp给出了列A中使用的最后一个单元格(因此从rows.count开始)
  • XlDown为您提供最后一个非空白单元格(您可以使用范围(“A1”)。结束(XlDown)。行

你会注意到很多人使用“A65536”而不是rows.count,但65536并不是某些版本Excel的限制,所以最好使用rows.count。

我认为第三种方法是最好的,它干净且允许更好的代码读取。谢谢