用户创建的VBA函数返回#VALUE

时间:2015-07-31 16:13:03

标签: vba function excel-vba excel

我处于创​​建vba函数的早期阶段,该函数将从单元格中提取电子邮件地址,然后对唯一ID执行vlookup。

我将使用该函数的单元格如下:

"该消息于7月31日由SOB发送至email@email.com,#34; 要么 "消息由SOB 7/31"

发送至email@email.com

我要做的第一件事是删除电子邮件地址后面的任何内容。为此,该功能将于7月31日由SOB搜索"" OR"由SOB 7/31"并将其替换为空。

我编写了以下代码来尝试完成此操作,但是当我在工作簿中使用它时收到错误消息:

Function ExtractEmail(extractStr As String) As String

Dim DateText As String
Dim DateNum As String

DateText = "by SOB on July 31st"
DateNum = "by SOB 7/31"

If InStr(extractStr, DateText ) Then
    Left(extractStr, InStr(extractStr, DateText )) = extractStr
        ElseIf InStr(extractStr, DateNum ) Then
            Left(extractStr, InStr(extractStr, DateNum )) = extractStr
        Else
            extractStr = "Nothing Found"

End If




End Function

所以这个:

  

此消息于7月31日由SOB发送至email@email.com

应该返回:

  

此邮件已发送至email@email.com

我知道为什么我会收到错误#Value!?

感谢您的帮助!

2 个答案:

答案 0 :(得分:2)

您以错误的方式分配事物,并且您需要使用UDF的名称实际从函数返回值。我认为这就是你所追求的:

Function ExtractEmail(extractStr As String) As String

Dim DateText As String
Dim DateNum As String

DateText = "by SOB on July 31st"
DateNum = "by SOB 7/31"

If InStr(extractStr, DateText ) Then
    extractStr = Left(extractStr, InStr(extractStr, DateText ))
ElseIf InStr(extractStr, DateNum ) Then
    extractStr = Left(extractStr, InStr(extractStr, DateNum ))
Else
    extractStr = "Nothing Found"
End If

ExtractEmail = extractStr

End Function

答案 1 :(得分:0)

如果您只想删除"由SOB"然后:

Function ExtractEmail(extractStr As String) As String

    ExtractEmail = Split(extractStr, " by SOB ")(0)

End Function