Option Explicit
Const Folder As String = "d:\goo\data2"
Const BookName As String = "Book1.xlsx"
Const SheetName As String = "Sheet1"
Const MarginRow As Long = 3 '製品名開始直前迄の行
Public Sub 日付数量抽出()
Dim wb As Workbook '入力ブック
Dim ws As Worksheet '入力ブックの入力シート
Dim ws2 As Worksheet '出力シート
Dim maxrow As Long '入力シート最大行数
Dim maxrow2 As Long '出力シート最大行数
Dim pcount As Long '製品件数
Dim wrow As Long '入力シート行番号
Dim wcol As Long '入力シート列番号
Dim wrow2 As Long '出力シート行番号
Dim wcol2 As Long '出力シート列番号
Dim i As Long '製品番号
Dim ctr As Long '登録数量カウンタ
Dim pname As String '製品名
Dim comment As String 'コメント(W列)
Set ws2 = Worksheets("Sheet2")
'入力ファイルオープン
Set wb = Workbooks.Open(Folder & "\" & BookName)
Set ws = wb.Worksheets(SheetName)
maxrow = ws.Cells(Rows.Count, "G").End(xlUp).Row 'G列の最大行取得
'11行未満の場合
If maxrow < MarginRow + 8 Then
MsgBox ("製品名なし")
Exit Sub
End If
'製品件数算出
pcount = (maxrow - MarginRow) \ 8
If (maxrow - MarginRow) Mod 8 <> 0 Then
MsgBox ("終端行不正")
Exit Sub
End If
'出力シートクリア
maxrow2 = ws2.Cells(Rows.Count, "D").End(xlUp).Row 'D列の最大行取得
If maxrow2 > 2 Then
ws2.Range("D3:D" & maxrow2).ClearContents
ws2.Range("AD3:AG" & maxrow2).ClearContents
End If
wrow2 = 3
'製品件数分繰り返す
For i = 1 To pcount
'数量記入行を決定
wrow = (i - 1) * 8 + MarginRow + 5
pname = ws.Cells(wrow, "G").Value
comment = ws.Cells(wrow, "W").Value
'W列にExpiryがない場合はエラー
If InStr(1, comment, "Expiry", 1) = 0 Then
MsgBox (wrow & "行 W列 Expiryなし")
Exit Sub
End If
ws2.Cells(wrow2, "D").Value = pname '製品名
ctr = 0
'Y列~BT列まで繰り返す
For wcol = 25 To 72
'数量が登録されていれば、Sheet2へ転記
If ws.Cells(wrow, wcol) <> "" Then
wcol2 = 30 + ctr * 2
ws2.Cells(wrow2, wcol2).Value = ws.Cells(3, wcol).Value '日付
ws2.Cells(wrow2, wcol2 + 1).Value = ws.Cells(wrow, wcol).Value '数量
ctr = ctr + 1
End If
Next
'数量が1件も登録されていない場合
If ctr = 0 Then
ws2.Cells(wrow2, "AD").Resize(, 4).Value = "-"
End If
wrow2 = wrow2 + 1
Next
wb.Close
MsgBox ("完了")
End Sub