为什么 MyTable.Range.Rows.Count return Excel VBA 中的值不正确

Why does MyTable.Range.Rows.Count return an incorrect value in Excel VBA

几天来我一直在研究一个问题,几乎找到了解决方案。我目前一直在开发一个 excel 应用程序,我有一个宏,通过单击按钮操作,它会重置 table.

中某些单元格内的数值

在此 table 中有 3 列; "Quantity Fitted (n)"、"Quantity Required (m)" 和 "Lock Configuration"。

我需要做的是,当单击按钮时,"Quantity Fitted (n)" 列中每一行的数值都将重置为与 "Quantity Required (m)" 列中显示的值相匹配行。

但是,如果该行 "Lock Configuration" 列中的单元格值设置为 "locked",我希望 "Quantity Fitted (n)" 值在单击按钮后保持不变。

我希望这是有道理的!这是我目前尝试编写的代码:

Dim x As Long

    'Set reference to your table.  Have hard-coded the sheet name and table name in.
    Dim MyTable As ListObject
    Set MyTable = Worksheets("System").ListObjects("Table_System")

    'These will be the numerical index numbers of the columns in your table.
    'This assumes your "Locked" column is in the table and has the header "Locked".
    Dim Required As Long, Fitted As Long, Locked As Long
    Required = MyTable.ListColumns("Quantity Required (m)").Index
    Fitted = MyTable.ListColumns("Quantity Fitted (n)").Index
    Locked = MyTable.ListColumns("Lock Configuration").Index

    'Look at each row in the table.  Am using `x` rather than `Each Cell`
    'as the row number of the cell may differ from the row location in the table
    'e.g. If your table starts on row 2, then first row after the header is row 3 - row 3 as Cell, but row 1 in table.
    For x = 1 To MyTable.Range.Rows.Count
        'If Locked column doesn't say "Locked" then copy value from
        'Fitted to Required columns, otherwise do nothing.
        If MyTable.DataBodyRange.Cells(x, Locked) <> "Locked" Then
            MyTable.DataBodyRange.Cells(x, Fitted) = MyTable.DataBodyRange.Cells(x, Required)
        Else
            'Do Nothing.
            'The ELSE and comment aren't really needed - just here to show nothing happens.
        End If
    Next x

End Sub

这实现了目标,但是由于 table 中的行数不正确,代码出现故障。在我的 table 中有 3 行,通过将公式直接输入到 =Rows(Table_System) 的 excel sheet 中,返回值 3。

但是,在我的代码中,我可以通过声明一个新变量 Dim y As Long 并将其设置为 y = MyTable.Range.Rows.Count 返回 y 的值为 5。

同样,如果我将 table 中的行数增加 1,excel 公式会将其解更新为 4。但是,我代码中的 y 值现在显示 6。它始终为 + 2领先?为什么会这样?

谢谢!

MyTable.Range

包括列 header 行和您可能拥有的任何页脚(例如总计)行

MyTable.DataBodyRange

仅包括数据行。所以这应该有效:

For x = 1 To MyTable.DataBodyRange.Rows.Count