Excel VBA中IF-Else使用current_row变量时条件始终不成立的问题
问题分析与解决方案:Excel VBA按钮IF条件未触发的问题
核心问题排查
从你的描述和代码来看,最可能的原因是列引用不匹配:你的表格里"Number of tasks done"列是第二列(对应VBA里的列号2,即B列),但代码中判断的是第7列(7,即G列)的单元格值。这就导致当current_row指向"End of Table"行时,你检查的G列单元格并不是你设置为0的那个单元格,自然条件永远不成立。
其他可能的原因(如果列号没问题的话)
如果确认列号是正确的,那可以排查以下几点:
- 单元格数据类型不匹配:如果"End of Table"行的目标单元格是文本型的"0"(而非数值型0),虽然VBA通常会自动转换类型,但偶尔会出现判断失效的情况。可以改用
CInt(Sheets("Sheet1").Cells(current_row, 7)) = 0来强制转换为整数后再判断。 - 单元格存在隐藏字符:如果单元格里的0是复制粘贴来的,可能带有空格或不可见字符,导致和纯0比较不相等。可以用
Trim(Sheets("Sheet1").Cells(current_row, 7).Value) = "0"来去除空格后判断(如果是文本型),或者用Abs(Sheets("Sheet1").Cells(current_row, 7).Value) < 0.0001来模糊判断数值是否接近0。
修正后的代码示例
假设你的"Number of tasks done"列是B列(列号2),调整列号后的代码如下:
Dim current_row As Long '<-- global variable Current Row Sub Button6_Click() current_row = Sheets("Sheet2").Cells(1, 1) ' 这里把列号从7改成2,对应你的表格中的任务数列 If Sheets("Sheet1").Cells(current_row, 2) = 0 Then Sheets("Sheet1").Cells(18, 1) = 555555 current_row = 11 '<-- return to first record row at the end of table-end of table has 0 value Else current_row = current_row + 1 '<--increases of 1 each click End If ' 同样把列号从7改成2 Sheets("Sheet1").Cells(current_row, 2) = Sheets("Sheet1").Cells(current_row, 2) + 1 Sheets("Sheet2").Cells(1, 1) = current_row Sheets("Sheet1").Cells(17, 1) = current_row End Sub
额外的逻辑优化建议
你当前的代码在每次点击后都会给目标单元格加1,包括回到首行的那次。如果这不是你想要的效果(比如回到首行时不应该增加任务数),可以把加1的逻辑移到Else分支里:
Dim current_row As Long '<-- global variable Current Row Sub Button6_Click() current_row = Sheets("Sheet2").Cells(1, 1) If Sheets("Sheet1").Cells(current_row, 2) = 0 Then Sheets("Sheet1").Cells(18, 1) = 555555 current_row = 11 '<-- return to first record row Else Sheets("Sheet1").Cells(current_row, 2) = Sheets("Sheet1").Cells(current_row, 2) + 1 current_row = current_row + 1 '<--increases of 1 each click End If Sheets("Sheet2").Cells(1, 1) = current_row Sheets("Sheet1").Cells(17, 1) = current_row End Sub
内容的提问来源于stack exchange,提问作者harix prog4
相关产品推荐
相关产品推荐

