在调用Class中的public / private子时,VBA Sub或函数未定义错误

我有一个如下所示的VBA脚本:

Sub button_click () ' ' < some code > ' call FindStrings (strfolder, Nothing) End Sub Public Sub FindStrings(strFolder As String, Optional wksSheet As Worksheet = Nothing) ' ' < some code> ' Call ProcessFolder(strFolder, strIndent, varStrings, varMatchesFound, varFileNames, lngFolderCount, lngFileCount) End sub Private Sub ProcessFolder(strFolder As String, ByRef strIndent As String, ByRef varStrings As Variant, ByRef varMatchesFound As Variant, ByRef varFileNames As Variant, ByRef lngFolderCount As Long, lngFileCount As Long) ' ' < some code> ' Call ProcessFile(objFile.Path, strIndent, varStrings, varMatchesFound, varFileNames) End sub Private Sub ProcessFile(strFullPath As String, ByRef strIndent As String, ByRef varStrings As Variant, ByRef varMatchesFound As Variant, ByRef varFileNames As Variant) ' ' < some code> ' End sub 

目前, button_clickFindStrings在一个ModuleProcessFolderProcessFile在一个Class

当我运行button_click子例程时,会抛出一个错误:

子或function未定义

FindStrings中Call ProcessFolder...行中发生错误。

我已经search了许多与错误Sub或函数没有定义有关的问题,也试图实现他们所提出的改变,以纠正这个错误,但它是行不通的。

任何帮助有关这个错误是什么,以及如何纠正它,将不胜感激。

如果你在一个Module内调用一个Class方法,那么你需要用New关键字来实例化这个类。 然后用点符号引用Class方法。

一个一般的例子是:

 'Module Public Sub Foo() Dim o As Class1 Set o = New Class1 o.Bar End Sub 'Class1 Public Sub Bar() MsgBox "Hello world" End Sub 

这对你的例子意味着你会做:

 'Module Sub button_click () '< some code > Call FindStrings (strfolder, Nothing) End Sub Public Sub FindStrings(strFolder As String, Optional wksSheet As Worksheet = Nothing) ' < some code> Dim o As YourClass Set o = New YourClass o.ProcessFolder(strFolder, strIndent, varStrings, varMatchesFound, varFileNames, lngFolderCount, lngFileCount) End Sub 'YourClass Public Sub ProcessFolder(strFolder As String, ByRef strIndent As String, ByRef varStrings As Variant, ByRef varMatchesFound As Variant, ByRef varFileNames As Variant, ByRef lngFolderCount As Long, lngFileCount As Long) ' < some code> Call ProcessFile(objFile.Path, strIndent, varStrings, varMatchesFound, varFileNames) End Sub Private Sub ProcessFile(strFullPath As String, ByRef strIndent As String, ByRef varStrings As Variant, ByRef varMatchesFound As Variant, ByRef varFileNames As Variant) ' < some code> End Sub 

注意:

  • FindStrings您需要创build一个YourClass的新实例
  • YourClassProcessFolder子例程需要为Public