Excel VBA Code for language translation broken?

时间:2016-05-17 11:14:14

标签: vba excel-vba excel

This code should translate all the words from it's dictionary in a cell, but instead, it translates only the first line (it only translates "E" to "And"), it should go through all the words and change all the words in the cell.

Sub traducaobeta2()

Dim translate As Object 'scritping.Dictionary

Set translate = CreateObject("Scripting.Dictionary")

translate("e") = "and"
translate("Telefones") = "Telephones"
translate("Livros") = "Books"
translate("Criado mudo") = "Night stand"
translate("Banqueta") = "Stool"
translate("livros") = "books"
translate("cadernos") = "papers"
translate("travesseiros") = "pillows"
translate("Mesa") = "Table"
translate("Materiais de escritório") = "Office materials"
' the list goes on...


Dim Words As Variant
Dim I As Integer
Words = Split(LCase(activecell.Value))


For I = LBound(Words) To UBound(Words)
    If translate(Words(I)) <> "" Then Words(I) = translate(Words(I))
Next
activecell.Value = Join(Words)
activecell.Value = Ucase$(Left$(activecell.Value, 1)) & Right$(activecell.Value, Len(activecell.Value) - 1)
end sub

2 个答案:

答案 0 :(得分:4)

当你像这样使用Split()时,它会将每个单词放入数组中,但会将它们更改为小写。字典中的键区分大小写,因此您需要使用小写键。

translate("e") = "and"
translate("telefones") = "Telephones"
translate("livros") = "Books"
translate("criado mudo") = "Night stand"
translate("banqueta") = "Stool"
translate("livros") = "books"
translate("cadernos") = "papers"
translate("travesseiros") = "pillows"
translate("mesa") = "Table"
translate("materiais de escritório") = "Office materials"
' the list goes on...

在旁注上,最后一个("materiais de escritório")将无法正常工作,因为它有空格,因此您的数组将在单独的索引中包含materiaisdeescritório将永远不会匹配字典键。

答案 1 :(得分:3)

除了Macro Man的优秀评论外,另一种方法是完全忽略LCase,UCase问题。不要试图改变或修复案件。相反,只需加强翻译对象,如:

ALTER USER user_name IDENTIFIED BY new_user_name ;
ALTER USER user_name IDENTIFIED BY user_name ;

如果源文本具有适当的大小写,则翻译将起作用,如果源文本全部为小写,则翻译应该有效。