开发者

Excel VBA question - If then ElseIf statement

I have a VBA conditional function I hacked together (I'm a noob) that checks for a name in a cell and then returns appropriate variations if one of the conditions is true, otherwise it returns a blank "". Instead of returning a blank, I'd like it to return the default cell value.

As a开发者_StackOverflow中文版n example, I have the following cells and results based on my function:

   Cells
   A        B
1  Bob      Bob Rob Robert
2  Mike     Mike Michael
3  Dan      Dan Daniel
4  Scott  

I'd like the result for B4 to return the default value in A4 (Scott), rather then a blank, like this:

   Cells
   A        B
1  Bob      Bob Rob Robert
2  Mike     Mike Michael
3  Dan      Dan Daniel
4  Scott    Scott

Any help would be appreciated:

Here's my function (abbreviated version without all names included in ElseIf):

Function NameList(pVal As String) As String

    If pVal = "Bob" Then
        NameList = "Bob Rob Robert"
    ElseIf pVal = "Mike" Then
        NameList = "Mike Michael"
    ElseIf pVal = "Dan" Then
        NameList = "Dan Daniel"
    Else
        NameList = ""
    End If

End Function

Thanks!


I think
Else
NameList = pVal

solves your problem.


Take a good look at the else clause:

 [...]
 Else
     NameList = ""
 End If

The function returns the empty string ("") if none of the if/elseif clauses matches.

If your function is called with pVal="Scott" you fall through to the default assignment. What would you like it to be instead of the empty string?


I do not know whether I understand your question correctly but try this

Function NameList(pVal As String) As String

If pVal = "Bob" Then
    NameList = "Bob Rob Robert"
ElseIf pVal = "Mike" Then
    NameList = "Mike Michael"
ElseIf pVal = "Dan" Then
    NameList = "Dan Daniel"
Else
    NameList = pVal
End If

End Function
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜