从子分配值

时间:2019-07-09 14:57:08

标签: excel vba

我似乎无法编写基本的子函数来返回值。我收到“编译错误:期望的函数或变量名称”,但VBA似乎可以识别该名称。当我更新函数名称时,它甚至会更改大小写。

我看过这里的帮助甚至类似的帖子。我认为这是一个愚蠢的错误,但是有人可以帮助我了解我在做什么错。我什至做了一个无法编译的简单函数:

Sub fIVe()
    Dim i As Integer
    i = 5
    fIVe = i
End Sub

sClassification = getClassification("Activities")
ExportSheet "Activities", sFolderName, xWb, True, sClassification

Public Sub getClassification(sTabName As String)
    Dim sClassificationCode As String, sClassification As String
    'Step 1: Find Code for tab name
    sClassificationCode = Application.WorksheetFunction.Index(Sheets("Cover Master").Range("B7:B12"), _
        Application.WorksheetFunction.Match(sTabName, Sheets("Cover Master").Range("A7:A12"), 0), 1)
    'Step 2: Find definition in Type Definitions tab using code from above
    sClassification = Application.WorksheetFunction.Index(Sheets("Type Definitions").Range("F6:F21"), _
        Application.WorksheetFunction.Match(sClassificationCode, Sheets("Type Definitions").Range("E6:E21"), 0), 1)
     getClassification = sClassification
End Sub

1 个答案:

答案 0 :(得分:1)

需要进行一些更改才能进行编译。要返回值,而不是

Public Sub foo
End Sub

您使用

Public Function foo As SomeReturnTypeOrOther
    foo = SomeValueOrOther
End Function

以下标记有“ <==”的更改。

Function fIVe() As Long    ' <== 'Function' instead of 'Sub'; add 'As <type>'
    Dim i As Long          ' <== Use 'Long' instead of 'Integer'
    i = 5
    fIVe = i
End Function                ' <== End Function

Public Sub DoSomething()    ' <== Wrap the 'sClassification = ...' 
                            ' and 'ExportSheet' lines in a Sub
    Dim sClassification As String   ' <== Since it's not in `getClassification`, 
                                    ' it doesn't share the variables
    sClassification = getClassification("Activities")
    ExportSheet "Activities", sFolderName, xWb, True, sClassification
End Sub

Public Function getClassification(sTabName As String) As String  ' <== Function; As String
    Dim sClassificationCode As String, sClassification As String
    'Step 1: Find Code for tab name
    sClassificationCode = Application.WorksheetFunction.Index(Sheets("Cover Master").Range("B7:B12"), _
        Application.WorksheetFunction.Match(sTabName, Sheets("Cover Master").Range("A7:A12"), 0), 1)
    'Step 2: Find definition in Type Definitions tab using code from above
    sClassification = Application.WorksheetFunction.Index(Sheets("Type Definitions").Range("F6:F21"), _
        Application.WorksheetFunction.Match(sClassificationCode, Sheets("Type Definitions").Range("E6:E21"), 0), 1)
     getClassification = sClassification
End Function

' I also added a stub ExportSheet since it wasn't included in your question.
Public Sub ExportSheet(ParamArray args() As Variant)
    ' Not sure what you want to do here
End Sub