ThisWoorkbook运行时错误438

我有一个VBA从Sheet1复制和粘贴到Sheet3上的唯一值。 但是,当我运行VBA时,我得到运行时错误438。 我的VBA看起来像这样:

Sub UniqueList() Application.ScreenUpdating = False Dim lastrow As Long Dim i As Long Dim dictionary As Object Set dictionary = CreateObject("scripting.dictionary") ThisWorkbook.Sheet1.Activate lastrow = Sheet1.Cells(Rows.Count, "M").End(xlUp).Row On Error Resume Next For i = 1 To lastrow If Len(Cells(i, "M")) <> 0 Then dictionary.Add Cells(i, "M").Value, 1 End If Next Sheet3.Range("a2").Resize(dictionary.Count).Value = _ Application.Transpose(dictionary.keys) Application.ScreenUpdating = True MsgBox dictionary.Count & " unique cell(s) were found and copied." End Sub 

获取错误的行是:

 ThisWorkbook.Sheet1.Activate 

我使用Sheet3中的button来运行VBA。 但我也尝试用Sheet1打开使用AltF8和AltF11,没有任何工作。

林不知道为什么我得到这个错误,所以我希望有一个人可以帮助解决scheme

Sheet1不是ThisWorkbook的成员。 ThisWorkbook是一个Workbook实例,并且Workbook对象不公开其Worksheets集合中的每个工作表的“dynamic成员”。 因此,错误438, 对象不支持属性或方法

Sheet1是[我推测] ThisWorkbook工作表的CodeName :它是一个全局作用域Worksheet VBA方便创build的对象,以文档模块的(Name)属性命名。

Sheet1对象具有Parent属性; 像每个Worksheet对象一样,它已经知道它属于哪个Workbook实例:

 Debug.Print Sheet1.Parent Is ThisWorkbook 

智能感知一直试图告诉你(通过列出Sheet1成员) – 听听它说什么!


这就是说,修复这样的指令:

 Sheet1.Activate 

…不能解决其他问题 :只使用Activate以便不合格的Cells调用可以引用特定的工作表:

 For i = 1 To lastrow If Len(Cells(i, "M")) <> 0 Then dictionary.Add Cells(i, "M").Value, 1 End If Next 

相反, 限定他们

 For i = 1 To lastrow If Len(Sheet1.Cells(i, "M")) <> 0 Then dictionary.Add Sheet1.Cells(i, "M").Value, 1 End If Next 

然后Activate呼叫变得完全无用。

这些隐式的ActiveSheet引用可以很容易地引入,很难被发现。 Rubberduck (我pipe理的一个开源的VBE插件项目)可以帮助你find它们(和其他东西):

“隐式引用ActiveSheet”检查结果