由于Private Declare语句的位置而编译错误

问题描述 投票:4回答:1

我正在尝试使用CreateObject("Scriptlet.TypeLib").GUID上提供的this Microsoft support page的替代品(有一些修改),但在Private Declare PtrSafe Function CoCreateGuid Lib "ole32.dll" (guid As GUID_TYPE) As LongPtr线上得到“编译错误:只有注释可能出现在End Sub,End Function或End Property之后”。

从下面的代码中可以看出,这一行是在一个函数内,所以我不明白是什么导致了这个编译错误。

我试图在函数内移动两条Private Declare线,看看是否可以解决问题,但继续得到同样的错误。

Public Function GetGUID() As String
  Private Type GUID_TYPE
    Data1 As Long
    Data2 As Integer
    Data3 As Integer
    Data4(7) As Byte
  End Type

  Private Declare PtrSafe Function CoCreateGuid Lib "ole32.dll" (guid As GUID_TYPE) As LongPtr
  Private Declare PtrSafe Function StringFromGUID2 Lib "ole32.dll" (guid As GUID_TYPE, ByVal lpStrGuid As LongPtr, ByVal cbMax As Long) As LongPtr

  Dim guid As GUID_TYPE
  Dim strGuid As String
  Dim retValue As LongPtr
  Const guidLength As Long = 39 'registry GUID format with null terminator {xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}
  retValue = CoCreateGuid(guid)
  If retValue = 0 Then
    strGuid = String$(guidLength, vbNullChar)
    retValue = StringFromGUID2(guid, StrPtr(strGuid), guidLength)
    If retValue = guidLength Then
      ' valid GUID as a string
      GetGUID = strGuid
    End If
  End If
End Function

此功能正在用于将日历事件从默认日历复制到另一个指定日历的模块中使用。

这段代码可以找到here。同样,它取代了此代码中的GetGUID = Mid$(CreateObject("Scriptlet.TypeLib").GUID, 2, 36)行。

导致此错误的原因是什么?是否有解决方案?

vba outlook outlook-vba
1个回答
4
投票

Declare语句属于模块级别。剪切两条线并将它们移动到模块的最顶部,就在Option Explicit所在的位置下方。

编译错误有点笨拙/误导:如果你在模块中的两个过程之间有Declare语句或变量声明,那么你将获得相同的编译错误。

Option Explicit
'legal here
Private Declare PtrSafe Function CoCreateGuid Lib "ole32.dll" (guid As GUID_TYPE) As LongPtr

Public Sub Foo()
End Sub

'illegal here
Private Declare PtrSafe Function CoCreateGuid Lib "ole32.dll" (guid As GUID_TYPE) As LongPtr

Private Function Bar()
    'illegal here
    Private Declare PtrSafe Function CoCreateGuid Lib "ole32.dll" (guid As GUID_TYPE) As LongPtr
End Sub

Declare语句必须存在于模块的(declarations)部分 - 观察代码窗格窗口顶部的左上角下拉列表:如果它没有说(declarations),那么你就在一个过程的范围内; Declare语句不能用于程序级别。

© www.soinside.com 2019 - 2024. All rights reserved.