2013-02-22 77 views
1

我需要一個查找功能來搜索我的工作表中的標題爲「引用表」的B列中找到「利潤調整」,如果它是區分大小寫的,這將是很好的。以下是我正在使用的代碼,但我無法獲得正確的範圍或措辭。任何幫助表示讚賞。需要一個查找功能來搜索一張紙的一列

Dim rFound As Range 
Set rFound = Range("B10:B1000") 

    Cells.Find(What:="Profit Adjustment", After:=ActiveCell, LookIn:=xlFormulas,   LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=True).Activate 
    ActiveCell.Offset(0, 8).Select 
    Selection.Copy 
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _ 
    :=False, Transpose:=False 

回答

1

我會重新寫你的例子是這樣的:

Sub copy_paste_example() 
    Dim c As Range 
    With ActiveWorkbook.Sheets("Quote Sheet") 
     Set c = .Columns("B").Find(What:="Profit Adjustment", _ 
            LookIn:=xlFormulas, LookAt:=xlPart, _ 
            SearchOrder:=xlByRows, _ 
            SearchDirection:=xlNext, MatchCase:=True) 
     On Error GoTo NotFoundErr: 
      c.Offset(0, 8).Value = c.Value 
    End With 
    Exit Sub 
NotFoundErr: 
    Debug.Print "value not found" 
End Sub 

注:

  1. 你沒有使用過的rfound Range對象,所以我刪除它。
  2. ActivateSelect不需要,甚至可能會減慢你的代碼。
  3. 請記住,Find會返回一個Range對象,該對象在您的代碼中稍後可能會有用。
+2

僅供參考 - 如果未找到「利潤調整」,則會拋出異常,因爲不會設置「c」,但會被「c.Value」使用。我可以建議在這裏使用條件語句嗎? '如果不是c沒有那麼...如果' – Sam 2013-02-22 17:46:00

+0

那是真正的好東西,山姆。考慮到你的敏銳觀察,我已經更新了示例代碼。 – bernie 2013-02-22 17:52:01

+0

我知道了。我真的很感激 – 2013-02-22 18:24:51

1
Sub samPle() 

    Dim rFound As Range, cellToFind As Range 
    Set rFound = Sheets("Quote Sheet").Range("B10:B1000") 

    Set cellToFind = Cells.Find(What:="Profit Adjustment", MatchCase:=True) 

    If Not cellToFind Is Nothing Then 
     cellToFind.Activate 
     ActiveCell.Offset(0, 8).Copy ActiveCell.Offset(0, 8) 
    End If 
End Sub 
1

如果你關心所有出現目前尚不清楚,我是否只想找到Profit Adjustment第一次出現,或。如果您想在Column B中找到全部行,其中包含Profit Adjustment,則下面的宏將按原樣運行。如果您只想找到首次出現,那麼只需取消註釋Exit For的註釋即可。

下面的代碼:

Sub FindValueInColumn() 
    Dim rowCount As Integer, currentRow As Integer, columnToSearch As Integer 
    Dim searchString As String 
    Dim quoteSheet As Worksheet 
    Set quoteSheet = ActiveWorkbook.Sheets("Quote Sheet") 
    searchString = "Profit Adjustment" 'string to look for 
    columnToSearch = 2     '2 represents column B 

    rowCount = quoteSheet.Cells(Rows.Count, columnToSearch).End(xlUp).Row 
    For currentRow = 1 To rowCount 
     If Not Cells(currentRow, columnToSearch).Find(What:=searchString, MatchCase:=True) Is Nothing Then 
      Cells(currentRow, 8).Value = Cells(currentRow, columnToSearch).Value 
      'uncomment the below "Exit For" line if you only care about the first occurrence 
      'Exit For 
     End If 
    Next 
End Sub 

搜索之前: enter image description here

搜索後:

enter image description here

相關問題