在vba中循环显示具有特定function的表单

我是非常新的使用VBA和我的问题是以下几点:我写了一个函数SCOSTs

Public Function SCosts(x As Range, y As Range) As Double Dim n As Integer Dim Z As Double Dim W As Double For n = 1 To y.Columns.Count If (y.Cells(1, n) > 8) And (y.Cells(1, n) <> "") Then Z = Z + 8 * x.Cells(1, n) / y.Cells(1, n) End If If (y.Cells(1, n) <= 8) And (y.Cells(1, n) <> "") Then W = W + x.Cells(1, n) End If Next n SCosts = Z + W End Function 

哪个工作。

现在我有20张表,我想评估每个表的两个范围上的SCosts-fct,然后总结出来。 我写了以下ACosts函数循环遍历所有表单。 但它不起作用。 谁能帮我?

 Public Function ACosts(t As Variant, u As Variant) Dim R As Variant Dim Z As Double Dim Ressource(1 To 2) As Variant Ressource(1) = "SHEET1" Ressource(2) = "SHEET2" .... Ressource(20)= "SHEET2" For Each R In Ressourcen Z = Z + SCosts(Application.Goto(ActiveWorkbook.Sheets(R).Range(t)), Application.Goto(ActiveWorkbook.Sheets(R).Range(u))) Next R ACosts = Z End Function 

我想你已经差不多到了。 我已经修改了一些我喜欢的数组和循环方法。

 Public Function ACosts(t As Variant, u As Variant) Dim Z As Double Dim r As Long, Ressource As Variant Ressource = Array("SHEET1", "SHEET2") With ActiveWorkbook For r = LBound(Ressource) To UBound(Ressource) Z = Z + SCosts(.Sheets(Ressource(r)).Range(t), .Sheets(Ressource(r)).Range(u)) Next r End With ACosts = Z End Function 

我testing了这两个工作表分配到数组中。 您应该能够添加更多的工作表与他们各自的名字。

编辑:该函数应该使用单元格地址作为string传入它。

=ACosts("B15", "C15")

传递给ACosts函数的实际单元格引用是无用的,因为在许多工作表上使用了单元格引用的string值。