需要find函数来搜索一个工作表的一列

时间:2013-02-22 16:55:57

标签: excel excel-vba vba

我需要一个find函数来搜索我的工作表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

3 个答案:

答案 0 :(得分: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范围对象,所以我将其删除了。
  2. ActivateSelect不需要,甚至可能会降低您的代码速度。
  3. 请记住,Find会返回一个范围对象,稍后您可以在代码中使用它。

答案 1 :(得分: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

答案 2 :(得分: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