我正在尝试制作一个包含两个TextBox和一个按钮的Windows窗体应用程序。
我希望能够自动写入Excel电子表格,但也可以手动编写(不是通过程序,而是在运行时)。所有这些都有效。我遇到的问题是当我打开表单并且电子表格已经打开时,它会创建一个只读副本并将其保存在Excel的默认位置(当尝试保存更改时,它有时会出现问题)。问题是App.Workbooks.Open
代码行。如果电子表格已经打开,是否可以替代Open
?
您可以通过“引用”而不是再次打开文档来写入Excel吗?
这是我的代码:
Imports Excel = Microsoft.Office.Interop.Excel
Dim App As New Excel.Application
Dim Worksheet As Excel.Worksheet
Dim Workbook As Excel.Workbook
Public Function LookForSpace()
Dim IsBlank As Boolean
Dim Counter As Integer
IsBlank = False
Counter = 1
While IsBlank = False
Workbook.Save()
If CStr(Worksheet.Cells(Counter, 1).Value) = "" And CStr(Worksheet.Cells(Counter, 2).Value) = "" Then
IsBlank = True
Else
Counter = Counter + 1
End If
End While
Return Counter
End Function
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Try
Workbook = App.Workbooks.Open("Path\example.xlsx")
Catch
MsgBox("Dokument nicht gefunden")
Me.Close()
End Try
Try
Worksheet = Workbook.Worksheets("Tabelle1")
App.Visible = True
Catch
MsgBox("Tabelle nicht gefunden!")
Me.Close()
End Try
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim YIndex As Integer
YIndex = LookForSpace()
Worksheet.Cells(YIndex, 1).Value = TextBox1.Text
Worksheet.Cells(YIndex, 2).Value = TextBox2.Text
Workbook.Save()
End Sub
LookForSpace函数只检查要写入的新行。
如果不清楚,请告诉我,因为我不是母语为英语的人。
任何帮助都会受到赞赏,因为我已经持续了一个星期了!