我在Visual Studio 2013中創建了一個表單,用於同時在多個用戶的Excel中輸入數據。除非兩個用戶同時打開表單,或者點擊了提交併且表單仍在處理,否則會發生錯誤。寫入excel和只讀屬性vb.net
未處理的異常發生在您的應用程序。來自HRESULT的例外:0x800A03EC
將數據寫入文件時,我想讓它只讀,以便其他用戶可以等待。我該怎麼做呢?
Imports excel = Microsoft.Office.Interop.Excel
Imports System.Runtime.InteropServices
Public Class Form1
Dim xlapp As New excel.Application
Dim workbook As excel.Workbook
Dim worksheet As excel.Worksheet
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
workbook = xlapp.Workbooks.Open("\2.xlsx")
xlapp.Visible = False
worksheet = workbook.Sheets("sheet1")
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
If workbook.MultiUserEditing Then
workbook.AcceptAllChanges()
workbook.Save()
End If
Dim row As Long
Dim alpha As Long = 0
row = 5
With worksheet
Do While .Cells(row, 4).value IsNot Nothing
row = row + 1
Loop
.Cells(row, 2).value = Me.fname.Text
.Cells(row, 3).value = Me.lname.Text
Me.fullname.Text = Me.fname.Text + Me.lname.Text
.Cells(row, 4).value = Me.fullname.Text
End With
xlapp.DisplayAlerts = False
workbook.SaveAs("\2.xlsx", AccessMode:=excel.XlSaveAsAccessMode.xlShared)
End Sub
End Class
你有沒有考慮製作的Excel文件的模板? – JohnG
這是什麼意思?對不起,我對這一切都不知道 – user5538704
模板文件就像只讀文件。例如:當您使用'workbook = xlapp.Workbooks.Open(「\ 2.xlsx」)打開一個常規的excel文件時,這會打開文件並保持打開狀態,直到用戶關閉它爲止。另一方面,模板將簡單地將自身作爲新文件複製到用戶「Document1」並關閉模板。然後,當用戶嘗試保存該文件時,系統會提示他們爲其提供文件名,因爲該模板已關閉。那麼用戶在同一時間抓取文件的可能性就會降低。 – JohnG