在subs之间传递参数的问题

时间:2014-07-23 15:39:27

标签: excel vba excel-vba

我的主要子项如下:

Option Explicit
Public y As String
Public xCell As Range
Sub BenAppMr()

Call SearchFor("Award")
Call ConvertToLetter(xCell)
MsgBox "The column letter is " & y
End Sub

然后是我从上面打电话的另外两个潜艇:

Sub SearchFor(z As String)
xCell = Cells.Find(What:=z, After:=ActiveCell, LookIn:= _
xlFormulas, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:= _
xlNext, MatchCase:=False, SearchFormat:=False)
End Sub

Sub ConvertToLetter(x As Range)
y = Split(x.Address(1, 0), "$")(0)
End Sub

我在这里遗漏了什么吗?我不太明白为什么这不起作用。

我希望在我的Excel工作表中搜索“奖励”并将列号转换为字母。我希望传递这些参数,因为我将在我的主要子中调用一些搜索和一些转换(一旦它正在工作)

自从我使用这种设置以来已经有很长一段时间了,通常我只是在没有传递参数的情况下调用程序,但这样会更加清晰。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

使用Sub来设置全局变量不是一个好的编码模式 - 使用函数将值直接返回到调用代码会更好:

Sub BenAppMr()

    Dim y As String, xCell As Range

    Set xCell = SearchFor("Award")

    If Not xCell Is Nothing Then
        y = ConvertToLetter(xCell)
        MsgBox "The column letter is " & y
    Else
        MsgBox "Search value not found!"
    End If

End Sub

Function SearchFor(z As String) As Range
    Dim xCell As Range

    Set xCell = ActiveSheet.Cells.Find(What:=z, After:=ActiveCell, LookIn:= _
    xlFormulas, LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:= _
    xlNext, MatchCase:=False, SearchFormat:=False)

    Set SearchFor = xCell
End Function

Function ConvertToLetter(x As Range) As String
    ConvertToLetter = Split(x.Address(1, 0), "$")(0)
End Function

...并使用Set作为对象类型变量,如Rory指出的那样。