简体   繁体   English

Excel VBA问题 - 如果那么ElseIf声明

[英]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 "". 我有一个VBA条件函数,我一起攻击(我是一个菜鸟),检查单元格中的名称,然后返回适当的变量,如果其中一个条件为真,否则返回一个空白“”。 Instead of returning a blank, I'd like it to return the default cell value. 而不是返回空白,我希望它返回默认的单元格值。

As an 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: 我希望B4的结果返回A4(Scott)中的默认值,而不是空白,如下所示:

   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): 这是我的函数(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子句:

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

The function returns the empty string ( "" ) if none of the if/elseif clauses matches. 如果if / elseif子句都不匹配,则该函数返回空字符串( "" )。

If your function is called with pVal="Scott" you fall through to the default assignment. 如果使用pVal="Scott"调用函数,则会进入默认赋值。 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM