[英]Invalid name entered in UDF with VBA for Excel
我正在制作一個簡單的UDF,用於檢查給定國家/地區是否是OECD成員。 我有兩個輸入:
包含國家/地區名稱的Excel單元格
輸入包含包含所有OECD國家的列的第一個單元格。
該功能通過循環比較單元格Candidate
和countries
列的內容。 如果候選人名稱與任何經合組織國家都不匹配,最后該功能會將其歸類為非經合組織國家。
我的代碼是這樣的:
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.