簡體   English   中英

Excel 2007 VBA - 運行時錯誤1004

[英]Excel 2007 VBA - Run Time Error 1004

我有一個Excel 2007工作簿,我用它連接到MSSQL 2008服務器以下拉一些名稱,我能夠成功實現這一點。 我的問題是我希望從它從SQL Server獲取的名稱創建新的工作表。

我已經能夠創建一個結果數組並遍歷數組創建一個新工作表,但不能讓它重命名工作表,VB返回運行時錯誤1004:應用程序定義或對象定義錯誤。 我已經創建了一個msgbox,它輸出數組結果,因為我迭代它並且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

任何人都可以提供的任何幫助將不勝感激。

謝謝,

馬特

設置名稱的三個想法可能會失敗:

  1. 您的工作簿中是否已經有一張帶有該名稱的工作表?
    嘗試設置已在使用的名稱將導致'1004'

  2. 也許您嘗試設置的名稱包含一些非法字符:
    : / \\ * ? [ ] : / \\ * ? [ ]是不允許的

  3. 也不允許使用空字符串或超過31個字符的字符串

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM