Excel 的 VBA 在 UDF 中输入的名称无效

Invalid name entered in UDF with VBA for Excel

我正在制作一个简单的 UDF,用于检查给定国家/地区是否为经合组织成员。我有两个输入:

  1. Excel 包含国家名称的单元格

  2. 输入包含包含所有经合组织国家/地区的列的第一个单元格。

该函数通过循环比较单元格 Candidatecountries 列的内容。如果候选名称与任何 OECD 国家都不匹配,最后函数将其归类为非 OECD 国家。

我的代码是这样的:

Function OECD(Candidate, Countries)
    Dim Candidate As String
    Dim Countries As String
    OECDCountry = Countries 'Variable that changes at every iteration, I compare the name of the candidate to this
    For i = 1 To 34     
        If Candidate.Value = OECDCountry Then
            OECD = 2                 
        Else: OECDCountry = Countries.Offset(i, 0)
    Next i

'If the column next to the candidate name, where I am running this function, is still empty, record the country as non-OECD

    If Candidate.Offset(0, 1) <> 2 Then OECD = 1                
End Function

但是,当我尝试使用该功能时,我在选择第二个输入时收到以下错误消息:

The name that you entered is not valid. Reasons for this can include:

-The name does not begin with a letter or an underscore

-The name contains a space or other invalid characters

-The name conflicts with an Excel built-in name or the name of another object in the workbook

为什么我会收到此错误消息,我该如何解决?

嗯,我必须说,我认为经合组织国家是静态数据的一个例子,因为它不会经常改变。我会将数据存储在某个 sheet 上,然后在第一次请求时使用 Scripting.Dictionary 将其读入缓存,然后可以使用 Exists 方法。这是我的解决方案

Option Explicit

Private mdicRunTimeCacheOECDCountries As Scripting.Dictionary

Sub DevTimeSetup_RunOnce()

    ' ___          _____ _           ___      _               ___           ___
    '|   \ _____ _|_   _(_)_ __  ___/ __| ___| |_ _  _ _ __  | _ \_  _ _ _ / _ \ _ _  __ ___
    '| |) / -_) V / | | | | '  \/ -_)__ \/ -_)  _| || | '_ \ |   / || | ' \ (_) | ' \/ _/ -_)
    '|___/\___|\_/  |_| |_|_|_|_\___|___/\___|\__|\_,_| .__/_|_|_\_,_|_||_\___/|_||_\__\___|
    '                                                 |_| |___|                                           http://www.network-science.de/ascii/
    '* just some code to set up a sheet with some data as OP supplied none
    '* so that anyone can play with this problem
    Dim rngOECD As Excel.Range
    Set rngOECD = Sheet1.Range(Sheet1.Cells(1, 1), Sheet1.Cells(7, 1))
    rngOECD.Value2 = [{"USA";"UK";"Germany";"France";"Italy";"Japan";"Canada"}] 'not full OECD, just G7
    rngOECD.Name = "OECDCountries"

End Sub


Private Function GetRunTimeCacheOECDCountries() As Scripting.Dictionary
    If mdicRunTimeCacheOECDCountries Is Nothing Then
        Set mdicRunTimeCacheOECDCountries = New Scripting.Dictionary

        Dim rngOECD As Excel.Range
        Set rngOECD = Sheet1.Range("OECDCountries")

        Dim rngLoop As Excel.Range
        For Each rngLoop In rngOECD
            mdicRunTimeCacheOECDCountries.Add rngLoop.Value2, 0
        Next

    End If
    Set GetRunTimeCacheOECDCountries = mdicRunTimeCacheOECDCountries
End Function



Public Function OECD(Candidate) As Long
    OECD = VBA.IIf(GetRunTimeCacheOECDCountries.Exists(Candidate), 1, 0)
End Function

并使用这样的单元格公式

下班打电话sheet

=OECD("UK")