Excel VBA 问题 - If then ElseIf 语句
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5330383/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Excel VBA question - If then ElseIf statement
提问by Simon
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.
我有一个 VBA 条件函数(我是菜鸟),它检查单元格中的名称,然后在其中一个条件为真时返回适当的变体,否则返回空白“”。我希望它返回默认单元格值,而不是返回空白。
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!
谢谢!
回答by Hossein
I thinkElse
NameList = pVal
solves your problem.
我认为
可以解决您的问题。Else
NameList = pVal
回答by Anders Lindahl
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. What would you like it to be instead of the empty string?
如果你的函数被调用,pVal="Scott"
你就会失败到默认分配。你希望它是什么而不是空字符串?
回答by MP?kalski
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