我使用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
答案 0 :(得分:1)
我认为你非常接近那里。我已经将一些数组和循环方法修改为我喜欢的方法。
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
我用分配到数组中的两个工作表测试了这个。您应该能够添加更多具有各自名称的工作表。
编辑:该函数应使用单元格地址作为传入其中的字符串。
=ACosts("B15", "C15")
传递到ACosts
函数的实际单元格引用是无用的,因为单元格引用的字符串值在许多工作表上使用。