2016-11-17 3 views
1

나는 매크로가 처음이므로 아래의 도움이 필요하다. 엑셀 매크로 - 데이터 조작

enter image description here

나는 위와 같은 값을 가지고있다. 사과, 오렌지 등의 총 개수를 계산하고 싶습니다. 제가 사과 = 15 바나나 = 17 개 망고 = 15 개 오렌지 = 13 멜론 아래와 같은 다른 시트의 최종 결과를 원하는 = 7

I는 I가 먼저 그들을 분리해야한다는 이해 카운트 배열 루프에 보관 그들. 하지만 어떻게해야할지 모르겠습니다. 도와주세요! 감사합니다. FIX으로 업데이트

+0

VBA가 필요한 경우 (여러 번 또는 많은 양의 데이터를 처리해야 할 필요가 있음) 데이터 원본을 검사하여 사용 가능한 형식으로 차용해야합니다. 한 열은 과일이고 다음 열은 수량입니다. 그렇게하면 인생이 극도로 단순 해지고 VBA가 전혀 필요 없습니다. – Rdster

+0

은 위의 예입니다. 원본 파일에는 csv 파일로 생성 된 많은 양의 데이터가 있습니다. 숫자를 나누어 계산하는 방법에 대한 논리를 이해하고 싶습니다. – Jane

+0

VBA를 피하려면 모든 셀을 한 열에 넣은 다음 리본의'데이터 '탭 아래에'텍스트를 열로'사용하는 것이 좋습니다. 그러면'COUNTIF()'수식을 사용할 수 있습니다. 그것은 가장 쉬운 길입니다. – Brian

답변

3
Public Function ConcatResults(rng As Range) As String 
Dim rng1 As Range, tmpArray() As String, nameArray() As String, sumArray() As Double, counter As Long 
For Each rng1 In rng 'for each cell in your range 
    If InStr(rng1.Value2, "=") > 0 Then 'if it contains an equal sign 
     tmpArray = Split(rng1.Value2, "=") 'the cell value gets split by the equal sign 
     If NameIndex(tmpArray(0), nameArray) > -1 Then 'if the fruit name is found already in the name array 
      sumArray(NameIndex(tmpArray(0), nameArray)) = sumArray(NameIndex(tmpArray(0), nameArray)) + CDbl(tmpArray(1)) 'then it adds the number to the existing name's corresponding sum 
     Else 'otherwise 
      ReDim Preserve nameArray(counter) 'it expands the array of fruit names 
      ReDim Preserve sumArray(counter) 'and the corresponding sum array 
      nameArray(counter) = tmpArray(0) 'adds the name to the last (open) place in the name array 
      sumArray(counter) = CDbl(tmpArray(1)) 'adds the name to the last (open) place in the sum array 
      counter = counter + 1 'increments the index for further potential list items 
     End If 
    End If 
Next rng1 
'exports data 
For i = LBound(nameArray) To UBound(nameArray) 'for the whole set 
    ConcatResults = ConcatResults & nameArray(i) & " = " & sumArray(i) & " " 'it concatenates [NAME] = [SUM] 
Next i 

ConcatResults = Left(ConcatResults, Len(ConcatResults) - 1) 'removes the ending space 

End Function 
Function NameIndex(str As String, arr() As String) As Long 'this function tells the index of the given string (fruit) in the [name]array 
'defaults to -1 
NameIndex = -1 
On Error GoTo err 'if the array is not yet defined it outputs the default -1 
For i = LBound(arr) To UBound(arr) 'for each item in the set 
    If arr(i) = str Then NameIndex = i 'if it's the same as the item we're looking for then outputs its index 
Next i 
err: 
End Function 

출력은 Apples = 15 Oranges = 13 Mangoes = 15 Banana = 12 Bananas = 5 Melon = 7되고, 바나나 = 5이 설명에 오타에서 유래 참고.

+0

고마워요! 미안하지만 sub() 함수를 호출하는 방법을 알려주시겠습니까? – Jane

+0

'Sub e()'/'MsgBox ConcatResults (범위 ("A2 : G8"))'/'End Sub'. 우리는 코딩 서비스가 아니라는 것을 명심하십시오. 당신은 환경에 대한 기본적인 이해와이 시점에서 당신이 달성하기를 원하는 점이 있어야합니다. 내 대답이 당신이 찾고 있던 해결책이라면, 그 것처럼 표시하십시오. 고맙습니다! – user3819867

+0

이것은 완벽하게 작동합니다. 고맙습니다! – Jane

1

는 항목을 저장하기 위해, 그렇지 않으면 내가 배열을 만들 것입니다, 범위를 벗어난 첨자와 이상을 +/- '의'

당신은 단지 당신의 예에서와 같이 5 개 항목이 제공 데리러 합계는 매번 배열을 반복하여 다음 항목이 이미 배열에 있는지 여부를 확인하여 합계를 더하고 배열에 추가합니다.

Sub test() 

Dim arr As Variant 
Dim n, Apples, Oranges, Banana, Mangoes, Melon As Integer 

Apples = 0 
Oranges = 0 
Banana = 0 
Mangoes = 0 
Melon = 0 

n = 0 
For Each Cell In Sheets(1).UsedRange.Cells 
    If IsEmpty(Cell) Then GoTo 0 

    arr = Split(Cell, "=") 

    If Left(arr(0), 5) = "Apple" Then 
    Apples = Apples + arr(1) 
    End If 

    If Left(arr(0), 6) = "Orange" Then 
    Oranges = Oranges + arr(1) 
    End If 

    If Left(arr(0), 6) = "Banana" Then 
    Banana = Banana + arr(1) 
    End If 

    If Left(arr(0), 5) = "Mango" Then 
    Mangoes = Mangoes + arr(1) 
    End If 

    If Left(arr(0), 5) = "Melon" Then 
    Melon = Melon + arr(1) 
    End If 

0 
Next 

Sheets(2).Cells(1, 2).Value = Apples 
Sheets(2).Cells(2, 2).Value = Oranges 
Sheets(2).Cells(3, 2).Value = Banana 
Sheets(2).Cells(4, 2).Value = Mangoes 
Sheets(2).Cells(5, 2).Value = Melon 

End Sub 
+0

감사하지만 원본 파일에 5 개 이상의 값이 있습니다. 방금 샘플로 게시했습니다. 특정 값을 제공하지 않으면 도움이 될 것입니다. 미리 감사드립니다! – Jane

+0

내 답변이 더 적절할 수 있습니다. 연결 섹션을 다른 시트의 셀 참조에 저장하는 것으로 변경하십시오. –