Search code examples
excelvbaxlsx

Why is the new file corrupting?


I create a file, and let the user choose at what location.
The file is named with the current date, and the project number.

After that I want to print a cell with Hello world. I dont know if this part works, because I can't open the file. It is corrupt.

'*************************************************************************************************************************************************************************************
'* Folder creater.
'*************************************************************************************************************************************************************************************
Option Explicit

Sub Acto_Export()
        
    Dim sFolder As String
    Dim ws As Worksheet
    Set ws = ThisWorkbook.Sheets("Systems")
  
    With Application.FileDialog(msoFileDialogFolderPicker)
        If .Show = -1 Then ' if OK is pressed
            sFolder = .SelectedItems(1)
        End If
    End With
    If sFolder = "" Then  ' if an error occured
        MsgBox ("no folder was selected")
        Exit Sub
    End If

    Dim ProjectNumber As String
    ProjectNumber = Blad1.Cells(8, 4).Value

    Dim ExportFileName As String
    ExportFileName = sFolder & "\" & Format(Now, "yyyy-MM-dd_HHmmss_") & ProjectNumber & "_importfileActo.xlsx"

    Open ExportFileName For Output As #1
    Cells(1, 1).Value = "Hello world"

End Sub

I think the problem is at the naming of the file. I tried exporting it as a .TXT file and have it just print hello world, but then the file remains empty.


Solution

  • You should replace

    Open ExportFileName For Output As #1
    

    with

    Workbooks.Add
    ActiveWorkbook.SaveAs ExportFileName
    

    The Open is used for outputting to text-files and uses typically Write or Print "hello world", #1 to output the text to the textfile.

    Cells(1,1).Value="Hello World" will work with having a new workbook open