在类

时间:2016-11-13 03:11:00

标签: excel vba excel-vba

我有一个如下的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子例程时,它会抛出一个错误:

  

子或功能未定义

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

我搜索了许多与错误 Sub或功能未定义相关的问题,并尝试实施他们回答的修改建议以纠正此错误,但它无法正常工作。

有关此错误是什么以及如何纠正错误的任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

如果您在Class内调用Module内的方法,则需要使用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中,您需要创建YourClass
  • 的新实例
  • YourClass ProcessFolder子例程需要Public