2013-07-28 80 views
1

我使用VBA創建了Excel工作簿以幫助創建用戶帳戶。它會生成8個字符的密碼,然後以語音形式顯示密碼。Excel-VBA將字符串轉換爲拼音字母表

一切工作正常,我只是想改善我的代碼。

這部分代碼需要密碼中的字母字符,並吐出北約語音等值。看起來我應該能夠容納大小寫字符,只有一半的代碼,我只是不知道如何。

Public Function Wordify(char As String) 
Wordify = Switch(char = "A", "ALFA", char = "B", "BRAVO", char = "C", "CHARLIE", char = "D", "DELTA", char = "E", "ECHO", char = "F", "FOXTROT", _ 
    char = "G", "GOLF", char = "H", "HOTEL", char = "I", "INDIA", char = "J", "JULIETT", char = "K", "KILO", char = "L", "LIMA", char = "M", "MIKE", _ 
    char = "N", "NOVEMBER", char = "O", "OSCAR", char = "P", "PAPA", char = "Q", "QUEBEC", char = "R", "ROMEO", char = "S", "SIERRA", char = "T", "TANGO", _ 
    char = "U", "UNIFORM", char = "V", "VICTOR", char = "W", "WHISKEY", char = "X", "XRAY", char = "Y", "YANKEE", char = "Z", "ZULU", _ 
    char = "a", "alfa", char = "b", "bravo", char = "c", "charlie", char = "d", "delta", char = "e", "echo", char = "f", "foxtrot", _ 
    char = "g", "golf", char = "h", "hotel", char = "i", "india", char = "j", "juliett", char = "k", "kilo", char = "l", "lima", char = "m", "mike", _ 
    char = "n", "november", char = "o", "oscar", char = "p", "papa", char = "q", "quebec", char = "r", "romeo", char = "s", "sierra", char = "t", "tango", _ 
    char = "u", "uniform", char = "v", "victor", char = "w", "whiskey", char = "x", "xray", char = "y", "yankee", char = "z", "zulu") 
End Function 
+0

您可以創建一個包含所有大寫值的數組,然後根據char的ASCII碼返回該數組中正確索引處的單詞的上下兩個版本。 –

回答

2

嘗試下面的代碼。簡化版本。

Public Function Wordify(char As String) 
Phonetics = Split("alfa,bravo,charlie,delta,echo,foxtrot,golf,hotel,india,juliett,kilo,lima,mike,november,oscar,papa,quebec,romeo,sierra,tango,uniform,victor,whiskey,xray,yankee,zulu", ",") 'storing your custom values into an array Phonetics 
AsciofChar = Asc(char) 'finding the ascii of the character passed to the function 
If AsciofChar >= 65 And AsciofChar <= 90 Then 'checking whether the char is upper case 
    Wordify = UCase(Phonetics(AsciofChar - 65)) 'selecting the value from the array corresponding to the char passed 
ElseIf AsciofChar >= 97 And AsciofChar <= 122 Then 'checking whether the char is in lower case 
    Wordify = LCase(Phonetics(AsciofChar - 97)) 'selecting the value from the array corresponding to the char passed 
End If 
End Function 
4

Simplfying伊恩的代碼進一步:


Public Function Wordify(char As String) As String 
    On Error Resume Next 
    Wordify = Split("alpha,bravo,charlie,delta,echo,foxtrot,golf,hotel,india,juliett,kilo,lima,mike,november,oscar,papa,quebec,romeo,sierra,tango,uniform,victor,whiskey,xray,yankee,zulu", ",")(Asc(LCase(char)) - 97) 
End Function 

PS。我還用北約音標中使用的拼寫替換了「阿爾法」; 「α」。

+0

此代碼將只返回小寫語音。 – Ian

+1

加'如果char = UCase(char)那麼Wordify = UCase(Wordify)',它會返回兩種情況。 – Ripster

+0

謝謝(對你們倆)。您也可以在Wordify(...)函數的返回周圍使用UPPER(...)內嵌函數。 – fanpages