2013-07-17 165 views
3

我創建了Excel的加載項,它確定了ActiveSheetActiveWorkbook的名稱。我使用的代碼如下。當我運行加載項時,它在消息框「變量集」之後顯示上述錯誤。但是當我在宏中運行它時,它工作正常。我不明白加載項發生了什麼。任何人都可以幫助我嗎?獲取錯誤「對象變量或未設置塊變量」

Sub sheetvalues() 
    Dim bk As Workbook, sht1 As Worksheet, sht2 As Worksheet, sht3 As Worksheet 
    Dim book As String, sht As String, i As Integer, j As Integer 
    Dim att(1 To 4) As String, att_col(1 To 4) As Integer 

    MsgBox ("variables set") 

    book = ActiveWorkbook.Name 
    sht = ActiveSheet.Name 
    MsgBox ("names set") 

    Set bk = Workbooks.Add 
    With bk 
     .Title = "MissingValues" 
     .SaveAs Filename:="MissingValues.xls" 
    End With 

    Set sht1 = bk.Sheets.Add 
    sht1.Name = "EndOne" 
    Set sht2 = bk.Sheets.Add 
    sht2.Name = "EndTwo" 
    Set sht3 = bk.Sheets.Add 
    sht3.Name = "EndThree" 

    MsgBox (book & " " & sht) 
    MsgBox ("completed") 
End Sub 
+0

您是否正在打開工作簿上的加載項運行? – Ripster

+7

如果您的加載項是加載的唯一工作簿,則可能沒有ActiveWorkbook ... –

回答

0

就像@TimWilliams說的,如果你的加載項是唯一加載的工作簿,你會得到這個錯誤。在這種情況下,沒有活動的工作簿和你的代碼是沒有上線

book = ActiveWorkbook.Name 

您可以通過添加以下行檢查工作簿的存在:

Set bk = Application.ActiveWorkbook 
If bk Is Nothing Then 
    MsgBox ("No workbook open. Creating a new one.") 
    Set bk = Workbooks.Add(xlWBATWorksheet) 
    Set sht1 = bk.ActiveSheet 
End If 

所以你最終:

Sub sheetvalues() 
    Dim bk As Workbook, sht1 As Worksheet, sht2 As Worksheet, sht3 As Worksheet 
    Dim book As String, sht As String, i As Integer, j As Integer 
    Dim att(1 To 4) As String, att_col(1 To 4) As Integer 

    MsgBox ("variables set") 

    Set bk = Application.ActiveWorkbook 
    If bk Is Nothing Then 
     MsgBox ("No workbook open. Creating a new one.") 
     Set bk = Workbooks.Add(xlWBATWorksheet) 
     Set sht1 = bk.ActiveSheet 
    End If 


    book = ActiveWorkbook.Name 
    sht = ActiveSheet.Name 
    MsgBox ("names set") 

    Set bk = Workbooks.Add 
    With bk 
     .Title = "MissingValues" 
     .SaveAs Filename:="MissingValues.xls" 
    End With 

    Set sht1 = bk.Sheets.Add 
    sht1.Name = "EndOne" 
    Set sht2 = bk.Sheets.Add 
    sht2.Name = "EndTwo" 
    Set sht3 = bk.Sheets.Add 
    sht3.Name = "EndThree" 

    MsgBox (book & " " & sht) 
    MsgBox ("completed") 
End Sub 
3

導致此問題的常見問題是忘記使用'Set'將值賦予變量。

-1

檢查Excel中的工作簿是否詢問您是否要打開寫保護版本。我認爲,雖然存在此問題,但工作簿不被視爲活動,也不是其他任何其他

相關問題