2016-02-21 28 views
0

我的代碼如下:VBA,具有一定的價值轉到電池(類型:日期)

Sub Find_First() 
    Dim FindString As String 
    Dim Rng As Range 
    FindString = Range("A1") 
    If Trim(FindString) <> "" Then 
     With Sheets("Kalendarz").Range("A5:LY5") 
      Set Rng = .Find(What:=FindString, _ 
          After:=.Cells(.Cells.Count), _ 
          LookIn:=xlValues, _ 
          LookAt:=xlWhole, _ 
          SearchOrder:=xlByRows, _ 
          SearchDirection:=xlNext, _ 
          MatchCase:=False) 
      If Not Rng Is Nothing Then 
       Application.Goto Rng, True 
      Else 
       MsgBox "Nothing found" 
      End If 
     End With 
    End If 
End Sub 

,但它不與日期格式,任何建議工作?

更多細節:在A1單元格,我將進入一個日期,在第5行我每天在2016年名單我想(運行宏後)去細胞與細胞A1日期。

+0

[見本](http://www.ozgrid.com/VBA/find-dates.htm)。你的代碼適用於我的標準Excel日期格式(MM/DD/YYYY),所以這可能是由於你的具體日期格式。 – ARich

回答

3

使用Find功能定位的日期是在Excel VBA中出了名的棘手。該功能依賴於您的搜索日期格式與Excel的默認設置相同。此外,你需要確保搜索字符串是Find函數內轉換爲日期,使用CDate。 Ozgrid上有一個很好的文章:http://www.ozgrid.com/VBA/find-dates.htm

我已經修改了你的代碼下面來滿足這些要求,並增加了額外的With Sheets...聲明,保證FindString從你的目標表使用的Range

但是,由於用戶調整日期格式的不可預測性,我更喜歡VBA循環,它使用Excel的日期數字表示形式的值2,所以不能擺弄。該Ozgrid文章寧願不使用時Find功能是如此之快VBA循環,但我想這是個人喜好的問題,我覺得一個定製的循環更加可靠。

取決於你想要去的哪一個。

Find方法:

Sub Find_First() 
    Dim FindString As String 
    Dim Rng As Range 

    With Sheets("Kalendarz") 
     FindString = .Range("A1") 
     If Trim(FindString) <> "" Then 
      With .Range("A5:LY5") 
       Set Rng = .Find(What:=CDate(FindString), _ 
           After:=.Cells(1), _ 
           LookIn:=xlValues, _ 
           LookAt:=xlWhole, _ 
           SearchOrder:=xlByRows, _ 
           SearchDirection:=xlNext, _ 
           MatchCase:=False) 
       If Not Rng Is Nothing Then 
        Application.Goto Rng, True 
       Else 
        MsgBox "Nothing found" 
       End If 
      End With 
     End If 
    End With 
End Sub 

的VBA循環方法:

Sub Find_First_VBA_Loop() 
    Dim dateVal As Long 
    Dim cell As Range 

    With Sheets("Kalendarz") 
     dateVal = .Range("A1").Value2 
     For Each cell In .Range("A5:LY5").Cells 
      If dateVal = cell.Value2 Then 
       Application.Goto cell, True 
       Exit For 
      End If 
     Next 
    End With 

End Sub 
+0

是的,它的工作原理!謝謝 :) – ana0890