VBA如何解决string错误以特殊字符开始

我在VBA方面相当新,我正在做一个项目,这是我面临的一个小问题。 我正在使用newLastCmtTypeCol,newLastCmtCol,newLastNoteCol,oldLastCmtTypeCol,oldLastCmtCol,oldLastNoteCol作为string,我只是在这部分代码中调用它们。 所以当一个string以特殊字符开始时,错误发生。 我正在从表单input大量的数据。 我绝对没有办法通过所有的数据。 我只是想忽略string开始与特殊字符,所以我wouldnt看到任何error.Here是代码的一部分。

Dim newLastCmtTypeCol As String Dim newLastCmtCol As String Dim newLastNoteCol As String Dim oldLastCmtTypeCol As String Dim oldLastCmtCol As String Dim oldLastNoteCol As String newLastCmtTypeCol = "N" newLastCmtCol = "O" newLastNoteCol = "P" oldLastCmtTypeCol = "Q" oldLastCmtCol = "R" oldLastNoteCol = "S" For j = 0 To indexNew(i, 4) If (StrComp(ws1.Range(newLastCmtTypeCol & i + j), ws1.Range(oldLastCmtTypeCol & i + j)) = 0) And _ (StrComp(ws1.Range(newLastCmtCol & i + j), ws1.Range(oldLastCmtCol & i + j)) = 0) And _ (StrComp(ws1.Range(newLastNoteCol & i + j), ws1.Range(oldLastNoteCol & i + j)) = 0) And categoryCode = 1 Then categoryCode = 1 ElseIf IsEmpty(ws1.Range(oldLastCmtTypeCol & i + j)) And IsEmpty(ws1.Range(oldLastCmtCol & i + j)) And IsEmpty(ws1.Range(oldLastNoteCol & i + j)) Then categoryCode = 3 Exit For Else categoryCode = 2 End If Next j 

任何解决scheme

 Public Function DelInvalidCharacters(InputString As String) As String Dim ModString As String, InvalidChars As String, Char As String Dim i As Integer InvalidChars = "\/:*?""<>|';#,()%&$+- " ModString = vbNullString For i = 1 To Len(InputString) Char = Mid(InputString, i, 1) If InStr(1, InvalidChars, Char) = 0 Then ModString = ModString & Char End If Next i DelInvalidCharacters = ModString End Function 

只需要调用这个函数为每个variables你想剥离坏字符

像这样调用它

 Dim this As String this = "*this" this = DelInvalidCharacters(this) 

您的问题似乎与包含错误,而不是特殊字符的单元格。 如果是这样,你可能想过滤出这样的细胞。

你可以使用IsError来包装你的代码,例如

  If (Not (IsError(ws1.Range(newLastCmtTypeCol & i + j))) and _ Not (IsError(ws1.Range(oldLastCmtTypeCol & i + j))) and _ ... _ ) Then 

那么你可以比较其他任何东西。 如果需要,您可能希望在string和数字之间使用转换。