调用先前保存的functionVBA

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

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 

无论何时调用,您都需要将两个范围传递给该函数。 你真的不想在函数内部recursion调用它,所以你应该使用一个单独的variables – 这是一个简单的修复:

 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 

如果不传递参数,就不能调用函数。 (除非是可选的)。 如下定义

  Function testranges(range1 As Range, range2 As Range) 

你将不得不调用该函数传递两个范围的function,例如

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

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

您不要将range1和range2parameter passing给compareheetnew子中的testranges函数。