2016-08-09 51 views
0

data on my Excel sheet我想在列A中查找日期。這是日期格式:「yyyy/mm/dd hh:mm:ss」。它總是發現什麼,但我正在尋找的日期是在A列 這是我的代碼片段:在列中查找日期值VBA

Dim LastDay As Date 
Dim strdate As String 
Dim rCell As Range 

strdate = Format(LastDay, "yyyy/mm/dd hh:mm:ss") 

Set rCell = Cells.Find(What:=CDate(strdate), After:=Range("A1"), LookIn:=xlValues _ 
     , LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False) 

If rCell Is Nothing Then 
MsgBox ("nothing") 
Else 

編輯:每個評論的新代碼。

Sub Copy() 
    Dim LastDayRow As Long 
    Dim FirstDayRow As Long 
    Dim LastDay As Date 
    Dim FirstDay As Date 
    Dim rcell As Range 

    LastDayRow = Range("E" & Rows.Count).End(xlUp).Row 
    Range("E" & LastDayRow).Copy Range("G1") 
    FirstDayRow = Range("A" & Rows.Count).End(xlUp).Row 
    Range("A" & FirstDayRow).Copy Range("G2") 
    LastDay = Cells(LastDayRow, "E").Value 
    FirstDay = Cells(FirstDayRow, "A").Value 

    Set rcell = Cells.Find(What:=LastDay, After:=Range("A1"), LookIn:=xlFormulas _ 
       , LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext) 

    If rcell Is Nothing Then 
     MsgBox ("nothing") 
    End If 

End Sub 
+1

從您提供的代碼,它不會出現你設置你的'LastDay'變量的任何值。 – Carrosive

+0

您編寫的代碼是基於xlValue查找的。單元格中的日期存儲實際上只是數字。因此,您將無法使用LookIn查找它:= xlValue –

+0

也可能是格式(將日期轉換爲字符串格式;並且您正在查找日期 – User632716

回答

0

問題在於日期的形式。在這個日期格式中的「/」:yyyy/mm/dd hh:mm:ss困惑了vba的運行。 源文件中的這些代碼行解決了這個問題:

Sheet1.Range("A:A").Replace What:="/", Replacement:="." 
Sheet1.Range("A:A").NumberFormat = "yyyy/mm/dd hh:mm:ss" 
Sheet3.Range("E:E").Replace What:="/", Replacement:="." 
Sheet3.Range("E:E").NumberFormat = "yyyy/mm/dd hh:mm:ss" 
0

日期類型以雙精度形式存儲在Excel和VBA中。通過將LookIn參數更改爲xlFormulas來搜索double值而不是日期。您也可以省略MatchCase參數(您正在使用默認值)。

Set rCell = Cells.Find(What:=LastDay, After:=Range("A1"), LookIn:=xlFormulas _ 
     , LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext) 

注意,你在這裏做一些毫無意義的工作...

strdate = Format(LastDay, "yyyy/mm/dd hh:mm:ss") 

...因爲你根本施展它的日期,當你做你查找:

What:=CDate(strdate) 
+0

我改變了你的建議,但仍然沒有在列A中找到日期。如果我將LastDay設置爲Double,則宏將停止並顯示錯誤消息。 – vergab

+0

@vergab - 您的更新代碼對我來說運行得非常好。錯誤是你得到和在哪裏? – Comintern

+0

rcell值是「沒有」,但日期是在列A中。這是列E中的最後日期:2016/08/02 18:16:21它也在A列。 – vergab

相關問題