使用excel查找时间序列

时间:2015-11-09 13:08:18

标签: excel vba excel-vba find

我的.find命令有问题。我想创建一个宏来复制范围并将其粘贴到使用find命令找到的特定单元格之后(偏移以将活动单元格移动到数据值):

Sub value()
Dim today As String
Dim lookfor As Range

Sheets(1).Range("C3:C19").Copy
today = "11.nov"

Set lookfor = Cells.Find(What:=today, _
            After:=ActiveCell, _
            LookIn:=xlValues, _
            LookAt:=xlPart, _
            SearchOrder:=xlByColumns, _
            SearchDirection:=xlNext, _
            MatchCase:=False, _
            SearchFormat:=False).Activate

lookfor.Offset(rowOffset:=1, columnOffset:=3).Paste
End Sub

1 个答案:

答案 0 :(得分:0)

事实上,在使用Find之前,您必须检查If Not LookFor Is Nothing Then方法是否有结果。

所以我的猜测是Find方法找不到您要查找的值的任何内容。

以下是修改后的代码:

Sub test_Veiko_Aunapuu()
Dim FirstAddress As String, _
    ToDay As String, _
    LookFor As Range

ToDay = "11.nov"

Sheets(1).Activate
Sheets(1).Range("C3:C19").Copy

With Sheets(1).Cells
    '----First, define properly the Find method
    Set LookFor = .Find(What:=ToDay, _
                After:=ActiveCell, _
                LookIn:=xlValues, _
                LookAt:=xlPart, _
                SearchOrder:=xlByColumns, _
                SearchDirection:=xlNext, _
                MatchCase:=False, _
                SearchFormat:=False)

    If Not LookFor Is Nothing Then
    '----If there is a result,
        FirstAddress = LookFor.Address
        'LookFor.Activate
        MsgBox "The row containing " & ToDay & " is : " & LookFor.Row
        'Keep looking with FindNext method : Not usefull for your example
        Do
            '-------------------------------------------------------------
            '----Place instructions to execute on the matched cell/row/...
            LookFor.Offset(rowOffset:=1, columnOffset:=3).Paste

            '-------------------------------------------------------------
            Set LookFor = .FindNext(LookFor)
        'Loop and keep looking until you find again the first result
        Loop While Not LookFor Is Nothing And LookFor.Address <> FirstAddress
    Else
    '----If there is no results, say it
        MsgBox "No matches were found for : " & ToDay, vbCritical + vbOKOnly, "No results"
    End If
End With

End Sub