2017-07-12 85 views
0

我需要針對以下情況的解決方案: 我有一張包含4張工作表的Exel文件。 所有牀單的結構都是一樣的,只是內容不同而已。在vba中計算值「x」

說明:

  • 用戶必須設置在該地區D9一個「X」:I9(這個「X」必須在所有表計,但有一個特殊情況:
  • 用戶可以設置在該區域K9的「Y」:P9

在這種情況下只應計算所有的「x」的「y」的區域之後,此片材的

實施例:

表1:D9:I9( 「X」)= 6 「×」 enter image description here

表2:D9:I9( 「X」)= 6 「×」 enter image description here

表3: D9:I9(「x」)= 6「x」| M9(「y」) enter image description here

而在表3中是特殊情況。 用戶設置了6個「x」,但也設置了「y」。

這意味着,不應計算在「y」之前和相同區域中設置的「x」。

我有以下VBA代碼,偉馳算我所有的「X」,而不是機智這種「特殊情況」(我不知道如何)

Function breaking_count() 

Const Area_x As String = "$D$9:$I$9" 
Const Area_y As String = "$K$9:$P$9" 

Dim Nr As Integer, Count_x As Integer 


For Nr = 4 To 1 Step -1 

    With Worksheets(CStr(Nr)) 

     If WorksheetFunction.CountIf(.Range(Area_y), "*y*") > 0 Then Exit For 
     Count_x = Count_x + WorksheetFunction.CountIf(.Range(Area_x), "*x*") 

    End With 

Next 
End Function 

回答

0

下面的代碼將顯示消息框爲每張紙計數爲x

Sub breaking_count() 
    Const Area_x As String = "$D$9:$I$9" 
    Const Area_y As String = "$K$9:$P$9" 
    Dim Nr As Integer, Count_x As Integer, Col_Ind 
    Dim temp_Area As Range 

    For Nr = 4 To 1 Step -1 
     'With Worksheets(CStr(Nr)) 
     With Worksheets(Nr) 
      If WorksheetFunction.CountIf(.Range(Area_y), "*y*") > 0 Then 
       'find the index of "y" in Area_y 
       Col_Ind = WorksheetFunction.Match("y", .Range(Area_y)) 
       'Reset the range Area_y in temp_Area using offset 
       Set temp_Area = .Range(.Cells(9, 4).Offset(0, Col_Ind), .Cells(9, 9)) 
       Count_x = Count_x + WorksheetFunction.CountIf(temp_Area, "*x*") 
      Else 
       Count_x = Count_x + WorksheetFunction.CountIf(.Range(Area_x), "*x*") 
      End If 
      MsgBox Worksheets(Nr).Name & " : " & Count_x 
      Count_x = 0 
     End With 

    Next 
End Sub 

讓我知道是否有什麼不清楚。

+0

非常感謝你:) – Ghost108

+0

@ Ghost108 - 不客氣! – Mrig