2016-02-14 35 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 
相关问题