2013-05-16 61 views
0

目标:我正在寻找一个可以根据一列中的单元格条件删除多行的宏,但我希望宏在每次运行时都要求一个值而不是在代码中包含设定值。到目前为止,我在网上找到的每个代码都不起作用,或者只编码一个值。Excel 2003 - 按单元格值删除多行的宏

我使用Excel 2003中

这里是我发现,我的目的工作的一个代码..但我想,这样它会提示用户输入一定次数以某种方式修改,而不是一次又一次地使用相同的号码。

 Sub Delete_Rows() 
      Dim rng As Range, cell As Range, del As Range 
      Set rng = Intersect(Range("A2:J707"), ActiveSheet.UsedRange) 
      For Each cell In rng 
      If (cell.Value) = "201" _ 
      Then 
      If del Is Nothing Then 
      Set del = cell 
      Else: Set del = Union(del, cell) 
      End If 
      End If 
      Next cell 
      On Error Resume Next 
      del.EntireRow.Delete 
     End Sub 
+0

您是否尝试过提供的解决方案?如果其中一个人回答你的问题,你应该将其标记为答案。 – neizan

+0

是的第二个为我的目的工作,但我是新的,显然与我的1声望......我在哪里标记为答案? – elpablo

+0

没关系,我明白了。 – elpablo

回答

0

您应该检查InputBox function

基本上,它会显示在对话框中提示,等待用户输入文本或单击按钮,然后返回包含文本内容的字符串框。

因此,对于您的代码,这将是这样的:

Sub Delete_Rows() 
    Dim selectedValue As Integer 
    selectedValue = InputBox ("Please, enter a number", "Input for deleting row", Type:=1) 
           'Prompt     'Title     'Value type (number here) 
    Dim rng As Range, cell As Range, del As Range 
    Set rng = Intersect(Range("A2:J707"), ActiveSheet.UsedRange) 
    For Each cell In rng 
    If (cell.Value) = selectedValue _ 
    Then 
    If del Is Nothing Then 
    Set del = cell 
    Else: Set del = Union(del, cell) 
    End If 
    End If 
    Next cell 
    On Error Resume Next 
    del.EntireRow.Delete 
End Sub 
+1

谢谢你。我不得不在你提供的网站的帮助下编辑一些代码..但它完成了工作。 – elpablo

+0

不错:)很高兴它的作品! –

0

试试这个。它首先选择所需的范围,然后运行宏。真的只有第一行和最后一行在范围内很重要,所以范围可以只是一列宽。它将删除所选范围内的所有行,其中输入的列中的值与输入的值匹配。

Sub DeleteRows() 
    Application.ScreenUpdating = False 

    Dim msg As String, title As String 
    Dim col As Integer 
    Dim value As String 

    msg = "Enter column number:" 
    title = "Choose column" 
    col = InputBox(msg, title) 

    msg = "Enter string to search for:" 
    title = "Choose search string" 
    value = InputBox(msg, title) 

    Dim rSt As Integer, rEn As Integer 
    rSt = Selection.Rows(1).Row 
    rEn = rSt + Selection.Rows.Count - 1 

    Dim r As Integer 
    r = rSt 
    While r <= rEn 
     If Cells(r, col).value = value Then 
      Rows(r).EntireRow.Delete Shift:=xlUp 
      rEn = rEn - 1 
     Else 
      r = r + 1 
     End If 
    Wend 

    Application.ScreenUpdating = True 
End Sub