如果 table 单元格等于变量值

If table cell equals variable value

如果单元格等于代码中指定的数字,我发现删除行有很多帮助,但如果单元格的值等于值,我无法删除 table 行的一个变量。

(这是我第一次尝试 VBA,也是我第一次使用这样的网站来寻求有关任何主题的帮助。感谢您提供的任何帮助。)

Sub NeverGonnaWork

Dim x as String

x = Sheets("Sheet1").Range("B5").Value

Dim tbl as ListObject

Set tbl = Sheets("Sheet2").ListObjects("Table2")

'if column 15 in last row of the table equals x, delete that row of the table'

If Cells(tbl.ListRows.Count, (15)) = x then
tbl.ListRows(tbl.ListRows.Count).Delete

End If

End Sub

It "doesn't work", because you are referencing Worksheet.Cells(<amount of rows in table>, 15) rather than the actual cell position inside the table.

换句话说,您只是在 Worksheet.

中引用了一些 "random" 单元格

将您的代码更改为此,它应该可以工作;-)

Private Sub thisWillWork()

  Dim compVal as String: compVal = Sheets("Sheet1").Range("B5").Value2
  Dim tbl as ListObject: Set tbl = Sheets("Sheet2").ListObjects("Table2")

  If tbl.ListRows(tbl.ListRows.Count).Range(,15) = compVal Then
     tbl.ListRows(tbl.ListRows.Count).Delete
  End If

End Sub