Option Explicit
Const RESTCOL As String = "E" 'Aシート作業列
Dim ws1 As Worksheet 'Aシート
Dim ws2 As Worksheet 'Bシート
Dim dicST As Object '連想配列 キー:車種 値:最初に出現する行番号(Aシート)
Dim dicEN As Object '連想配列 キー:車種 値:最後に出現する行番号(Aシート)
Dim Arr As Variant 'Bシートイメージ保存
Dim row2 As Long 'Bシート 行番号
Public Sub 転記()
Dim maxrow1 As Long '最大行数 Aシート
Dim maxrow2 As Long '最大行数 Bシート
Dim row1 As Long '行番号 Aシート
Dim ix As Long 'Arr 添え字
Dim key As String '車種
Set ws1 = Sheets("A")
Set ws2 = Sheets("B")
Set dicST = CreateObject("Scripting.Dictionary") ' 連想配列の定義
Set dicEN = CreateObject("Scripting.Dictionary") ' 連想配列の定義
maxrow1 = ws1.Cells(Rows.Count, 1).End(xlUp).Row 'A列の最大行取得
maxrow2 = ws2.Cells(Rows.Count, 4).End(xlUp).Row 'D列の最大行取得
'最大行数が要件を満たしてないなら処理しない
If maxrow1 < 5 Then Exit Sub
If maxrow2 < 5 Then Exit Sub
'Bシートを配列へ転送
Arr = ws2.Range("A5:Z" & maxrow2).Value
'Bシート 5行以降をクリア
ws2.Rows("5:" & Rows.Count).ClearContents
row2 = 5
'車種を取り込む
For row1 = 5 To maxrow1
key = ws1.Cells(row1, "A").Value
ws1.Cells(row1, RESTCOL).Value = ws1.Cells(row1, "D").Value '作業用在庫
If dicST.exists(key) = False Then
dicST(key) = row1
dicEN(key) = row1
Else
If dicEN(key) + 1 <> row1 Then
ws1.Activate
ws1.Cells(row1, "A").Select
MsgBox ("車種が連続していません")
Exit Sub
End If
dicEN(key) = row1
End If
Next
'Arrを1列毎に処理する。
For ix = 1 To UBound(Arr, 1)
'転記処理(Bシートの行番号)
Call tenki(ix)
Next
ws1.Range(RESTCOL & "5:" & RESTCOL & maxrow1).ClearContents '作業列クリア
MsgBox ("完了")
End Sub
'転記処理 ix:Arrの添え字
Private Sub tenki(ByVal ix As Long)
Dim rcnt As Long '該当者車種の行数(Aシート)
Dim srow1 As Long '該当車種の開始行(Aシート)
Dim key As String '車種
Dim rest As Variant '受注残
Dim row1 As Long '行番号 Aシート
Dim temp As Variant
'Bシートの1行分(A~Z)をArrから転送
temp = WorksheetFunction.Index(Arr, ix)
ws2.Cells(row2, 1).Resize(1, 26).Value = temp
rest = Arr(ix, 8) '受注残
key = Arr(ix, 4) '車種
'Aシートに未登録なら終了
If dicST.exists(key) = False Then
GoTo FIN99
End If
'該当車種の行を繰り返す
For row1 = dicST(key) To dicEN(key)
'在庫がない製造番号はスキップする
If ws1.Cells(row1, RESTCOL).Value = 0 Then GoTo NEXT99
'受注残が0なら終了
If rest = 0 Then Exit For
ws2.Cells(row2, "J").Value = ws1.Cells(row1, "C").Value '製造NO
If ws1.Cells(row1, RESTCOL).Value >= rest Then
ws2.Cells(row2, "K").Value = rest '在庫
ws1.Cells(row1, RESTCOL).Value = ws1.Cells(row1, RESTCOL).Value - rest '在庫残
rest = 0 '受注残
Else
ws2.Cells(row2, "K").Value = ws1.Cells(row1, RESTCOL).Value '在庫
rest = rest - ws1.Cells(row1, RESTCOL).Value '受注残
ws1.Cells(row1, RESTCOL).Value = 0 '在庫残
End If
row2 = row2 + 1
NEXT99:
Next
FIN99:
row2 = row2 + 1
End Sub