Excel VBA调试时RowCount代码行红黄高亮报错问题咨询
问题原因及解决方法
1. 当前行高亮报错的直接原因
你代码里的常量拼写错误:x1Up 里的第二个字符是数字1,而VBA内置的向上查找常量正确写法是xlUp,第二个字符是小写字母L。把该行代码修正为 RowCount = Cells(Rows.Count, "A").End(xlUp).Row 即可解决当前高亮提示。
2. 代码其他需要修正的隐藏问题
- 变量未声明:
RowCount、totalVolume、循环变量i都未做声明,建议在模块最顶部添加Option Explicit强制变量声明,从根源避免拼写类低级错误 - 赋值逻辑错误:两个条件判断分支目前都在给
endingPrice赋值,首次出现DQ的分支应该给startingPrice赋值,否则后续计算收益率时startingPrice为空会触发运行时错误 - 边界溢出风险:循环到最后一行
i=RowCount时,判断Cells(i + 1, 1)会超出工作表行范围,需要补充边界判断
修正后的参考代码
Option Explicit Sub DQAnalysis() Dim totalVolume As Long Dim startingPrice As Double Dim endingPrice As Double Dim RowCount As Long Dim i As Long Worksheets("DQ Analysis").Activate Range("A1").Value = "DAQ0 (Ticker: DQ)" '创建表头行 Cells(3, 1).Value = "Year" Cells(3, 2).Value = "Total Daily Volume" Cells(3, 3).Value = "Return" Worksheets("2018").Activate totalVolume = 0 '获取需要循环的总行数 RowCount = Cells(Rows.Count, "A").End(xlUp).Row '遍历所有行 For i = 2 To RowCount If Cells(i, 1).Value = "DQ" Then '累加交易量 totalVolume = totalVolume + Cells(i, 8).Value '判断是否为DQ首次出现,记录起始价 If Cells(i - 1, 1).Value <> "DQ" Then startingPrice = Cells(i, 6).Value End If '判断是否为DQ最后一次出现,记录结束价 If i = RowCount Or Cells(i + 1, 1).Value <> "DQ" Then endingPrice = Cells(i, 6).Value End If End If Next i Worksheets("DQ Analysis").Activate Cells(4, 1).Value = 2018 Cells(4, 2).Value = totalVolume '增加空值判断避免除零错误 If startingPrice <> 0 Then Cells(4, 3).Value = (endingPrice / startingPrice) - 1 Else Cells(4, 3).Value = "无有效起始价" End If End Sub
内容的提问来源于stack exchange,提问作者Dontrell92
相关产品推荐
相关产品推荐

