我正在创建一个宏来将 Excel 工作表连接到 SQL 服务器。excel 文件将在我在家和在外面时使用。现在一切都在处理我的 DNS www.server1.com。
现在,如果由于某种原因服务器 1 不工作,我想访问第二个备份服务器 www.server2.com
问题是我无法处理错误。在“Cn.Open ....”之后,如果它无法与服务器通信,宏将停止,我收到excel错误:“运行-rime错误:'-2147467259(80004005)”
我希望不是返回这个错误,我可以用类似的东西手动处理错误: If Cn.Error Then Server_Name = "www.server2.com" etc ...
我怎样才能做到这一点?
Server_Name = "www.server1.com" ' Enter your server name here
Port = "3306"
Database_Name = "mydb" ' Enter your database name here
User_ID = "myuserid" ' enter your user ID here
Password = "mypassword" ' Enter your password here
Dim Cn As ADODB.Connection
Set Cn = New ADODB.Connection
Cn.Open "Driver={MySQL ODBC 5.3 ANSI Driver};Server=" & Server_Name & ";PORT=" & Port & ";Database=" & Database_Name & ";Uid=" & User_ID & " ;Pwd=" & Password & ";"
On Error ...
如果已连接,则需要在下一行添加一个和测试;如果不是,请连接到您的备份服务器。最后,停用错误处理。
Dim Cn As ADODB.Connection
Set Cn = New ADODB.Connection
On Error Resume Next
Cn.Open "Driver={MySQL ODBC 5.3 ANSI Driver};Server=" & Server_Name & ";PORT=" & Port & ";Database=" & Database_Name & ";Uid=" & User_ID & " ;Pwd=" & Password & ";"
if Cn.State = 0 Then : _
Cn.Open ... 'Backup connection
On Error Goto 0
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句