2016-03-07 77 views
3

我正在進行自動化操作,需要在單元格內拼寫檢查段落並突出顯示紅色的錯誤單詞,並且此拼寫檢查需要在具有動態範圍的列中進行。拼寫檢查單元格中的單詞拼寫並將拼寫錯誤的單詞顏色更改爲紅色

我使用下面的代碼

Sub spellcheck() 

    Dim intOffsetCol As Integer 
    Dim intChrCnt As Integer 
    Dim varTempString As Variant 

    intOffsetCol = 1 

     For intChrCnt = 1 To Trim(Len(ActiveCell.Value)) Step 1 'Left to right 
      'A space character is represented by an ASCII code of 32. 
      If Asc(Mid(ActiveCell.Value, intChrCnt, 1)) <> 32 Then 
       varTempString = varTempString & Mid(ActiveCell.Value, intChrCnt, 1) 
      Else 


       If Not Application.CheckSpelling(Word:=varTempString) Then 
       varTempString.Interior.ColorIndex = 52 

       varTempString = "" 
       intOffsetCol = intOffsetCol + 1 
       End If 
      End If 
     Next intChrCnt 

     If varTempString <> "" Then 
      If Not Application.CheckSpelling(Word:=varTempString) Then varTempString.Interior.ColorIndex = vbRed 

     End If 

End Sub 

而且我得到「運行時錯誤424」varTempString.Interior.ColorIndex = 52

爲什麼我在該行得到一個錯誤?

+0

看到我在我的編輯解決方案。 – Chrismas007

回答

5

varTempString正被用作String變量,您的代碼正在嘗試更改不可能的單元格內部。

解決方案強調特定文本是:

Sub SpellCheckUpdate() 

Dim cel As Range, CellLen As Long, CurChr As Long, TheString As String 

For Each cel In Selection 
    For CurChr = 1 To Len(cel.Value) 
     If Asc(Mid(cel.Value, CurChr, 1)) = 32 Then 
      If InStr(CurChr + 1, cel.Value, " ") = 0 Then 
       TheString = Mid(cel.Value, CurChr + 1, Len(cel.Value) - CurChr) 
      Else 
       TheString = Mid(cel.Value, CurChr + 1, InStr(CurChr + 1, cel.Value, " ") - CurChr) 
      End If 
      If Not Application.CheckSpelling(Word:=TheString) Then 
       cel.Characters(CurChr + 1, Len(TheString)).Font.Color = RGB(255, 0, 0) 
      Else 
       cel.Characters(CurChr + 1, Len(TheString)).Font.Color = RGB(0, 0, 0) 
      End If 
      TheString = "" 
     End If 
    Next CurChr 
Next cel 

End Sub 

這是更簡單的代碼來突出顯示拼寫錯誤的單詞全電池:

Sub ColorMispelledCells() 
    For Each cl In ActiveSheet.UsedRange 
     If Not Application.CheckSpelling(Word:=cl.Text) Then _ 
      cl.Interior.ColorIndex = 28 
    Next cl 
End Sub 
+0

酷的工作精湛:)。非常感謝Chrismas007 – Linga