为避免这种情况,您可以使用标准 URL 方式对搜索词进行编码。
如果您有 Excel 2013 或更高版本,则可以使用 WorksheetFunction.EncodeURL 来执行此操作。您的代码将是:
Sub SpecialLetters()
Dim objIe As Object
Set objIe = CreateObject("InternetExplorer.Application")
objIe.Visible = True
objIe.Navigate "http://www.google.com/search?hl=en&ie=UTF-8&q=" & WorksheetFunction.EncodeURL(Sheets("Sheet1").Range("A1").Value)
End Sub
对于 Excel 2010 或更低版本,如果不创建自己的函数就无法做到这一点,但幸运的是,Tomalak 已经在 VBA (see here) 中提供了一个函数来执行此操作,然后您可以简单地使用它:
Public Function URLEncode( _
ByVal StringVal As String, _
Optional SpaceAsPlus As Boolean = False _
) As String
Dim bytes() As Byte, b As Byte, i As Integer, space As String
If SpaceAsPlus Then space = "+" Else space = "%20"
If Len(StringVal) > 0 Then
With New ADODB.Stream
.Mode = adModeReadWrite
.Type = adTypeText
.Charset = "UTF-8"
.Open
.WriteText StringVal
.Position = 0
.Type = adTypeBinary
.Position = 3 ' skip BOM
bytes = .Read
End With
ReDim result(UBound(bytes)) As String
For i = UBound(bytes) To 0 Step -1
b = bytes(i)
Select Case b
Case 97 To 122, 65 To 90, 48 To 57, 45, 46, 95, 126
result(i) = Chr(b)
Case 32
result(i) = space
Case 0 To 15
result(i) = "%0" & Hex(b)
Case Else
result(i) = "%" & Hex(b)
End Select
Next i
URLEncode = Join(result, "")
End If
End Function
确保您参考了 Microsoft ActiveX 数据对象库以使其正常工作。
你的代码会变成:
Sub SpecialLetters()
Dim objIe As Object
Set objIe = CreateObject("InternetExplorer.Application")
objIe.Visible = True
objIe.navigate "http://www.google.com/search?hl=en&ie=UTF-8&q=" & URLEncode(Sheets("Sheet1").Range("A1").Value)
End Sub