Visual Basic for Applications(VBA)编译错误:过程声明与具有相同名称的事件或过程的描述不匹配

时间:2016-07-05 11:53:38

标签: vba excel-vba compiler-errors excel

尝试返回并从函数调用值时出现上述错误;这是我的源代码:

Private Function Fence_Change()
  Contents = Fence.Text
  Range("D4:ZZ4").Clear
  Range("D5:ZZ5").Clear
  Output = ""
  For Counter = 1 To Len(Contents)
      Cells(4, Counter + 3) = Mid(Contents, Counter, 1)
      Output = Output + Mid(Contents, Counter, 1)
      Counter = Counter + 1
  Next Counter
  For Counter = 2 To Len(Contents)
      Cells(5, Counter + 3) = Mid(Contents, Counter, 1)
      Output = Output + Mid(Contents, Counter, 1)
      Counter = Counter + 1
  Next Counter
  Fence_Change = Output
End Function
Private Sub Fence_DblClick(ByVal Cancel As MSForms.ReturnBoolean)
    Output1 = Fence_Change()
    MsgBox (Output1)
End Sub

使用VBA IDE for Office(Excel)2016。 我见过很多其他有类似问题的人,但似乎仍然无法解决问题,有人可以帮助解决这个问题吗? 也许有用的知道我已经返回并以相同的方式调用另一个函数而没有任何错误:

Private Function Difficulty_Select()
  Set List = New Collection
  Select Case Difficulty
  Case "Easy"
      DifficultyInt = 10
      DifficultyOption = "Easy"
  Case "Medium"
      DifficultyInt = 25
      DifficultyOption = "Medium"
  Case "Hard"
      DifficultyInt = 50
      DifficultyOption = "Hard"
  End Select
  List.Add DifficultyInt
  List.Add DifficultyOption
  Set Difficulty_Select = List
End Function
Private Sub CommandButton1_Click()
   MsgBox ("Hello, welcome to a quiz")
   Name = InputBox("What is your name?")
   Sheets("All results").Unprotect
   Score = 0
   Set List1 = Difficulty_Select()
   ...

3 个答案:

答案 0 :(得分:3)

假设Fence是一个控件,它已经有一个Change事件,它是一个Sub,而不是一个Function。即使您实际上没有沉没内置的Change事件,也无法使用相同的名称创建自己的函数。

答案 1 :(得分:0)

正如Rory所说,Fence看起来像是Control,因此Fence_ChangeChange事件的处理程序,应该是Sub过程

您可以尝试重新组织代码,以便Fence_Change事件 Fence_DblClick事件调用常用函数,如下所示:

Private Sub Fence_Change()
  GetOutput Fence.Text
End Sub

Private Sub Fence_DblClick(ByVal Cancel As MSForms.ReturnBoolean)
    Output1 = GetOutput(Fence.Text)
    MsgBox Output1
End Sub

'This is the new helper function
Private Function GetOutput(contents As String) as String
  Range("D4:ZZ4").Clear
  Range("D5:ZZ5").Clear
  Output = ""
  For Counter = 1 To Len(Contents)
      Cells(4, Counter + 3) = Mid(Contents, Counter, 1)
      Output = Output + Mid(Contents, Counter, 1)
      Counter = Counter + 1
  Next Counter
  For Counter = 2 To Len(Contents)
      Cells(5, Counter + 3) = Mid(Contents, Counter, 1)
      Output = Output + Mid(Contents, Counter, 1)
      Counter = Counter + 1
  Next Counter
  GetOutput = Output
End Function

答案 2 :(得分:-1)

如果它是带有Service Pack 1的Windows 7 Ultimate,只需删除该Service Pack或将其卸载即可。那解决了问题。