2015-05-25 85 views
0

所以我發現了這個在微軟網站(https://msdn.microsoft.com/en-us/library/office/ff839746.aspx)當我試圖在VBA編程的東西如何使用。在VBA中查找特定的數據類型?

表達.Find(什麼,之後,看着,注視,SearchOrder,SearchDirection,MatchCase,MatchByte,SearchFormat) 表達上表示Range對象的變量。

什麼:要搜索的數據。可以是字符串或任何Microsoft Excel數據類型。

我想讓我的代碼找到第一個單元格,其中「Date」數據類型在特定的範圍temp中。

Dim temp As Range, next_date As Range 
temp = Range("A63:A70") 
Set next_date = temp.Find(Date) 
Debug.Print (next_date) 

但我不斷收到「對象變量未設置」的錯誤,我認爲這意味着它無法找到範圍內的日期。這個範圍中肯定有一個日期,但是當我將鼠標放在.Find()中輸入的「Date」上時,我意識到它顯示了今天的日期。

我認爲這段代碼可能試圖在該範圍內尋找今天的日期。但我只是希望它找到一個通用的「日期」數據類型的單元格,有沒有辦法做到這一點,而不指定具體的日期?謝謝!!

+0

感謝您的答案!我意識到我誤讀了「可以是字符串或任何Microsoft Excel數據類型」 - 我認爲這意味着.Find可以用於查找特定數據類型,但我現在意識到它的意思.Find可用於查找某些字符串或數字或日期或其他Excel數據類型的任何其他數據。我希望避免循環,因爲我實際上正在處理數百行(但在示例中未指定),但我可能會使用您的答案,Jeeped!另外,感謝Alex P和Dawid提供的有用輸入 – cobaltB12

回答

0

的問題是沒有這麼多'A63:A70有日期嗎?'但是'A63還有什麼:A70?'。日期並不是一種獨立的價值。對於大多數意圖和目的(稍後更多),它們被視爲數字。如果您只想在包含日期,文本,空白但沒有其他數字的範圍內找到第一個日期類型,則應該這樣做。

Dim temp As Range 
    On Error Resume Next 
    Set temp = Range("A63:A70").SpecialCells(xlCellTypeConstants, xlNumbers) 
    If Not temp Is Nothing Then 
     Set temp = temp.Cells(1, 1) 'reset temp to the 1st date if there are more than one 
     Debug.Print temp.Address 
    Else 
     Debug.Print "no date in range" 
    End If 

我之所以說意圖和目的是因爲VBA確實有IsDate Function。這可能看起來是a)值的數字性質,b)Range.Value和Range.Value2之間的差異,以及c)單元格的數字格式,以確定單元格值是否爲42,14925-May-2015。但是,IsDate函數一次只能檢查一個單元,因此需要耗費耗費時間的單元循環。

Dim temp As Range 
    For Each temp In Range("A63:A70") 
     If IsDate(temp) Then Exit For 
    Next temp 
    If Not temp Is Nothing Then 
     Debug.Print temp.Address 
    Else 
     Debug.Print "no date in range" 
    End If 

你舉的例子是隻有8細胞,使循環不會過於不利的性能,但它肯定會慢下來有幾千個細胞逐個檢查。

+0

關於循環性能的好處 - 我在回答中考慮過這種情況,即如果只有小範圍,那麼循環很好,但對於大型數據集,它不會那麼好。 –

2

我不確定您可以使用Find()查找任何值爲日期類型的值。我想你需要指定你正在搜索的實際日期。例如:

Set FoundCell = Range("A1:A10").Find (what:="7/18/1998") 

一種替代的選擇是一個簡單的循環:

Sub FindNextDate() 
    Dim val As Range 

    For Each val In Range("A1:A10") 
     If IsDate(val) Then 
      Debug.Print "Date: " & val & " found at cell: " & val.Address 
      Exit Sub 
     End If 
    Next val 
End Sub 
0

temp是一個對象Range。您必須使用set - >What does the keyword Set actually do in VBA?

我認爲你不能使用.Find()找到的數據類型,但是,你可以嘗試找到格式,這表明我們正在處理的日期:

Sub tt() 

Dim temp As Range, next_date As Range 
Set temp = Range("A60:A70") 

Application.FindFormat.NumberFormat = "m/d/yyyy" 

Set next_date = temp.Find("", SearchFormat:=True) 

Debug.Print next_date 
Debug.Print next_date.Address 

End Sub 
相關問題