我没有太多经验,但我正在尝试编写一个搜索A列的函数,第一次找到以“AT”开头的字符串,它会将整个字符串复制到Cell N1,第二个字符串从“AT”开始将被复制到N2,依此类推,直到A列耗尽为止。到目前为止,这是我的微弱尝试,但我没有太多运气。
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
答案 0 :(得分:0)
您的代码的错误是文本(字符串)AT需要用双引号“AT”括起来。将Option Explicit
添加到模块的顶部,当您尝试编译或执行该函数时,它会将您带到此错误。
但是,根据您的描述,我怀疑您可能想要编写子过程(SUB)而不是函数。函数旨在返回一个值。如果你想使用一个函数,你可以这样定义它:
Function Find_AT(rng As Range, ByVal i As Integer)
也就是说,您将为其提供Range
进行搜索,并使用数字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
对象。
答案 1 :(得分: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
答案 2 :(得分: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