在列中搜索今天日期并选择单元格

时间:2018-04-21 17:16:13

标签: vba excel-vba date excel

我找到了一个代码,但我不知道为什么它不起作用,我对VBA几乎不陌生。请帮帮我..

我想要实现的是我需要今天从另一个搜索wb。

这是我的完整代码:

    Sub Sample

Sheets("Database").Select
Dim i as Workbook
Dim c as Workbook

Set i = Workbooks("Workbook1.xlsm")
Set c = Workbooks.Open(FileName:=Range("U2").Value)
'U2 contains the link or path of the file.

ThisWorkbook.Activate

Sheets("Summary").Activate
Windows("Workbook1").Activate
Sheets("Database").Select

Workbooks(2).Activate
Sheets("Summary").Select

Dim FindString As Date
Dim Rng As Range

FindString = CLng(Date)
With Sheets("Summary").Range("A:A")
Set Rng = .Find(What:=FindString, After:=.Cells(.Cells.Count), LookIn:=xlFormulas, LookAt:=xlWhole, SearchOrder:=xlbyColumns, SearchDirection;=xlNext,MatchCase;=False)

If Not Rng Is nothing then
Application.Goto Rng, True
Else
Msgbox "Nothing Then"
End if
End with
End Sub

最近打开的其他工作簿包含摘要表,其中包含A列上的日期:A

2 个答案:

答案 0 :(得分:0)

如果您收到语法错误 - 这两个参数是用分号“;”定义的而不是冒号“:”

SearchDirection;=xlNext,MatchCase;=False

变为

SearchDirection:=xlNext,MatchCase:=False

在测试之前修复语法 - 使用Debug |编译

答案 1 :(得分:0)

激活和选择不是必要且有害的

还有一些语法错误

您可能需要从以下代码重新开始:

Sub Sample
    Dim dbSheet as Worksheet
    Dim Rng As Range

    Set dbSheet = Workbooks("Workbook1.xlsm").Sheets("Database") 'set the “database” worksheet
    With Workbooks.Open(FileName:=dbSheet.Range("U2").Value).Sheets("Summary") 'open the workbook whose link is in “database” sheet cell U2 and reference its “Summary” sheet
        With  .Range("A1", .Cells(.Rows.Count, 1).End(xlUp)) ' reference referenced sheet column A cells from row 1 down to last not empty row
            Set Rng = .Find(What:=CLng(Date), After:=.Cells(.Rows.Count), LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:=False) ' try finding current date starting from the cell at the top of referenced range
        End With 
    End With 
    If Not Rng Is nothing then
        Application.Goto Rng, True
    Else
        Msgbox "Nothing Then"
    End if
End Sub

此代码未经测试,但根据评论中的说明,您可以调整它以达到目标