2016-09-10 105 views
0

我有一個連接到MySQL服務器的excel工作簿。我放置了一個刷新數據的刷新按鈕,它保留對錶格的解除保護和保護。檢查DSN是否存在於excel vba

我的問題是當打開excel文件,並在不在網絡中的計算機上單擊刷新時,我得到一個DSN創建嚮導,並且如果我在嚮導中按取消,工作表變得不受保護。

我想地方檢查,如果DSN是可用IF條件,如果不是應該退出子。

任何想法?

這是我的代碼錯誤處理程序,但我仍然得到DSN創建嚮導和MSGBOX被關閉之後的紙張是不受保護

On Error GoTo handler 
Application.ScreenUpdating = False 
Sheets("DEC-2015").Unprotect Password:="password" 
ActiveWorkbook.Connections("Query from Sample").Refresh 
Sheets("DEC-2015").Protect _ 
Password:="password", _ 
UserInterfaceOnly:=True, _ 
AllowFiltering:=True, _ 
AllowSorting:=True, _ 
AllowUsingPivotTables:=True 
handler: 
MsgBox "Server Connection Lost...", vbOKOnly + vbCritical, "Warning" 
Exit Sub 
+0

只是一個嘗試,嘗試關閉警報關閉與'Application.DisplayAlerts = FALSE'。 – Gareth

+0

這樣做的伎倆,但它仍然沒有保護我的表(這是我最關心的:() – Danny

回答

0

開啓警報關閉通過改變你的代碼如下:

Public Sub DoSomething() 

    On Error GoTo handler 

    With Application 
     .ScreenUpdating = False 
     .DisplayAlerts = False 
    End With 

    With ThisWorkbook 
     .Sheets("DEC-2015").Unprotect Password:="password" 
     .Connections("Query from Sample").Refresh 
     .Sheets("DEC-2015").Protect _ 
      Password:="password", _ 
      UserInterfaceOnly:=True, _ 
      AllowFiltering:=True, _ 
      AllowSorting:=True, _ 
      AllowUsingPivotTables:=True 
    End With 

    With Application 
     .ScreenUpdating = True 
     .DisplayAlerts = True 
    End With 

    Exit Sub 

    handler: 
     ThisWorkbookSheets("DEC-2015").Protect _ 
      Password:="password", _ 
      UserInterfaceOnly:=True, _ 
      AllowFiltering:=True, _ 
      AllowSorting:=True, _ 
      AllowUsingPivotTables:=True 

     With Application 
      .ScreenUpdating = True 
      .DisplayAlerts = True 
     End With 

     MsgBox "Server Connection Lost...", vbOKOnly + vbCritical, "Warning" 

End Sub 
相關問題