2016-02-14 36 views
2

我在Excel中與vba有點新。 我試圖做一個函數來檢查特定文本的範圍,並將包含該值的單元格添加到新範圍。並返回新的範圍。轉到範圍,並將具有特定值的單元格添加到新範圍

我在brettdj上發現了幾乎相同的代碼,並對其進行了一些修改。

功能樣子:

Function Test(Testvalue As String, TargetRange As Range) As Range 

    Dim rng2 As Range 
    Dim c As Range 

    For Each c In TargetRange 
    If c.Text = Testvalue Then 
     If Not rng2 Is Nothing Then 
     ' Add the 2nd, 3rd, 4th etc cell to our new range, rng2 
     ' this is the most common outcome so place it first in the IF test (faster coding) 
      Set rng2 = Union(rng2, c) 
     Else 
     ' the first valid cell becomes rng2 
      Set rng2 = c 
     End If 
    End If 
    Next 
    Set Test = rng2 
End Function 

但是,當我把這個用在Excel中,例如在= ISBLANK(測試(蘋果; A1:A5)),它返回一個#VALUE!

有人想法我怎麼能得到這個工作。 許多thz提前

+0

你想要的功能,以什麼樣的回報?我測試了這個函數,它返回了'FALSE',而不是'#VALUE!'。你想讓該函數返回true/false,還是希望它返回找到值的單元格地址? – ARich

+0

你好ARICH,我想返回單元格作爲範圍。所以我可以在其他函數中使用輸出,其中有一個範圍作爲輸入。在我的問題中有一個錯誤,我使用Countblank而不是IsBlank對其進行了測試。結果#Value! –

回答

3

單元格地址是String類型,而不是Range類型,所以你不能返回兩個函數。用戶定義的函數(UDF)不能返回Range對象。你可以做的是回到每個單元的地址:

Function Test(Testvalue As String, TargetRange As Range) As String 
    Dim rng2 As String 
    Dim c As Range 

    For Each c In TargetRange 
     If c.Text = Testvalue Then 
      If rng2 <> vbNullString Then 
       ' Add the 2nd, 3rd, 4th etc cell to our new range, rng2 
       ' this is the most common outcome so place it first in the IF test (faster coding) 
       rng2 = rng2 & "," & c.Address 
      Else 
       ' the first valid cell becomes rng2 
       rng2 = c.Address 
      End If 
     End If 
    Next 
    Test = rng2 
End Function 

,此函數的輸出是一個逗號分隔的單元格地址的列表,其中字符串被發現。 (B3包含公式,B2顯示了在B3的公式是什麼樣子。)

Example Usage

使用單元格地址的這個字符串,你必須創建一個不同的UDF(雖然UDF不能修改不同的單元格的內容或格式):

Function test2(TestValue As String) As String 
    Dim c As Range 
    For Each c In Range(TestValue) 
     MsgBox "The cell's address is: " & c.Address 
    Next c 
    test2 = "Last calculated on " & Now() 
End Function 

如果你想以任何方式修改包含文本「蘋果」的細胞,你應該考慮使用不同的方法。

+0

所以如果我理解正確,我不能將給定範圍內的單個單元格加在一起並返回該Rang?它會一直返回逗號分隔的字符串嗎? –

+0

@BasdeKoning正確,如果您試圖通過Excel工作表中的UDF(公式)返回範圍對象。如果您嘗試通過Sub過程或函數中的函數返回範圍,則可以執行您正在談論的內容。 – ARich

+0

@BasdeKoning如果找到多個單元格,我答案中的代碼將始終返回一個字符串,逗號分隔。 – ARich

0

額外的變種已經提供

Function Test(Testvalue As String, TargetRange As Range) As String 
    Dim d As Object: Set d = CreateObject("Scripting.Dictionary") 
    Dim c As Range 
    For Each c In TargetRange 
    If c.Value2 = Testvalue Then d.Add c.Address(0, 0), "" 
    Next 
    Test = Join(d.keys, ","): Set d = Nothing 
End Function 
相關問題