与C / CPP / CSharp / JScript一样,我们如何在VBA中进行链式赋值?换句话说,VBA是否具有赋值运算符的右关联性?
例如在C-sharp和JavaScript中,我们可以使用:
var alpha, bravo, charlie;
alpha = bravo = charlie = "hello";
现在在VBA中编写此表达式必须:
Dim alpha, bravo, charlie
alpha = "hello"
bravo = "hello"
charlie = "hello"
但我们不能使用:
Dim alpha, bravo, charlie
alpha = bravo = charlie = "hello"
VBA不允许折叠表达式。还有其他办法吗?
答案 0 :(得分:5)
不,VBA与赋值运算符没有正确的关联性。但是,VBA确实具有其他逻辑运算符的右关联性或链接操作。请考虑以下表达式:
alpha = 3
bravo = 5
charlie = 4
alpha = bravo < charlie
MsgBox(alpha) 'would display false
alpha = 3
bravo = 5
charlie = 4
alpha = bravo > charlie < alpha
MsgBox(alpha) 'would display ture .. because (bravo > charlie) is true
'and true (or 1) less than alpha
但是,VBA解释器优先于赋值运算符的比较运算符,两者都由=
表示。好的,
alpha = bravo = "hello"
MsgBox(alpha) 'would display false, because bravo <> "hello"
因此,您需要明确使用多个语句进行分配。
答案 1 :(得分:1)
我将使用
代替以下分配功能Public Sub Assign(ParamArray varsAndValue() As Variant)
Dim idx As Long
Dim value As Variant
If UBound(varsAndValue) < 1 Then
Err.Raise 999, "Invalid call to «Assign»: Last argument should be the value to set, first upto one but last should be the variables"
ElseIf UBound(varsAndValue) < 2 Then
Err.Raise 999, "Why don't you use a normal assignment when you only need to assign one variable?"
Else
value = varsAndValue(UBound(varsAndValue))
For idx = 0 To UBound(varsAndValue) - 1
varsAndValue(idx) = value
Next idx
End If
End Sub
答案 2 :(得分:0)
从某种意义上说,你不想这样做。 This question表示VB.net中也不存在该功能。
如上所述,VBA使用最左边的=符号将值分配给alpha,所有其他用于比较目的。
一次分配多个变量的唯一选择是使用数组。
这些示例来自here
Dim myarray As Variant
myarray = Array("Cat", "Dog", "Rabbit")
或
Dim MyStringArr() As String
MyStringArr = Split("Text1,Text2,Text3", ",")
答案 3 :(得分:0)
你可以随时使用这样的功能:
Private Function assign(var As Variant, value As Variant) As Variant
var = value
assign = value
End Function
Private Sub Form_Load()
Dim alpha, bravo, charlie
Call assign(alpha, assign(bravo, assign(charlie, "hello")))
Debug.Print alpha, bravo, charlie
End Sub
......但它很快变得丑陋。