我试图在特定行中对特定标题的列进行求和,但我得到该行的所有列的总和,而不管标题

时间:2018-03-29 08:01:23

标签: excel vba for-loop if-statement

'我试图在特定行中对特定标题的列进行求和,但是我得到该行的所有列的总和,而不管标题。有人可以告诉我我的错误吗?请参见附图中的样本输入输出。enter image description here

Dim DSum As Integer
Dim PSum As Integer
With wsn
    NIMsLastRow = Worksheets("NIMSCarrierCount").Cells(Rows.Count, 1).End(xlUp).Row
    NIMsLastCol = Worksheets("NIMSCarrierCount").Cells(1, Columns.Count).End(xlToLeft).Column
    For j = 2 To NIMsLastRow
        DSum = 0
        PSum = 0
        For k = 2 To NIMsLastCol
            If .Cells(1, k).Value = "LTE 1900Deployed" Or "LTE 2500Deployed" Or "LTE 800Deployed" Or "UnassignedDeployed" Then
                DSum = DSum + CInt(.Cells(j, k).Value)
            End If
            If .Cells(1, k).Value = "LTE 1900Planning" Or "LTE 2500Planning" Or "LTE 800Deployed" Or "UnassignedPlanning" Then
                PSum = PSum + CInt(.Cells(j, k).Value)
            End If
        Next k
        .Cells(j, NIMsLastCol + 1).Value = DSum
        .Cells(j, NIMsLastCol + 2).Value = PSum
    Next j
End With

2 个答案:

答案 0 :(得分:0)

您的if语句写错了。

每个查询都会将Or "LTE 2500Deployed"评估为True。

您需要为每个参数指定完全 .Cells(1, k).Value = "LTE 1900Deployed" Or .Cells(1, k).Value = "LTE 2500Deployed" Or...

答案 1 :(得分:0)

我会考虑重写以使用Select Case,它也可以解决测试条件周围的错误。请记住在模块顶部使用Option Explicit来检查变量声明。您的DSum和PSum可能需要Double吗?注意我已经为Longs交换了Integers以避免潜在的溢出(当尝试存储对于声明的数据类型来说太大的东西时会出现大数字)

Option Explicit 'Always use Option Explicit

Sub test()

Dim wsn As Worksheet
Set wsn = ThisWorkbook.Worksheets("NIMSCarrierCount") 'assumption this is correct sheet assigment

Dim DSum As Long 'use Long to avoid potential overflow
Dim PSum As Long
Dim NIMsLastRow As Long 'declare all variables
Dim NIMsLastCol As Long
Dim j As Long
Dim k As Long

With wsn

    NIMsLastRow = .Cells(.Rows.Count, 1).End(xlUp).Row
    NIMsLastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column

    For j = 2 To NIMsLastRow

        DSum = 0
        PSum = 0

        Dim testValue As String

        For k = 2 To NIMsLastCol

            testValue = .Cells(1, k)

            Select Case testValue

            Case "LTE 1900Deployed", "LTE 2500Deployed", "UnassignedDeployed"
                DSum = DSum + CLng(.Cells(j, k))

            Case "LTE 1900Planning", "LTE 2500Planning", "UnassignedPlanning"
                PSum = PSum + CLng(.Cells(j, k))

            Case "LTE 800Deployed"

              DSum = DSum + CLng(.Cells(j, k))
              PSum = PSum + CLng(.Cells(j, k))

            End Select

        Next k

        .Cells(j, NIMsLastCol + 1).Value = DSum
        .Cells(j, NIMsLastCol + 2).Value = PSum

    Next j

End With

End Sub