2013-02-22 81 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

相关问题