首页 > 解决方案 > Excel-VBA-带变量的IF-Else语句第一部分不回答

问题描述

我有一个按钮的 VBA 代码,可以在 Excel 中依次增加单元格的值。代码是这样的:

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, 7) = 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
    Sheets("Sheet1").Cells(current_row, 7) = Sheets("Sheet1").Cells(current_row, 7) + 1
    Sheets("Sheet2").Cells(1, 1) = current_row
    Sheets("Sheet1").Cells(17, 1) = current_row
End Sub

当我使用 current_row 时,在 IF 子句的第一部分中,条件永远不会为真(但是,current_row 的值正确更改,并且我添加了一个临时显示 current_value 的命令,该命令在单元格第 18 行和第 1 列中显示正确)但是当我写一个数字而不是 current_row 变量并且目标单元格的值为零,第一个 IF 为真并正确继续。此代码适用于这样的表:

+=============+========================+
| **Name**    |**Number of tasks done**|
+=============+========================+
| Joe         |                      3 |
+-------------+------------------------+
| John        |                      2 |
+-------------+------------------------+
| Emma        |                      1 |
+-------------+------------------------+
| Sophia      |                      1 |
+-------------+------------------------+
|End of Table |                      0 |
+-------------+------------------------+

同时,我清除了表格末尾所有为1的所有单元格值,并在表格末尾写入零,或者将表格的单元格末尾留空,不进行任何操作,从第一个数字中取出起始值表的行并从表的开头开始增加,但在表的末尾再次继续插入1个值并继续同样的问题

请问您能说一下是什么问题吗?

标签: vbaexcelif-statement

解决方案


我发现了问题。

在 IF 语句之前,变量的值是从指定的单元格中接收到的,并在条件下进行检查,如果单元格的值等于 0,则将一个单元添加到变量中,然后在下一个单元格的基础上初始化单元格到 current_row。表示检查当前单元格的数量是否为 0,但下一个单元格已初始化,因此表末尾的值为零,始终更改,并且在审查之前或之后永远不会为零。

正确的代码是这样的:

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, 7) = "end" Then
        Sheets("Sheet1").Cells(18, 1) = 5453
        current_row = 11
        Sheets("Sheet1").Cells(current_row, 7) = Sheets("Sheet1").Cells(current_row, 7) + 1
        current_row = current_row + 1
    Else
        Sheets("Sheet1").Cells(current_row, 7) = Sheets("Sheet1").Cells(current_row, 7) + 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

谢谢大家


推荐阅读