2017-10-04 55 views
1

在未來column.My代碼翻譯在Excel和粘貼結果一整列翻譯在Excel和粘貼結果一整列如下:在下一列

Sub test() 
Dim s, r As Range, l As String 

For Each s In Range("A2:A3").Cells 
     l = s 
     **Range("B2:B3").Cells = translate_using_vba(s, l)** 

    Next s 

End Sub 


Public Function translate_using_vba(str, l) As String 
' Tools Refrence Select Microsoft internet Control 
    Dim IE As Object, i As Long, j As Long 
    Dim inputstring As String, outputstring As String, text_to_convert As String, result_data As String, CLEAN_DATA 
    Set IE = CreateObject("InternetExplorer.application") 
    ' TO CHOOSE INPUT LANGUAGE 
    inputstring = "auto" 
    ' TO CHOOSE OUTPUT LANGUAGE 
    outputstring = "en" 

    text_to_convert = str 
    'open website 
    IE.Visible = False 
    IE.navigate "http://translate.google.com/#" & inputstring & "/" &outputstring & "/" & text_to_convert 
    Do Until IE.ReadyState = 4 
     DoEvents 
    Loop 
    Application.Wait (Now + TimeValue("0:00:5")) 
    Do Until IE.ReadyState = 4 
     DoEvents 
    Loop 

    CLEAN_DATA = Split(Application.WorksheetFunction.Substitute(IE.Document.getElementById("result_box").innerHTML, "</SPAN>", ""), "<") 

    For j = LBound(CLEAN_DATA) To UBound(CLEAN_DATA) 
     result_data = result_data & Right(CLEAN_DATA(j), Len(CLEAN_DATA(j)) - InStr(CLEAN_DATA(j), ">")) 
    Next 

    IE.Quit 
    translate_using_vba = result_data 


End Function 

問題:它工作正常,但我導致列B每次都被覆蓋。我怎樣才能存儲B2值,然後移動到B3?

回答

0

試試這個:

Set r = Range("B2") ' Initial (starting) cell 
For Each s In Range("A2:A3").Cells 
    l = s 
    r.value = translate_using_vba(s, l) 
    Set r = r.Offset(1, 0) 'Next row 
Next s 
+0

它的工作原理!非常感謝你。 – user3578975

+0

需要改進的一個問題 - 當單元格中的數據很多且空間很大且========時,會出現運行時錯誤:應用程序定義或對象定義的錯誤在行「r.Value = translate_using_vba(s,l)「。有沒有辦法避免它? – user3578975

+0

那麼,通過單步調試你的代碼,並利用立即窗口找出原因 – peakpeak