![](/img/trans.png)
[英]VBA code to remove a range of cells in a row if a cell's condition criteria is met
[英]Deleting cells and corresponding row if criteria is met
我有一個電子表格,其中的列從 A5 到 AA5,數據從 A6 到 AA10000。 在單元格 A1 中,用戶輸入一個值,在單元格 A2 中是一個下拉框,其中包含列 X 到 AA(A、B、C、D)的標題,在 A3 中我有一個邏輯運算符下拉列表(<,> ,<>,=)。 我正在嘗試編寫一個腳本,通過 X 列到 AA 並刪除滿足用戶設置條件的單元格,例如用戶輸入值 300、標題“B”和邏輯運算符“<”和宏通過具有標題“B”的 Y 列並刪除小於 300 的所有值,刪除從 A 到 AA 的行。
到目前為止,我已經嘗試過這個:
Sub removedata()
Dim ws As Worksheet
Dim rng As Range
Dim headerval As Variant
Dim sign As Variant
Dim inputval As Variant
Dim b_header As Range
Dim Cell As Range
Set ws = Worksheets("Sheet1")
Set rng = ws.Range("X5:AA5000")
Set b_header = ws.Range("X5:X5000")
inputval = cells(1, 1).Value
headerval = cells(2, 1).Value
sign = cells(3, 1).Value
For Each Cell In b_header.cells
If (headerval = "B") And (sign = "<") And (inputval < Cell.Value) Then
Cell.Delete
End If
Next Cell
End Sub
我只是在 B 柱上嘗試過它作為測試,看看我是否能得到一些東西。 當我運行這個宏時,它只是緩沖一秒鍾,然后什么也沒有發生。
任何幫助將不勝感激!
編輯:實際上我意識到它會刪除大於輸入(單元格 A1)的值,但是每次運行它時它只會刪除其中的幾個,它還會將其下方的單元格移動到其位置。
COUNTIF/COUNTIFS 工作表函數接受標准並將其解釋為字符串。 您可以與 Evaluate 一起使用或直接通過應用程序對象使用。
Option Explicit
Sub delSpecial()
Dim lr As Long, i As Long, c As String, cl As Long
With Worksheets("sheet6")
c = .Cells(3, "A").Value & .Cells(1, "A").Value
cl = Application.Match(.Cells(2, "A").Value, .Rows(5), 0)
lr = Application.Max(.Cells(.Rows.Count, "X").End(xlUp).Row, _
.Cells(.Rows.Count, "Y").End(xlUp).Row, _
.Cells(.Rows.Count, "Z").End(xlUp).Row, _
.Cells(.Rows.Count, "AA").End(xlUp).Row)
For i = lr To 6 Step -1
If CBool(Application.CountIf(.Cells(i, cl), c)) Then
.Cells(i, "A").Resize(1, 27).Interior.Color = vbYellow
'.Rows(i).EntireRow.Delete
End If
Next i
End With
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.