2017-10-11 2 views
-1

私は次の解決策は非常に簡単だと確信していますが、私は困っています。2つの配列の名前が一致する場合、どのようにExcelの列の値を合計するだけですか?

Excelブックで次のことを実行します。私たちは名前の範囲を持っている、と値

A1 - Alan B1 - 1 
A2 - Bob B2 - 0 
A3 - Jim B3 - 1 
A4 - Tom B4 - 2 

の範囲B列に、私は、私は列Bの値に追加する必要があり、同様のデータを別のワークブックを受けるが、列Aに言うことができます新しいブックに元のブックの名前がす​​べて含まれていない

A1 - Alan B1 - 1 
A2 - Jim B2 - 2 
A3 - Dave B3 - 1 
A4 - Tom B4 - 1 

は、私は、彼らが各ブックから列Bの合計を与えるように、列Bに元のブックの値を更新し、第2の(新しい)ワークブックの列Aから新しい名前を追加します元のワークブックの列Aの名前の範囲。

列に新しく追加さ名はAはまた、私は現在のフィルターを使用して、手動で値を更新しています列B

から関連する値を表示する必要があり、名前の範囲が大きい場合、それは時間がかかるのです、それは私を運転です怒っている...私は確かにこれにはよりエレガントなソリューションがあります。

ヘルプ?

ありがとうございます。

+1

ピボットテーブルを試しましたか? –

答えて

0

これを行う最も簡単な方法は、新しいリストを古いリストと同じワークシートに置くことだと思いました。これは、新しいリストを列Dに入れることを前提としています(newCol参照)。

新しいブックを選択してその上の特定のシートを取得する場合は、新しいブックをどのように選択するかを知っておく必要があります(ファイルセレクタ、常に特定のファイルにありますか?選択されたもの、シート名となるものなど)。

Sub AddAndAppend() 
Dim ws As Worksheet 
Dim i As Long, j As Long 
Dim origCol As Long, newCol As Long, startRow As Long 

On Error GoTo ErrorHandler 

'sets to the current worksheet 
Set ws = ActiveSheet 

'speeds up macro for longer lists 
Application.ScreenUpdating = False 
Application.Calculation = xlCalculationManual 

'assumes a header row so starts on row 2 
startRow = 2 

'origcol is where the names are to start, newcol is where the names are in the new list 
origCol = 1 
newCol = 4 

'loop through all the new names 
For i = startRow To ws.Cells(ws.Rows.Count, newCol).End(xlUp).Row 
    'if name in new list is found in old list... 
    If WorksheetFunction.CountIf(ws.Range(ws.Cells(startRow, origCol), ws.Cells(ws.Cells(ws.Rows.Count, origCol).End(xlUp).Row, origCol)), ws.Cells(i, newCol).Value) > 0 Then 
     '...find the name in the old list and combine the values 
     For j = startRow To ws.Cells(ws.Rows.Count, origCol).End(xlUp).Row 
      If ws.Cells(j, origCol).Value = ws.Cells(i, newCol).Value Then 
       ws.Cells(j, origCol + 1).Value = ws.Cells(j, origCol + 1).Value + ws.Cells(i, newCol + 1).Value 
       Exit For 
      End If 
     Next j 
    Else 
     '...otherwise, add the new name to the end of the old list 
     ws.Cells(ws.Cells(ws.Rows.Count, origCol).End(xlUp).Row + 1, origCol).Value = ws.Cells(i, newCol).Value 
     ws.Cells(ws.Cells(ws.Rows.Count, origCol).End(xlUp).Row, origCol + 1).Value = ws.Cells(i, newCol + 1).Value 
    End If 
Next i 

'turns off speeding up 
Application.ScreenUpdating = True 
Application.Calculation = xlCalculationAutomatic 
Exit Sub 

ErrorHandler: 
Application.ScreenUpdating = True 
Application.Calculation = xlCalculationAutomatic 

MsgBox Err.Number & vbCr & Err.Description 
Exit Sub 

End Sub 
関連する問題