I am able to save the datagridview as an excel sheet but everytime i do it,the previously saved file gets replaced which i do not want..i want the file to be saved with a new name everytime

Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
        Dim xlApp As Excel.Application
        Dim xlWorkBook As Excel.Workbook
        Dim xlWorkSheet As Excel.Worksheet
        Dim misValue As Object = System.Reflection.Missing.Value
        Dim i As Integer
        Dim j As Integer

        xlApp = New Excel.Application
        xlWorkBook = xlApp.Workbooks.Add(misValue)
        xlWorkSheet = xlWorkBook.Sheets("sheet1")

        For i = 0 To DataGridView1.RowCount - 2
            For j = 0 To DataGridView1.ColumnCount - 1
                xlWorkSheet.Cells(i + 1, j + 1) = _
                    DataGridView1(j, i).Value.ToString()
            Next
        Next
        For j = 0 To DataGridView1.ColumnCount - 1

            xlWorkSheet.Cells(1, j + 1) = DataGridView1.Columns(j).Name

        Next

        For i = 0 To DataGridView1.RowCount - 1

            For j = 0 To DataGridView1.ColumnCount - 1

                Dim cell As DataGridViewCell
                cell = DataGridView1(j, i)
                xlWorkSheet.Cells(i + 2, j + 1) = cell.Value
            Next
        Next

        xlWorkSheet.SaveAs("C:\Users\Space Era\Documents\vbexcel.xlsx")
        xlWorkBook.Close()
        xlApp.Quit()

        releaseObject(xlApp)
        releaseObject(xlWorkBook)
        releaseObject(xlWorkSheet)

        MsgBox("You can find the file C:\Users\Space Era\Documents\vbexcel.xlsx")
    End Sub

If you want to use a different file name then you have to generate a new name for the SaveAs. For example, you might want to generate numbers 0001, 0002, etc and append to "vbexcel" to create vbexcel0001.xlsx, vbexcel0002.xlsx, etc. Or you could generate a name like "vbexcel-yyyy-mm-dd-hh-mm.xlsx" using the current date & time. Using the date/time tag should ensure you don't have duplicate file names (but it still wouldn't hurt to check before you save). You can generate a name as

Dim filename As String = "vbExcel-" & Now().ToString("yyyy-MM-dd-HH-mm-ss") & ".xlsx"

Edited 4 Years Ago by Reverend Jim: n/a

I need to make changes to the following line so as to save it with a different name
xlWorkSheet.SaveAs("C:\Users\Space Era\Documents\vbexcel.xlsx")
how can i implement your idea here

Dim filename As String = "vbExcel-" & Now().ToString("yyyy-MM-dd-HH-mm-ss") & ".xlsx"
xlWorkSheet.SaveAs("C:\Users\Space Era\Documents\" & filename)

This question has already been answered. Start a new discussion instead.