gpt4 book ai didi

vba - 由于 Private Declare 语句的位置而导致编译错误

转载 作者:行者123 更新时间:2023-12-02 16:16:35 27 4
gpt4 key购买 nike

我正在尝试使用 this Microsoft support page 上提供的 CreateObject("Scriptlet.TypeLib").GUID 的替代方案(经过一些修改)但在 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) 行。

是什么导致了这个错误?有解决办法吗?

最佳答案

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) 部分 - 查看代码 Pane 窗口顶部的左上角下拉列表:如果它没有说明(声明),那么您就在过程的范围内; Declare 语句的作用域不能限定在过程级别。

关于vba - 由于 Private Declare 语句的位置而导致编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55814470/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com