1

I don't have much experience but I'm trying to write a function that will search column A and the 1st time it finds a string beginning with "AT" it will copy that whole string to Cell N1, the 2nd string beginning with "AT" will be copied to N2, so on and so forth until column A is exhausted. This is my feeble attempt so far but I'm not having much luck.

Function Find_AT(ByVal I As Integer)

Dim c As Range
Dim COUNTER As Integer
Dim CAPTURE As Long

    COUNTER = 0

    For Each c In Range("A1", Range("A65636").End(xlUp))
        If Left(c, 2) = AT Then
            COUNTER = COUNTER + 1
            If COUNTER = I Then
            CAPTURE = c
            Exit For
            End If
        End If
        Next c
Find_AT = CAPTURE

End Function
4

3 回答 3

0

考虑:

Function Find_AT(ByVal I As Long) As String
    Dim c As Range
    Dim COUNTER As Long
    Dim CAPTURE As String
    Dim v As String
    COUNTER = 0
    CAPTURE = "xx"
    For Each c In Range("A1", Range("A65636").End(xlUp))
        v = c.Text & "  "
        If Left(v, 2) = "AT" Then
            COUNTER = COUNTER + 1
            If COUNTER = I Then
                CAPTURE = c.Address
                Exit For
            End If
        End If
    Next c
    Find_AT = CAPTURE
End Function
于 2013-06-27T23:07:35.860 回答
0

过滤效率更高。以下两种方法:

筛选

Sub GetAT1()
X = Filter(Application.Transpose(Range([a1], Cells(Rows.Count, "A").End(xlUp))), "AT", True)
If UBound(X) > 0 Then [n1].Resize(UBound(X) + 1) = Application.Transpose(X)
End Sub

自动筛选

Sub GetAT()
Dim rng1 As Range
Set rng1 = Range([a1], Cells(Rows.Count, "A").End(xlUp))

Application.ScreenUpdating = False
ActiveSheet.AutoFilterMode = False
rng1.AutoFilter 1, "=AT*"
rng1.Copy [n1]
If LCase$(Left$([n1], 2)) <> "at" Then [n1].Delete xlUp

ActiveSheet.AutoFilterMode = False
Application.ScreenUpdating = True
End Sub
于 2013-06-28T02:27:49.553 回答
0

您的代码的错误是文本(字符串)AT 需要用双引号“AT”括起来。添加Option Explicit到模块的顶部,当您尝试编译或执行该函数时,它会将您带到此错误。

但是,根据您的描述,我怀疑您可能想要编写子过程(SUB)而不是函数。函数旨在返回一个值。如果你想使用一个函数,你可以这样定义它:

Function Find_AT(rng As Range, ByVal i As Integer)

也就是说,您将为其提供 aRange进行搜索,并提供数字 1 以查找以“AT”开头的范围内的第一个值。但是,如果将此函数放在一个单元格中并将其复制下来,它仍将仅返回第一次出现。您需要手动将 1 更改为 2、3 等(或使用 ROW() 的变体来自动生成此序列)。

无论如何,我怀疑您真的想要一个可以通过单击工作表上的按钮来运行的 SUB 程序。

如果您希望继续使用当前函数,则可以将返回类型声明为字符串:

Function Find_AT(ByVal i As Integer) As String
'...
Dim CAPTURE As String
'...
    CAPTURE = c.Text

否则,设置CAPTURE = c并尝试返回此值会导致问题,因为 c 是一个Range对象。

于 2013-06-27T22:55:31.767 回答