2017-06-16 1 views
0

Ich habe 2 qns, die in VBA-Code ausgeführt werden soll. 1. Ich möchte die Gesamtzahl der Wiederholungen einer bestimmten Zeichenfolge für mehr als 40 eindeutige Werte in einer Spalte zählen. Wie dies erreicht werden kann.Zählwerte in Spalte wiederholt für einzigartigen fileds

für zB - einzigartige Werte wie Apfel, Banane, Weintrauben (40 weitere einzigartige Werte) werden in einer Spalte wiederholt und ich möchte die Anzahl der einzelnen Saiten so.

Apple- 30 times repeated 
banana- 4 times repeated. 
  1. nach der Gesamtzahl der einzelnen Strings nehmen, ich möchte, dass sie zählen mit bestimmten Kriterien.

EG- Zählung Apfel, nur dann, wenn die Kosten, wenn über 40 Zählung Trauben, nur dann, wenn die Kosten, wenn über 40

any1 kann auf dieser pls helfen, wie dies in der VBA-Code zu implementieren.

+2

Ist diese Hausaufgabe zufällig? Haben Sie selbst einen Code versucht? – CallumDA

Antwort

0

Der folgende Code fügt alle Zeichenfolgen aus Spalte A in eine Auflistungsstruktur ein, sortiert sie beim Zählen jedes eindeutigen Werts und speichert jeden eindeutigen Wert und die entsprechende Summe in einer Dictionary-Struktur. Die Ergebnisse werden dann in das Direktfenster gedruckt. Hoffe das hilft.

Sub main() 


'variables 
Dim colCollection As New Collection 
Dim x, q As Variant 
Dim cellValue As String 
Dim j, i, count As Integer 
Dim numbers As New Scripting.Dictionary 'NOTE: add microsoft scripting Runtime Ref 


x = 1 'collections start at 1 

    While Worksheets("Sheet1").Cells(x, "A").Value <> "" 'while cell is not empty 
     cellValue = Worksheets("Sheet1").Cells(x, "A").Value 'store string value from cell 
     colCollection.Add (cellValue) ' add entry from cell to collection 
     x = x + 1 'increment 
    Wend 

    'Sort collection (bubbble sort) and record number of each unique item 
    For i = colCollection.count To 2 Step -1 'count down from collection 
     For j = 1 To i - 1 
      'bubble up item 
      If colCollection(j) > colCollection(j + 1) Then 
       colCollection.Add colCollection(j), After:=j + 1 
       colCollection.Remove j 
      End If 
     Next j 
     'finding count of unique item 
     If i <> colCollection.count Then 'if not at last item (can't compare 2 items when only given 1) 
      If i = 2 Then 'if at end 
       numbers.Add colCollection(i), count + 3 'add sum to dictionary with corresponding key value 
      Else 
       If StrComp(colCollection(i + 1), colCollection(i), 1) = 0 Then 'if same string 
        count = count + 1 'increment count 
       Else 
        numbers.Add colCollection(i + 1), count + 1 'add sum to dictionary with corresponding key value 
        count = 0 'reset count 
       End If 
      End If 
     End If 
    Next i 


'loop through dictionary 
For Each q In numbers.Keys 
    Debug.Print q & "- " & numbers.Item(q); " times repeated." 
Next 


End Sub