【发布时间】:2010-11-18 00:57:56
【问题描述】:
我有一个 Excel 2007 工作簿,用于连接到 MSSQL 2008 服务器以提取一些名称,我能够成功实现这一点。我的问题是我想要使用从 SQL Server 获得的名称创建新的工作表。
我已经能够创建一个结果数组并遍历该数组创建一个新工作表,但不能让它重命名工作表,VB 返回 1004 的运行时错误:应用程序定义或对象定义错误.我创建了一个 msgbox,将数组结果输出为 Im 迭代它,并且在 msgbox 中显示的名称是正确的并且数量正确。
是否有人能够指出我的代码有任何问题,或者解释一下这个错误的含义以及如何解决它?我的代码在将活动表重命名为数组中的名称的行上出错。如果我要将名称设为 i 的值,则活动表将被重命名。
这是我正在使用的代码:
Public Sub Dataextract()
' Create a connection object.
Dim cnPubs As ADODB.Connection
Set cnPubs = New ADODB.Connection
' Provide the connection string.
Dim strConn As String
strConn = "Source=OLEDB;Provider=SQLOLEDB.1;Integrated Security=SSPI;" _
"Persist Security Info=True;Data Source={REMOVED};"
'Now open the connection.
cnPubs.Open strConn
' Create a recordset object.
Dim rsPubs As ADODB.Recordset
Set rsPubs = New ADODB.Recordset
With rsPubs
' Assign the Connection object.
.ActiveConnection = cnPubs
' Extract the required records.
' The Select Query to display the data
.Open "SELECT DISTINCT [databaseName] FROM [DBMonitor].[dbo].[dbGrowth]"
' Copy the records into cell A2 on Sheet1.
'Sheet1.Range("A2").CopyFromRecordset rsPubs
vArray = rsPubs.GetRows()
rowsreturned = UBound(vArray, 2) + 1
For i = 0 To rowsreturned - 1
' Added the following to see if it errors anywhere else, or if it is
' just the one record.
'On Error Resume Next
Sheets.Add After:=Sheets(Sheets.Count)
' FAILS HERE....
ActiveSheet.Name = vArray(0, i)
MsgBox (i & " " & vArray(0, i))
Next i
' Tidy up
.Close
End With
cnPubs.Close
Set rsPubs = Nothing
Set cnPubs = Nothing
End Sub
任何人都可以提供任何帮助,我们将不胜感激。
谢谢,
马特
【问题讨论】: