概述
我目前正在开发一个简单的函数来帮助验证我的数组的起始位置。我正在使用DO语句,然后只是偏移活动单元格,直到满足我的DO语句的条件。
代码
Public Function ArrayStart() As Variant
Range("A3").Select
Do
ActiveCell.Offset(1, 0).Select
Loop While (ActiveCell.Value <> "Date" Or _
ActiveCell.Value <> "Open" Or _
ActiveCell.Value <> "High" Or _
ActiveCell.Value <> "Low" Or _
ActiveCell.Value <> "Close" Or _
ActiveCell.Value <> "Adj Close" Or _
ActiveCell.Value <> "Volume")
ArrayStart = ActiveCell.Row
End Function
Excel表格中的数据
Date Open High Low Close Adj Close Volume
12/22/1998 19.05 19.05 18.85 18.94 9.98 55900
12/23/1998 18.86 19.22 18.86 19.22 10.13 78800
12/24/1998 19.22 19.34 19.15 19.34 10.20 43800
12/28/1998 19.33 19.33 19.04 19.09 10.06 51900
12/29/1998 19.12 19.29 18.89 19.29 10.17 100800
12/30/1998 19.19 19.32 19.09 19.22 10.13 154600
12/31/1998 19.22 19.24 19.04 19.04 10.04 65400
日期位于范围“A4”中,所有数据的整个范围都位于“A4:G11”范围内
问题
代码一直工作,直到它进入Loop While部分,即使activecell是“A4”,即“Date”,它也不会识别它,并将继续保持循环。
当我拿出OR条件并使用此代码时,它可以完美地运行
Loop While (ActiveCell.Value <> "Date")
我正在运行相同的整体代码,但是删除了OR语句并且它运行良好,我没有错误,我只是无法理解为什么它不起作用。此外,当我将鼠标悬停在vba窗口中的activecell.value上时,当它到达单元格“A4”时显示“Date”???
答案 0 :(得分:2)
尝试
Public Function ArrayStart() As Variant
Range("A1").Select
Do
ActiveCell.Offset(1, 0).Select
Loop Until (ActiveCell.Value = "Date" Or _
ActiveCell.Value = "Open" Or _
ActiveCell.Value = "High" Or _
ActiveCell.Value = "Low" Or _
ActiveCell.Value = "Close" Or _
ActiveCell.Value = "Adj Close" Or _
ActiveCell.Value = "Volume")
ArrayStart = ActiveCell.Row
End Function
避免使用ActiveCell
,有关详细信息,请参阅this。更高效的代码将是
Public Function ArrayStartMMM() As Variant
Dim rng As Range
Set rng = Range("A1")
Do
Set rng = rng.Offset(1, 0)
Loop Until (rng.Value = "Date" Or _
rng.Value = "Open" Or _
rng.Value = "High" Or _
rng.Value = "Low" Or _
rng.Value = "Close" Or _
rng.Value = "Adj Close" Or _
rng.Value = "Volume")
ArrayStart = rng.Row
End Function