【VBA】Create Excel file

You can create Excel file!

PR

VBA Code

As an example, Create Excel file “hogehoge.xlsx”.

Option Explicit

Sub sample()

    Dim excelFilePath As String
    Dim sheetName As String
    Dim fso As Object
    Dim wb As Workbook
    Dim ws As Worksheet
    
    Application.ScreenUpdating = False
    
    'Set "File path you want to create"
    excelFilePath = "C:\Users\user\Desktop\hogehoge.xlsx"
    'シート名
    sheetName = "sample"
    
    Set fso = CreateObject("Scripting.FileSystemObject")
    
    'File existence check
    If Not fso.FileExists(excelFilePath) Then
        'Create a new book
        Set wb = Workbooks.Add
        'Change sheet name
        Set ws = wb.Sheets(1)
        ws.Name = sheetName
        'Write in cell "B2"
        ws.Range("B2") = "Write from VBA."
        'Save Book
        wb.SaveAs excelFilePath
        'Close Book
        wb.Close
        
        MsgBox "New Excel file created."
    Else
        MsgBox "Stopped creating Excel file."
    End If
    
    Application.ScreenUpdating = True
    
End Sub

Set “File path you want to create”(Line 14).

PR

Result

You created Excel file!

Result①
Result①
Result②
Result②
PR

FYI

For more information about following, see the following official online manual:

Add method” of “Workbooks Object”


Sheets property” of “Workbook Object”


Name property” of “Worksheet Object”


Range property” of “Worksheet Object”


SaveAs method” of “Workbook Object”


Close method” of “Workbook Object”

タイトルとURLをコピーしました