用于单元格数据语言翻译的VBA代码

时间:2016-05-12 13:54:50

标签: vba excel-vba language-translation excel

我正在编写代码将所选单元格中的数据从葡萄牙语翻译成英语,但我遇到了错误:

翻译过的单元格正在返回"和"无论我写什么,它都应该翻译单元格中的所有单词......任何想法都是聪明的头脑?

enter image description here

这是我的代码:

Sub traducaobeta()

Dim translate As Object 'scritping.Dictionary

Set translate = CreateObject("Scripting.Dictionary")

translate("cadeira") = "chair"
translate("cadeiras") = "chairs"
translate("criado mudo") = "night stand"
translate("criado-mudo") = "night stand"
translate("mesa") = "table"
translate("mesas") = "tables"
translate(" e ") = " and "
' the list goes on...


Dim ptWords As String
Dim enWords As String

ptWords = LCase(activecell.Value)

For Each tempVar In translate.Keys()

enWords = Replace(Replace(CStr(tempVar), CStr(tempVar), translate(CStr(tempVar)), InStr(CStr(tempVar), CStr(tempVar))), " e ", " and ")

activecell.Offset(0, 1).Value = enWords

Next
End Sub

任何人都知道如何修复它?

2 个答案:

答案 0 :(得分:1)

错误告诉您必须在Variant循环中使用For Each类型变量。您使用的ptWordsString,但translate.Keys()返回的值不是导致错误的显式字符串类型。

将变量声明为变体

Dim ptWords As Variant

或在循环中使用通用变体:

For Each tempVar In translate.Keys()

enWords = Replace(Replace(CStr(tempVar), CStr(tempVar), translate(CStr(tempVar)), InStr(CStr(tempVar), CStr(tempVar))), " e ", " and ")

activecell.Offset(0, 1).Value = enWords

Next

应该做的伎俩。

请注意,我已使用tempVar明确地将CStr()转换为代码中的字符串 - 虽然这可能总是是必要的(由于隐式类型转换)进入是一个很好的做法。

答案 1 :(得分:1)

我会尝试循环浏览文本中的单词。 以下过程将翻译您的集合中的每个单词,并以葡萄牙语留下其他单词:

Sub traducaobeta()

Dim translate As Object 'scritping.Dictionary

Set translate = CreateObject("Scripting.Dictionary")

translate("cadeira") = "chair"
translate("cadeiras") = "chairs"
translate("criado mudo") = "night stand"
translate("criado-mudo") = "night stand"
translate("mesa") = "table"
translate("mesas") = "tables"
translate(" e ") = " and "
' 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.Offset(0, 1).Value = Join(Words)

End Sub