我有一个Excel 2007工作簿,我正在使用它连接到MSSQL 2008服务器以下拉一些名称,我能够成功地实现这一点。我的问题是,我希望使用从SQL Server获取的名称创建新的工作表。
有没有人能指出我的代码有什么问题,或者解释这个错误的含义和解决方法?我的代码在将activesheet重命名为数组中的名称的行上出错。如果要将名称设为I的值,则会重命名activesheet。
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
任何人能提供的任何帮助都将不胜感激。
谢谢