如果表格单元格等于变量值

问题描述 投票:1回答:1

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

(这是我第一次尝试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
excel vba delete-row
1个回答
0
投票

它“不起作用”,因为你引用的是Worksheet.Cells(<amount of rows in table>, 15)而不是表格中的实际单元格位置。

换句话说,你只是引用你的 Worksheet中的一些“随机”单元格。

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

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
© www.soinside.com 2019 - 2024. All rights reserved.