我设置了一个宏,以将框添加到图表并将其链接到其他两张表中的表。
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
'Declare and assign values to sh1 and sh2
Dim sh1 As Worksheet
Dim sh2 As Worksheet
Set sh1 = ActiveWorkbook.Sheets("Training Master")
Set sh2 = ActiveWorkbook.Sheets("Attendance Master")
'Declare and assign values to sp1 and sp2
Dim sp1 As Range
Dim sp2 As Range
Set sp1 = sh1.Range("C:C").Find("2nd Process")
Set sp2 = sh2.Range("C:C").Find("2nd Process")
'Adds boxes to organizational chart
Target.Borders(xlEdgeBottom).LineStyle = xlDouble
Target.Borders(xlEdgeLeft).LineStyle = xlDouble
Target.Borders(xlEdgeRight).LineStyle = xlDouble
Target.Borders(xlEdgeTop).LineStyle = xlDouble
Target.Offset(1).Borders(xlEdgeBottom).LineStyle = xlDouble
Target.Offset(1).Borders(xlEdgeLeft).LineStyle = xlDouble
Target.Offset(1).Borders(xlEdgeRight).LineStyle = xlDouble
Target.Interior.ColorIndex = 45
Target.Font.ColorIndex = 3
'Adds line to table in Training Master, links appropriate cells to
organizational chart
sp1.Offset(0, -2).Resize(1, 19).Insert
sp1.Offset(-2, -1).Copy sp1.Offset(-1, -1)
sp1.Offset(-2, 9).Copy sp1.Offset(-1, 9)
'Adds line to table in Attendance Master, returns error 91
sp2.Resize(1, 7).Insert 'Debug identifies this line as error 91
sp2.Offset(-2).Copy sp2.Offset(-1)
End Sub
似乎每个变量都被分配了一个值,并且我已经进行了两次和三次检查,以确保工作表名称的拼写与代码中的引用匹配。我为什么得到:
错误91对象变量或未设置块变量
答案 0 :(得分:1)
使用Range.Find method后,始终测试查找是否成功:
Set sp1 = sh1.Range("C:C").Find("2nd Process")
If sp1 Is Nothing Then
MsgBox "2nd Process was not found in " & sh1.Name
Exit Sub
End If
我强烈建议始终为查找方法指定LookAt
参数:
Find(What:="2nd Process", LookAt:=xlWhole)
查找整个单元格值Find(What:="2nd Process", LookAt:=xlPart)
查找单元格值的一部分。如果未指定LookAt
参数,Excel将使用VBA或使用find的手册最后使用的参数。因此,如果不指定它,则永远不会知道使用哪个Excel。
答案 1 :(得分:0)
出现错误是因为如果@"\t"
不存在,则sp1
将失败。将您的代码更改为该代码,以检查它是否为“ Something”并采取相应措施:
Offest