Search code examples
excelexcel-2010vb.net-2010vba

Connecting two path strings to get the final path?


I'm trying to save excel file into a specific path. So basically, when I click the button, I'm creating a folder, and want to save the file inside that folder. The created folder has the current month as name. I'm trying to save into that current month folder.

    'Create folder as Month Name. Save filename as date inside "month".
    Dim sDate As String = DateTime.Now.ToString("yyyy-MM-dd") & "_" & DateTime.Now.ToString("HH-mm-ss")
    Dim sMonth As String = DateTime.Now.ToString("MMMM")
    Dim sFolder = Application.StartupPath & "\Resources\Excel\"


    My.Computer.FileSystem.CreateDirectory(sFolder & Format(sMonth))

    Dim sfinal = Path.Combine(sFolder, sMonth)
    xlSh.SaveAs(sfinal & Format(sDate) & ".xlsx")

    xlApp.Workbooks.Close()
    xlApp.Quit()

As it is, this code doesn't give me any errors. But instead of creating a folder named "March" <-current month and saving inside it, it saves the file in \Excel\ and it also creates folder in the same place.


Solution

  • After long hours of excruciating pain, I've finally did it! Apparently I was missing an "\" Since "sMonth" became dynamic name, which later I wanted to use as path, and save files in that folder. I needed to simply put that "\" after sMonth, to tell it to save inside it.

    Before I realize this... I've broken down, simplified the code as much as I could so I can logically connect the pieces. What I ended up with, is something slightly different. Now the SaveAS properly saves the file inside the new folder.

        Dim sDate As String
        sDate = DateTime.Now.ToString("yyyy-MM-dd") & "_" & DateTime.Now.ToString("HH-mm-ss")
    
        Dim sMonth As String
        sMonth = DateTime.Now.ToString("MMMM")
    
        Dim sFileName As String
        sFileName = sDate + ".xlsx"
    
        Dim sFolder As String
        sFolder = Application.StartupPath & "\Resources\Excel\"
    
    
        Dim sfinal As String
        sfinal = (sFolder & sMonth & "\") '<- this thingie here o.O
    
        My.Computer.FileSystem.CreateDirectory(sFolder & Format(sMonth))
    
        xlSh.SaveAs(sfinal & Format(sFileName))
    
        xlApp.Workbooks.Close()
        xlApp.Quit()
    

    Thanks for the help.