2010-09-02 105 views
1

我想在vb中编写一个宏来选择列B中的值包含字符'via'的所有行。这是我对宏的第一次尝试,并不太清楚如何开始。excel 2007宏选择记录

回答

1

这一个应该为你做(它为我工作) - 代码改编自here

Option Explicit 

Sub SelectByValue(Rng1 As Range, Value As String) 

    Dim MyRange As Range 
    Dim Cell As Object 

    'Check every cell in the range for matching criteria. 
    For Each Cell In Rng1 
     If InStr(1, Cell.Text, "via") Then 
      If MyRange Is Nothing Then 
       Set MyRange = Range(Cell.Address) 
      Else 
       Set MyRange = Union(MyRange, Range(Cell.Address)) 
      End If 
     End If 
    Next 
    'Select the new range of only matching criteria 
    MyRange.Select 

End Sub 

Sub CallSelectByValue() 

    'Call the macro and pass all the required variables to it. 
    'In the line below, change the Range and the Value as needed 
    Call SelectByValue(Range("B1:B10"), "via") 

End Sub 

如何使用它?

  1. 复制上面的代码。
  2. 打开您想要运行此代码的工作簿。
  3. 按下Alt + F11打开Visual Basic编辑器(或VBE)。
  4. 从菜单中选择插入模块。
  5. 将代码粘贴到右侧的代码窗口中。
  6. 更改代码中的呼叫SelectByValue(范围(“B1:B10”),“通过”)行以符合您的需求。
  7. 关闭VBE。

如何测试代码?

  1. 打开工具 - 宏 - 宏并双击CallSelectByValue。

运行宏之前:

alt text

运行宏后:

alt text

+0

感谢您的详细答复,真的很感激。还有一件事,我将如何显示或切割到另一个工作表中的行 – vbNewbie 2010-09-02 20:27:17