Sub Main
    
    'Clear any output in the Immediate window
    Debug.Clear
    
    'Initialize Surfer
    Dim SurferApp As Object
    Set SurferApp = CreateObject("Surfer.Application")
    SurferApp.Visible = True

    '===============================================
    'USER-DEFINED VARIABLES
    '===============================================
    'Directory containing all of your data files
    fileDirectory = "C:\Temp\"
    
    'Name of the new, combined output file
    outputFileName = "combined_data.dat"
    
    'File extension to search for (without the dot)
    fileExtension = "dat"
    '===============================================

    'Create a new worksheet to hold the combined data
    Dim Wks As Object
    Set Wks = SurferApp.Documents.Add(DocType:=srfDocWks)

    'Ensure the directory path ends with a backslash
    If Right(fileDirectory, 1) <> "\" Then
        fileDirectory = fileDirectory + "\"
    End If

    'Find the first data file in the directory
    dataFileName = Dir(fileDirectory + "*." + fileExtension)
    
    'Initialize the row counter for importing data
    importRow = 1
    fileCount = 0

    'Loop through all data files in the specified directory
    While dataFileName <> ""
        
        'Display progress information
        fileCount = fileCount + 1
        Debug.Print "Processing file " + Str(fileCount) + ": " + dataFileName

        'Merge the current data file into the worksheet
        Wks.Merge(FileName:=fileDirectory + dataFileName, _
                    Row:=importRow, Col:=1)

        'Update the import row for the next file
        importRow = Wks.UsedRange.LastRow + 1

        'Get the next data file in the directory
        dataFileName = Dir()
    Wend

    'Check if any files were processed
    If fileCount = 0 Then
        MsgBox "No files with extension '" + fileExtension + "' found in directory: " + fileDirectory, _
               vbExclamation, "No Files Found"
        Exit Sub
    End If

    'Save the combined data file
    outputFilePath = fileDirectory + outputFileName
    Wks.SaveAs(FileName:=outputFilePath, FileFormat:=srfSaveFormatDat)
    
    'Display completion message
    MsgBox "Successfully combined " + Str(fileCount) + " files into: " + outputFilePath, _
           vbInformation, "Files Combined"
    
    Debug.Print "Script completed successfully!"

End Sub
