2016-12-07 104 views
1

我有一個問題,如何使用查找功能獲取單元格地址。下面的代碼如何獲取單元格地址從Excel中的查找功能vba

Dim Found As Range 

Set Found = Worksheets("Sheet 1").Cells.Find(What:="test", LookAt:=xlWhole, MatchCase:=True) 

    If Not Found Is Nothing Then 
      ' do something 
    End If 

問題是,當我嘗試調試代碼,「發現」變量包含「字符串」,而不是細胞解決。

不知道我的代碼有什麼問題。

+0

'Found'變量不包含'String',因此聲明它爲'Range',因此它包含'Range'對象引用。 [一個'Range'有一個'Address'屬性](https://msdn.microsoft.com/en-us/library/office/ff837625.aspx) - 使用它。您看到的字符串內容是範圍的「Value」,它是* default屬性*(即,當沒有指定成員時隱式引用的成員)。 –

回答

4

看來你可以只使用found.address,即使它顯示爲字符串。以下代碼適用於我。

Sub findCellAddress() 

    Dim ra As Range 

    Set ra = Cells.Find(What:="fff", LookIn:=xlFormulas, LookAt _ 
     :=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _ 
     False, SearchFormat:=False) 

    If ra Is Nothing Then 
     MsgBox ("Not found") 
     Else 
     MsgBox (ra.Address) 
    End If 

End Sub 
+2

'find'可以返回'Nothing',所以將'.Address'加到它的末尾就是[只需要運行時錯誤91](http://stackoverflow.com/search?q=%5Bexcel-vba %5D +找到+誤差+ 91)。在使用任何屬性之前,應始終將「Find」設置爲臨時的'Range'對象並針對'Nothing'進行測試。 – Comintern

+0

嗨@ nightcrawler23感謝您的反饋。有沒有辦法從「ra.Address」單獨獲取行和列?我想將其應用於單元格選擇(例如:單元格(1,2)) –

+0

範圍具有行和列屬性。所以你可以使用ra.Row和ra.Column來獲取值。 https://msdn.microsoft.com/en-us/library/office/ff838238.aspx#Anchor_3 – nightcrawler23

相關問題