我在Visual Studio 2013中创建了一个表单,用于同时由多个用户在Excel中输入数据。它工作得非常好,除非两个用户同时打开表单或者如果一个用户单击提交并且表单仍处理,则会发生错误。
您的应用程序中发生了未处理的异常。来自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
答案 0 :(得分:0)
你想要的是,文件应该是互相排斥的,即如果某人打开它进行写作,其他人就无法打开它进行编辑。 解决此问题的一个简单方法是,每当用户打开文件时都会跟踪它。这可以通过在DB或文件系统中跟踪表来实现。
filename
文件夹中是否存在Lock
的空文件。如果文件存在,请将标签的文本设置为" Read only
"并且不允许保存。如果文件不存在,请在filename
文件夹中创建一个Lock
的空文件,并允许保存。保存/关闭表单时从文件夹中删除此文件。 更新了文件系统方法: - 以下是向您展示的方法。我没有编译代码。请原谅我。
---代码低于---
Dim lockFile As String ' form/class level variable
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles Me.Load
Dim filename As String = "2.xlsx"
Dim sharedFolder As String = "\\ComputerABC\XL_FILE_FOLDER\LOCK\"
lockFile = sharedFolder + filename
If (System.IO.File.Exists(lockFile)) Then
Me.lblAccess.Visible = True
Me.lblAccess.Text = "Read-Only Access. Data cannot be saved."
Else
IO.File.Create(lockFile).Dispose() 'create empty file
Me.lblAccess.Visible = False
End If
Me.Button1.Enabled = Not Me.lblAccess.Visible
workbook = xlapp.Workbooks.Open("\" + filename)
xlapp.Visible = False
worksheet = workbook.Sheets("sheet1")
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
:
:
:
If Not lblAccess.Visible Then
workbook.SaveAs("\2.xlsx", AccessMode:=excel.XlSaveAsAccessMode.xlShared)
System.IO.File.Delete(lockFile)
lockFile = ""
End If
End Sub