代码之家  ›  专栏  ›  技术社区  ›  Lima

Excel 2007 VBA-运行时错误1004

  •  3
  • Lima  · 技术社区  · 16 年前

    我有一个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
    

    任何人能提供的任何帮助都将不胜感激。

    谢谢

    1 回复  |  直到 8 年前
        1
  •  4
  •   Treb    16 年前

    设置名称可能失败的三个原因:

    1. 您的工作簿中是否已有同名的工作表?

    2. 您试图设置的名称可能包含一些非法字符:
      : / \ * ? [ ] 不允许

    3. 也不允许使用空字符串或超过31个字符的字符串