如果声明里面的for循环在VBA

时间:2016-12-30 07:15:14

标签: excel vba excel-vba

我正在尝试搜索一个列(在我的第3列中)并查看它是否将字符串传递给Extract函数。当If语句获得命中时,它会从同一行的不同列复制文本(在我的第6列中)并退出For循环。函数中的For循环将扫描第3列中的所有行。要检查匹配,我使用了VBA中可用的工作表函数。

Function Extract(x As String, Y As Integer) As String

    Dim i As Integer

    For i = 2 To Y
        If Application.WorksheetFunction.IsNumber(Application.WorksheetFunction.Find(x, Cells(i, 3))) = True Then
            Extract = Cells(i, 6)
            Exit For   
        End If
    Next i

End Function

我已经尝试过运行这段代码,我写过这似乎没有用。

2 个答案:

答案 0 :(得分:0)

已修改以添加“部分匹配”功能

  • 部分匹配

    使用Find()对象的Range方法:

    Function Extract(x As String, Y As Integer) As String    
        Dim f As Range
    
        Set f = Range(Cells(2, 3), Cells(Y, 3)).Find(what:=x, lookAt:=xlPart, LookIn:=xlValues) '<--| "xlPart" value of "lookAt" argument makes the "partial" match functionality
        If Not f Is Nothing Then Extract = f.Offset(,3).Text    
    End Function
    

    使用LookUp()对象的Application方法:

    Function Extract(x As String, Y As Integer) As String
        Dim f As Variant
    
        f = Application.VLookup("*" & x & "*", Range(Cells(2, 3), Cells(Y, 6)), 4, False) '<--| the "False" argument and the asterisks ("*") makes the "partial" match functionality
        If Not IsError(f) Then Extract = f
    End Function
    
  • 完全匹配

    使用Find()对象的Range方法:

    Function Extract(x As String, Y As Integer) As String    
        Dim f As Range
    
        Set f = Range(Cells(2, 3), Cells(Y, 3)).Find(what:=x, lookAt:=xlWhole, LookIn:=xlValues) '<--| "xlWhole" value of "lookAt" argument makes the "exact" match functionality
        If Not f Is Nothing Then Extract = f.Offset(,3).Text    
    End Function
    

    使用LookUp()对象的Application方法:

    Function Extract(x As String, Y As Integer) As String
        Dim f As Variant
    
        f = Application.VLookup(x, Range(Cells(2, 3), Cells(Y, 6)), 4, False)'<--| the "False" 4th argument makes the "exact" match functionality
        If Not IsError(f) Then Extract = f
    End Function
    

答案 1 :(得分:0)

您可以使用Match函数在第3列查找x。如果第3列中存在匹配,您将获得该行号。如果不是Extract将返回一个字符串,让您知道没有匹配。

注意:在我的测试中,Extract无法在Excel中运行,也许是保存的单词或其他内容,因此我修改为Extract2

修改1 :修改代码以支持PO的查找部分字符串的请求 - 在*之前和之后添加了x通配符。

Function Extract2(x As String, Y As Integer) As String

If Not IsError(Application.Match("*" & x & "*", Columns(3), 0)) Then ' successful match
    Extract2 = Cells(Application.Match("*" & x & "*", Columns(3), 0), 6)
Else  ' match was unable to find a result in column 3
    Extract2 = x & " not found in Column 3"
End If

End Function