繁体   English   中英

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

[英]Invalid name entered in UDF with VBA for Excel

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

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

  2. 输入包含包含所有OECD国家的列的第一个单元格。

该功能通过循环比较单元格Candidatecountries列的内容。 如果候选人名称与任何经合组织国家都不匹配,最后该功能会将其归类为非经合组织国家。

我的代码是这样的:

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

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

您输入的名称无效。 原因可能包括:

-名称不能以字母或下划线开头

-名称包含空格或其他无效字符

-名称与Excel内置名称或工作簿中另一个对象的名称冲突

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

好吧,我必须说,我认为经合组织国家是静态数据的一个例子,因为它不会经常改变。 我将数据存储在某个地方的工作表上,然后在第一次请求时使用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

并使用这样的单元格公式从工作表中调用

=OECD("UK")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM