转到“范围”并将具有特定值的单元格添加到新范围

时间:2016-02-14 21:50:24

标签: excel vba excel-vba range

我在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(test(Apple; A1:A5))中它返回一个#VALUE!。

有人知道如何让这个工作。 许多事先提前

2 个答案:

答案 0 :(得分: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

如果您试图以任何方式修改包含文本&#34; Apple&#34;的单元格,您应该考虑使用其他方法。

答案 1 :(得分:0)

已提供的其他变体

F(x) = (sin(x) + 1) / 2
2*F(x) -1 = sin(x)
sin^-1(2*F(x) -1) = x

# in R code
Finv = function(p) {
  x = 180/pi * asin(2*p - 1)
  ind = abs(x) < (2/pi)
  x[ind] = 0
  return(x)
}