0
0

ChatGPTでExcel VBAのコード生成

Last updated at Posted at 2024-04-16

個人メモ

複数のブックのSheet3のデータを1つのブックにまとめるVBAコードをChatGPTで作成。

このコードは、フォルダ内のすべてのExcelファイルを処理し、それぞれのSheet3からデータを取得して、1つの新しいブックに統合する。

手順1
同じフォルダに全てのデータをまとめる。

手順2
以下のコードをコピペ。
適宜修正。

Excel VBA
Sub CombineSheet3Data()
    Dim myPath As String
    Dim myFile As String
    Dim currentWb As Workbook
    Dim newWb As Workbook
    Dim lastRow As Long
    Dim i As Long
    
    '新しいブックを作成します
    Set newWb = Workbooks.Add
    
    'マクロが保存されているフォルダのパスを取得します
    myPath = ThisWorkbook.Path
    
    'マクロが保存されているフォルダ内のExcelファイルを処理します
    myFile = Dir(myPath & "¥*.xls*")
    Do While myFile <> ""
        'ファイルがExcelファイルであることを確認します
        If myFile <> ThisWorkbook.Name Then
            'Excelファイルを開きます
            Set currentWb = Workbooks.Open(myPath & "¥" & myFile)
            
            'Sheet3のデータを取得します
            With currentWb.Sheets("Sheet3")
                lastRow = .Cells(.Rows.Count, 1).End(xlUp).Row
                If lastRow > 0 Then
                    .Range("A1").CurrentRegion.Copy Destination:=newWb.Sheets(1).Cells(i + 1, 1)
                    i = i + lastRow
                End If
            End With
            
            'Excelファイルを閉じます(保存しない)
            currentWb.Close False
        End If
        
        '次のExcelファイルを処理します
        myFile = Dir
    Loop
    
    '新しいブックをアクティブにします
    newWb.Activate
    
    '統合した行数を表示します
    MsgBox "統合された行数: " & i, vbInformation
End Sub

おまけ
連番のみが降ってある場合に、空白を消去するコード

Excel VBA
Sub 空白消去()
    
    For i = 50 To 1 Step -1
        If Cells(i, 2).Value = "" Then
             Rows(i).Delete
        End If
    Next i

End Sub
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0