無法打開另一個 Excel 文件(當一個 Excel 由 .net 打開時)
我設計了一個 .net 應用程序,它將在登錄時打開一個 Excel 文件並使用它來列印報告。註銷使用者時它將關閉。我將 Excel 文件的可見設置為 false,這樣使用者就不知道後台程序。
但是,如果有人在此期間打開任何其他 Excel 文件,我的報表 Excel 文件將變為可見並且 Excel 對象將折疊。我必須去任務管理器並殺死所有打開的 Excel 實例來解決這個問題。
程式碼:
Private Sub OK_Click(sender As Object, e As EventArgs) Handles OK.Click Try Dim dt As New DataTable() Dim Adapter As New SqlDataAdapter() ConnectMe() Dim SQLCmd As New SqlCommand("uspLogin", Con) SQLCmd.CommandType = CommandType.StoredProcedure SQLCmd.Parameters.AddWithValue("@pLoginName", UsernameTextBox.Text.Trim()) SQLCmd.Parameters.AddWithValue("@pPassword", PasswordTextBox.Text.Trim()) Adapter.SelectCommand = SQLCmd Adapter.Fill(dt) SQLCmd.Dispose() If dt.Rows.Count > 0 Then Me.Cursor = Cursors.WaitCursor Loading.Show() OpenAllTempaltes() Me.Hide() Con.Close() Me.Cursor = Cursors.Arrow Else MsgBox("Your Credential is Wrong !!!", MsgBoxStyle.OkOnly + MsgBoxStyle.Critical, "Login") UsernameTextBox.Text = "" PasswordTextBox.Text = "" UsernameTextBox.Focus() End If Catch ex As Exception Application.Exit() End Try End Sub Public Sub OpenAllTempaltes() Try xlWorkBook = xlApp.Workbooks.Open(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Templates", "Excel_Templates_GST.xlsm"), Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, True) Catch ex As Exception Throw End Try End Sub Public Sub CloseAllTempaltes() Try CleanUp(xlApp, xlWorkBook, xlWorkSheet) Catch ex As Exception ExceptionLog("PrintPage", "CloseAllTempaltes", ex.ToString(), DateTime.Now.ToString("dd-MMM-yyyy")) Finally GC.Collect() End Try End Sub我怎樣才能防止這種情況?
使用
IgnoreRemoteRequestsExcel 應用程序對象的屬性:
xlApp.IgnoreRemoteRequests = True這相當於在
File |檢查 Excel UI 選項。選項 | 高級 | 一般 | 忽略使用動態數據交換 (DDE) 的其他應用程序。
(請參閱SuperUser 上的相關答案。)
我無法使用 .NET 應用程序方便地重現您的場景,但通過後期綁定 Word VBA 中的 Excel.Application 對象執行了一些測試,它按預期工作。我創建了一個隱藏的 Excel 應用程序,並且能夠在文件資源管理器中點兩下打開文件之前和之後對其執行操作。
在我的測試中,下次我正常打開 Excel 時該設置仍未打開,但您可能希望在退出應用程序對象之前擷取其值並恢復它,以防該行為不通用。
編輯:這種行為至少從 Excel 2003 開始就存在,我使用 Excel 2016(32 位)進行了驗證。
在 Excel 2013 或更高版本中,Excel 切換到單文件界面:每個工作簿都在自己的視窗中打開。
至少到 2016 年,Visual Basic 編輯器仍然是一個多文件界面,您可以通過查看 VBE 中的 Project Explorer 窗格輕鬆查看在應用程序會話中打開了哪些文件。