2010-09-02 109 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