如何永久保存通过vb.net用户窗体输入到excel中的数据,而无需输入新数据替换以前的数据

时间:2019-04-27 03:01:28

标签: vb.net

我创建了一个vb.net用户窗体,该窗体将数据馈入excel。但是问题是,每当我输入新数据时,以前的数据都将被新数据替换而没有任何检索方法。所以我的观点是;我想要工作表上显示的是先前输入的数据和新输入的数据。我确实需要代码来解决此问题。还需要显示用于在DataGridView中输入的相同数据的代码。预先感谢!

Private Sub BtnAddRecord_Click(sender As Object, e As EventArgs) Handles BtnAddRecord.Click
    Dim AppExcel As New Excel.Application 'Create a new Excel Application
    Dim workbook As Excel.Workbook = AppExcel.Workbooks.Add("C:\Users\DELL\OneDrive\Documents\VbNetFormDone.xlsx") ' 'Create a new workbook
    Dim sheet As Excel.Worksheet = workbook.Sheets("Sheet1") ' Create variable a Sheet, Sheet1 must be in WorkBook
    AppExcel.Visible = True
    AppExcel.DisplayAlerts = False
    'Work with range'

    Dim AddNew As Range
    AddNew = sheet.Range("A65356").End(XlDirection.xlUp).Offset(1, 0)


    'Range with text address
    AddNew.Offset(0, 0).Value = TextReferenceNo.Text
    AddNew.Offset(0, 1).Value = TextFirstname.Text
    AddNew.Offset(0, 2).Value = TextSurname.Text
    AddNew.Offset(0, 3).Value = TextAddress.Text
    AddNew.Offset(0, 4).Value = TextPostalCode.Text
    AddNew.Offset(0, 5).Value = TextTelephone.Text
    AddNew.Offset(0, 6).Value = TextDateOfReg.Text
    AddNew.Offset(0, 7).Value = TextProveOfId.Text
    AddNew.Offset(0, 8).Value = TextMemberType.Text
    AddNew.Offset(0, 9).Value = TextMemberFees.Text


    workbook.SaveAs("C:\Users\DELL\OneDrive\Documents\VbNetFormDone.xlsx", FileFormat:=56) 'Save the workbook
    workbook.Close() 'Close workbook
    AppExcel.Quit() 'Quit the application

1 个答案:

答案 0 :(得分:0)

似乎您每次都在创建一个新的Excel工作簿。这就是为什么您的新数据会覆盖旧数据的原因。

尝试更改此行以打开工作簿,而不是创建一个新工作簿。

#innodb_force_recovery = 1

参考文献:
Dim workbook As Excel.Workbook = AppExcel.Workbooks.Open("C:\Users\DELL\OneDrive\Documents\VbNetFormDone.xlsx")
https://docs.microsoft.com/en-us/office/vba/api/excel.workbooks.add

Add()
https://docs.microsoft.com/en-us/office/vba/api/Excel.Workbooks.Open