调用以前保存的函数VBA

时间:2015-06-29 08:01:42

标签: excel vba excel-vba

想知道为什么我收到错误“编译错误 - 参数不可选”当我运行以下代码时?我是VBA的初学者。基本上,我希望它通过调用它来嵌入先前定义的函数。

 Function testranges(range1 As Range, range2 As Range)
    'function to compare if the values of two ranges are the same
    'define the variables
    Dim range1rows, range1cols, range2rows, range2cols, i, j As Integer
    ' count the rows and columns in each of the ranges
    range1rows = range1.Rows.Count
    range1cols = range1.Columns.Count
    range2rows = range2.Rows.Count
    range2cols = range2.Columns.Count

    'are the ranges the same dimension?
    testranges = (range1rows = range2rows And range1cols = range2cols)

    'if same dimension loop through the cells
    If (testranges) Then

        For i = 1 To range1rows
            For j = 1 To range1cols

            If (range1.Cells(i, j).Value <> range2.Cells(i, j).Value) Then
                testranges = False
            End If

            Next
        Next

    End If

    'loop through
    'for
End Function

'Call previously defined fucntion
Sub comparesheetnew()
    Call testranges

End Sub

3 个答案:

答案 0 :(得分:0)

如果不将参数传递给它,则无法调用函数。 (除非它们是可选的)。定义如下

 Function testranges(range1 As Range, range2 As Range)

您必须通过将两个范围传递给函数来调用该函数,例如

Call testranges range("A1:A2"), range("B1:B2")

如果没有传递两个范围,函数本身将无法正常运行

答案 1 :(得分:0)

您不能将range1和range2参数传递给 comparisonheetnew 子中的测试范围功能。

答案 2 :(得分:0)

每当你调用它时,你需要将两个范围传递给该函数。你真的不想在函数本身内递归调用它,所以你应该使用一个单独的变量 - 这是一个简单的修复:

Function testranges(range1 As Range, range2 As Range)
'function to compare if the values of two ranges are the same
'define the variables
    Dim range1rows            As Long
    Dim range1cols            As Long
    Dim range2rows            As Long
    Dim range2cols            As Long
    Dim i                     As Long
    Dim j                     As Long
    Dim bMatches              As Boolean

    ' count the rows and columns in each of the ranges
    range1rows = range1.Rows.Count
    range1cols = range1.Columns.Count
    range2rows = range2.Rows.Count
    range2cols = range2.Columns.Count

    'are the ranges the same dimension?
    bMatches = (range1rows = range2rows And range1cols = range2cols)

    ' true if the same size, false otherwise
    testranges = bMatches

    'if same dimensions loop through the cells
    If bMatches Then

        For i = 1 To range1rows
            For j = 1 To range1cols

                If (range1.Cells(i, j).Value <> range2.Cells(i, j).Value) Then
                    testranges = False
                    ' no point testing the rest
                    Exit Function
                End If

            Next
        Next

    End If

End Function

'Call previously defined fucntion
Sub comparesheetnew()
    ' you have to pass two ranges here.
    MsgBox testranges(Range("A1:A10"), Range("B1:B10"))

End Sub
相关问题