相关疑难解决方法(0)

为什么 For Each over Range.Columns(1) 不迭代单元格?

如果范围是由地址指定的,我可以迭代一系列单元格以分别对每个单元格进行操作:

Dim cell as Range
For Each cell In Range("A1:A10")
  debug.print cell.Address
Next cell
Run Code Online (Sandbox Code Playgroud)

产生预期的输出:

$A$1
$A$2
... etc
Run Code Online (Sandbox Code Playgroud)

但是,当我从范围集合中指定一列时Columns,迭代仅对整个列运行一次:

For Each cell In UsedRange.Columns(1)
    Debug.Print cell.Address
Next cell
Run Code Online (Sandbox Code Playgroud)

仅产生一个输出,包含整列:

$A$1:$A$20
Run Code Online (Sandbox Code Playgroud)

不是UsedRange.Columns(1)一个Range物体吗?如果不是的话,那是什么??

我已经阅读了关于行/列作为范围的讨论以及Range vs Range.Cells 的讨论,但我仍然可以弄清楚如何迭代UsedRange.Columns(1).

excel vba

3
推荐指数
1
解决办法
375
查看次数

在VBA中,Rows属性有一种奇怪的行为

我试图弄清楚如何在大范围内的特定行上工作.但是,使用rows属性创建的范围似乎与简单范围的行为不同.检查以下代码,第一次定义变量SpecificRow时,无法选择特定的单元格.然而,通过重新定义范围的奇怪解决方法,它工作正常.您是否知道为什么以及如何以更优雅的方式定义范围?

'The following shows the weird behavior of Rows property
Dim SourceRng As Range
Dim SpecificRow As Range
Dim i As Long

i = 3

Set SourceRng = Range("A1:D20")
Set SpecificRow = SourceRng.Rows(i)

'This will show the address of the selected row ("A3:D3")
MsgBox SpecificRow.Address

'Unexplicable behavior of the range when trying to select a specific cell
'where it will instead consider the whole row (within the limits of SourceRng)
MsgBox SpecificRow(1).Address
MsgBox SpecificRow(2).Address

'This would send an error
'MsgBox …
Run Code Online (Sandbox Code Playgroud)

excel vba excel-vba

2
推荐指数
1
解决办法
177
查看次数

试图理解在Range对象上使用Item属性和Cells属性之间的区别

我明白:

  • Range.Item 返回一个Range对象,该对象表示偏移到指定范围的范围.

  • Range.Cells 返回一个Range对象,该对象表示指定范围内的单元格.

但是,当我读到"Item是Range对象的默认属性"时,会出现混淆.

这让我想问:

Range("A1:D5").Cells(1,1)真正的简化版本 Range("A1:D5").Cells.Item(1,1)

为什么不在Range("A1:D5").Item(1,1)任何情况下使用?

为什么VBA程序员似乎使用该Cells属性来引用范围而不是Item属性?仅仅省略Item默认属性是"最佳实践" Cells吗?

excel vba

1
推荐指数
1
解决办法
77
查看次数

标签 统计

excel ×3

vba ×3

excel-vba ×1