我创建了一个Excel加载项,用于确定ActiveSheet
和ActiveWorkbook
的名称。我使用的代码如下。当我运行加载项时,它会在消息框“变量设置”后显示上述错误。但是当我在宏中运行它时工作正常。我不明白加载项发生了什么。有人可以帮我这个吗?
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 :(得分:7)
导致此问题的一个常见问题是忘记使用'Set'为变量赋值。
答案 1 :(得分: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
答案 2 :(得分:-1)
检查Excel中的工作簿是否询问您是否要打开写保护版本。我认为虽然存在这个问题但是工作簿不被认为是活动的,也没有任何其他的