初回ポスター、長時間の読者。Excel VBAで複数の列に均等に要素を均等に分散する
これに従わないとお詫び申し上げます。
私には名字と姓のリストを持つスプレッドシートがあります。私がしたいのは、同じ姓を持ち、同じスプレッドシート内の3つの参照列に等間隔に置かれ、コンマで区切られた最初のすべての名前を取ることです。
200+の名前と成長があるので、私はVBAでこれをやりたい、と後でコードは、より多くのワークブックを作成し、移入するために、この情報を使用します。
これまでのところ、3つ以下のファーストネーム(すなわち、1つのカラムあたり1つ)を持つすべての姓に対して機能していますが、3つ以上のファーストネームがある姓の場合は機能しません。
私は、すべての名前を配列に読み込み、3つ以上の名前を持つ要素を別の配列に分割し、これらを一緒に結合してコンマで区切って、シートの関連する列に転送することを考えました。
しかし何らかの理由で、複数の名前を列に出力することができません。
私はこれでいくつかの試みをしましたが、これは私の最近の試みです。
Private Sub cmdUpdate_Click()
Dim i As Long
Dim j As Long
Dim k As Long
Dim l As Long
Dim m As Long
Dim namesPerCol As Long
Dim strLastNameMatches As String
Dim arrNames() As String
Dim arrMultiNames(3) As String
Application.ScreenUpdating = False
With ActiveSheet
'Finds the last row with data in it
lngLastRow = .Cells(.Rows.count, "A").End(xlUp).Row
End With
'Sort the Columns
Columns("A:E").Sort key1:=Range("A1"), Header:=xlYes
'Loop through the LastNames
For i = 2 To lngLastRow
'Second loop through the LastNames
For j = 2 To lngLastRow
'If the last name matches
If Cells(i, 2).Value = Cells(j, 2).Value Then
'If the cell is empty then
If Range("C" & i).Value = "" Then
'Place the name in colA into colC
Range("C" & i).Value = Range("A" & j).Value
Else
'If the cell is not empty, then place a comma and space and then the value from colA
Range("C" & i).Value = Range("C" & i).Value & ", " & Range("A" & j).Value
End If
End If
Next j
Next i
For i = 2 To lngLastRow
strLastNameMatches = Range("C" & i).Value
arrNames = Split(strLastNameMatches, ", ")
If UBound(arrNames) > 2 Then
namesPerCol = UBound(arrNames)/3
For l = 0 To 1
For k = LBound(arrNames) To namesPerCol
arrMultiNames(l) = arrNames(k) & ", "
Next k
Next l
For m = LBound(arrMultiNames) To UBound(arrMultiNames)
Select Case m
Case 0
Range("C" & i).Value = arrMultiNames(m)
Case 1
Range("D" & i).Value = arrMultiNames(m)
Case 2
Range("E" & i).Value = arrMultiNames(m)
End Select
Next m
Else
For j = LBound(arrNames) To UBound(arrNames)
Select Case j
Case 0
Range("C" & i).Value = arrNames(j)
Case 1
Range("D" & i).Value = arrNames(j)
Case 2
Range("I" & i).Value = arrNames(j)
End Select
Next j
End If
Next i
Application.ScreenUpdating = True
End Sub
悪い品質のコーディングのお詫びは、私はそれがすべて動作したらそれをあきらめて作業します。
私は均等に3列にわたって名前をこのコード分割を出すために得ることができるすべてのヘルプは非常にあなたがより多くのツリー構造にデータを保存することができれば、この作業は単純かもしれません
あなたはなぜ各列に2つの名前をグループ化します。 C1 =ジョン、D1 =ダビデ、E1 =ジョージ、F1 =サラ、G1 =メアリー、H1 =エリザベス?それは容認できる解決策ですか? –
申し訳ありませんが、このデータは他のユーザーによって3つの参照フィールドしかない別のアプリケーション(私たちによって管理されていない)にコピーされるので、3つのフィールドに名前を分割する必要があります。 – ItsNotGoneWell