2016-08-30 25 views
2

我想在某些变量前添加+符号,如果它们是肯定的。 例如:使用子/函数修改变量

Sub mySub() 
    Dim cash As Variant 
End Sub 

它运作良好,如果我这样做:

Dim plus As String 
plus = "+" 


If cash > 0 Then 
    cash = plus & cash 
    Else 
    cash= cash 
End If 

但我一直在寻找一个子或函数,将采取所有我的变量,并添加如果他们面前的一个+号是积极的。

sub NewSub(i As Variant) 
    If i > 0 Then 
     i = plus & i 
     Else 
     i = i 
    End If 
End sub 

但它似乎没有工作,因为它不告诉我任何东西(我当时在Excel单元格中显示我的变量)。而且一个功能也不起作用。

任何想法如何创建一个子/功能来做到这一点?我可以以任何方式循环访问变量吗?

+1

您是否设想使用单元格格式? –

回答

3

首先,开始使用Option Explicit,它强制您显式声明每个变量,并在VBA编辑器中捕获不匹配错误,而不是在运行时捕获。

接下来,如果要通过在左端添加'加号'来将数值变量更改为字符串,那么原始变量必须是变体类型。如果你想传递一个参数到一个子程序中并让子程序改变它,那么参数必须是ByRef

或者,您可以将该变量推入一个函数并返回新值。

Option Explicit 

Sub main() 
    Dim cash As Variant, cash2 As Variant 

    cash = 10 
    Debug.Print cash '10 (as number) 

    AddPlus cash 
    Debug.Print cash '+10 (as string) 

    cash = 10 
    Debug.Print cash '10 (as number) 

    cash = udfAddPlus(cash) 
    Debug.Print cash '+10 (as string) 

End Sub 

Sub AddPlus(ByRef i As Variant) 
    If i > 0 Then 
     i = "+" & i 
    Else 
     i = i 
    End If 
End Sub 

Function udfAddPlus(i As Variant) 
    If i > 0 Then 
     udfAddPlus = "+" & i 
    Else 
     udfAddPlus = i 
    End If 
End Function 

Debug.Print命令将输出发送到VBE的Immediate window

+0

非常感谢!现在你会知道如何通过函数循环不同的变量(比如告诉函数以cash1开始并停止在cashn中)? – lo1ngru

+1

如果我有一些* *变量要声明,我会使用一个数组。 '暗淡的现金(3)作为变量'产生4个变量变量;现金(0),现金(1),现金(2)和现金(3)。从[LBound](https://msdn.microsoft.com/en-us/library/t9a7w1ac(v = vs.90).aspx)到[UBound](https://msdn.microsoft.com/en -us /图书馆/办公室/ gg278658.aspx)。 – Jeeped