使用表格在VBA中求和

时间:2019-03-10 14:49:16

标签: excel vba excel-formula

enter image description here

我已经定义了一个名为subtable的表。我试图以比使用适当的单元格定义range更为动态的方式执行计算。 但是,下面的行抛出compile error。我不确定我要去哪里。

Set tbl = Sheets("ASF").ListObjects("tblASF")
tbl.Resize Range("A1:C1200")

Set ws = ThisWorkbook.Sheets.Add(After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count))
ws.Name = "Test"
tbl.Range.Copy Destination:=ws.Range("C1")
Set subtable = Sheets("Test").ListObjects(1)

Dim rate As Long

Set ws = ActiveSheet
rate = Application.WorksheetFunction.SumProduct(--(Range("subtable[Tye]") = "Standard"), Range("subtable[Amount]"), Range("subtable[Rate]")) / Application.WorksheetFunction.SumIf(Range("subtable[Amount]"), "Standard")

3 个答案:

答案 0 :(得分:1)

  • 访问范围时使用Range("name of range here")(暂时忽略[]语法糖)-最好包括父级工作簿和工作表名称(包含范围)。
  • 我认为您的公式有误。您尚未包括SUMIF的第三个参数,因此返回值将为零(这意味着即使您的代码在语法上有效,也将得到除以0的错误)。
  • 我认为您不能像在单元格中那样在VBA中使用SUMPRODUCT。更具体地说,在VBA中,您不能双重否定数组(--)才能将其转换为10的数组。相反,您必须手动遍历数组并将其转换为所需的数组(据我所知)。

您需要在部门中固定除数/分母(我已对其进行了更改以使示例工作)。

假设您的subtable表在工作表"Sheet1"上:

Option Explicit

Private Sub SumproductInVBA()

    With ThisWorkbook.Worksheets("Sheet1")

        Dim typeColumn As Variant
        typeColumn = .Range("subtable[Type]").Value2

        Dim rowIndex As Long
        For rowIndex = LBound(typeColumn, 1) To UBound(typeColumn, 1)
            If typeColumn(rowIndex, 1) = "Standard" Then
                typeColumn(rowIndex, 1) = 1
            Else
                typeColumn(rowIndex, 1) = 0
            End If
        Next rowIndex

        Dim someVariable As Double
        someVariable = Application.SumProduct(typeColumn, .Range("subtable[Amount]"), .Range("subtable[Rate]")) / Application.SumIf(.Range("subtable[Type]"), "Standard", .Range("subtable[Amount]"))

    End With

End Sub

或者,代替上面的方法,更简短但更慢的方法可能是:

someVariable = Application.Evaluate("SUMPRODUCT(--(subtable[Type]=""Standard""),subtable[Amount],subtable[Rate])/SUMIF(subtable[Type],""Standard"",subtable[Amount])")

以上对我有用。

答案 1 :(得分:1)

我想您正在公式中使用“子表”(例如:Range("subtable[Tye]")...)来引用您在subTable中设置的Set subtable = Sheets("Test").ListObjects(1)对象变量所指向的表,但是它不起作用那样

->您必须在“子表”之后实际命名

Set subtable = ws.ListObjects(1)
subtable.Name = "subtable" '<- name the table after "subtable"

然后,您必须遵循@chillin有关使用SUMPRODUCT()工作表函数的建议

最终代码可能是:

Dim tbl As ListObject, subtable As ListObject
Dim ws As Worksheet

Set tbl = Sheets("ASF").ListObjects("tblASF")
tbl.Resize Range("A1:C1200")

Set ws = ThisWorkbook.Sheets.Add(After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count))
ws.Name = "Test"
tbl.Range.Copy Destination:=ws.Range("C1")

Set subtable = ws.ListObjects(1)
subtable.Name = "subtable"

Dim rate As Long
rate = Application.Evaluate("SUMPRODUCT(--(subtable[Tye]=""Standard""),subtable[Amount],subtable[Rate])/SUMIF(subtable[Tye],""Standard"",subtable[Amount])")

顺便说一句,请注意Dim rate As Long将把rate以下的任何public static void readSessionsApiAllSessions(Context context) { SessionReadRequest readRequest = readFitnessSession(); Fitness.getSessionsClient(context , GoogleSignIn.getLastSignedInAccount(context)) .readSession(readRequest) .addOnSuccessListener(new OnSuccessListener<SessionReadResponse>() { @Override public void onSuccess(SessionReadResponse sessionReadResponse) { // Get a list of the sessions that match the criteria to check the result. List<Session> sessions = sessionReadResponse.getSessions(); Log.i(TAG, "Session read was successful. Number of returned sessions is: " + sessions.size()); for (Session session : sessions) { // Process the session dumpSession(session); // Process the data sets for this session List<DataSet> dataSets = sessionReadResponse.getDataSet(session); for (DataSet dataSet : dataSets) { dumpDataSet(dataSet); } } } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Log.i(TAG, "Failed to read session"); } }); } public static SessionReadRequest readFitnessSession() { Calendar cal = Calendar.getInstance(); Date now = new Date(); cal.setTime(now); long endTime = cal.getTimeInMillis(); cal.add(Calendar.DAY_OF_YEAR, -2); long startTime = cal.getTimeInMillis(); // Build a session read request SessionReadRequest readRequest = new SessionReadRequest.Builder() .setTimeInterval(startTime, endTime, TimeUnit.MILLISECONDS) .read(DataType.TYPE_WORKOUT_EXERCISE) .readSessionsFromAllApps() .enableServerQueries() .build(); // [END build_read_session_request] return readRequest; } 都削减为零

答案 2 :(得分:0)

两个问题:

1)[ ]并不是在VBA中访问数组中元素的方式。相反,[x]Evaluate("x")大致相同,因此类似subtable[Amount]的事物类似于subtable Evaluate("Amount"),这显然毫无意义。

2)Type是保留字

您没有提供足够的上下文来说明更多信息。