我想删除D列中包含“+”和“ - ”的所有单元格。我已经尝试了以下宏,我认为它可以工作,但没有任何反应。
Sub doWhile4()
'Replace blank spaces with underscores in a Range of Cells, using VBA loops; or 'Remove
blank spaces in a Range of Cells, using VBA loops.
Dim iCell As Range
Dim textString As String
Dim n As Integer
'iCell is a Cell in the specified Range which contains the textString
'textString is the text in a Cell in which blank spaces are to be replaced with
'underscores. n is the position of blank space(s) occurring in a textString
For Each iCell In ActiveSheet.Range("D2:D34")
textString = iCell
n = InStr(textString, "+")
'The VBA InStr function returns the position of the first occurrence of a string within
'another string. Using this to determine the position of the first blank space in the
'textString.
Do While n > 0
textString = Left(textString, n - 1) & Right(textString, Len(textString) - n)
'This line of code is to remove all blank spaces in the
'textString
n = InStr(textString, "+")
Loop
iCell = textString
Next
End Sub
我做错了什么?
答案 0 :(得分:1)
如果单元格包含+或 -
,请尝试清除值Option Explicit
Sub doWhile4()
'Replace blank spaces with underscores in a Range of Cells, using VBA loops; or
'Remove blank spaces in a Range of Cells, using VBA loops.
Dim iCell As Range
Dim textString As String
Dim n As Integer
Dim hasPlus As Boolean
Dim hasMinus As Boolean
'iCell is a Cell in the specified Range which contains the textString
'textString is the text in a Cell in which blank spaces are to be replaced with
'underscores. n is the position of blank space(s) occurring in a textString
For Each iCell In ActiveSheet.Range("D2:D34")
textString = iCell
'reset our boolean variables for each iteration
hasPlus = False
hasMinus = False
If InStr(textString, "+") > 0 Then hasPlus = True
If InStr(textString, "-") > 0 Then hasMinus = True
'The VBA InStr function returns the position of the first occurrence of a string within
'another string. Using this to determine the position of the first blank space in the
'textString.
If hasPlus Or hasMinus Then iCell.Value = vbNullString
Next
End Sub
答案 1 :(得分:0)
尝试下面的内容。
基本上,它在列F中创建一个公式,在列D中搜索+或 - 并在找到一个时返回NA#错误,然后我们使用Excels SpecialCells函数返回并清除所有出现该错误的单元格。 ..
Sub clearCells()
'
Dim sFormula As String
'
sFormula = "=IF(IF(OR(IF(ISERROR(FIND(""+"",A:A)),"""",IF(FIND(""+"",A:A)>0,1,0))=1,IF(ISERROR(FIND(""-"",A:A)),"""",IF(FIND(""-"",A:A)>0,1,0))=1),1,0)=1,NA(),"""")"
'
' put in formula to find the cells with the characters in them...
Range("F1:F" & Range("D1").End(xlDown).Row).Formula = sFormula
'
' now clear the cells returned by SpecialCells ...
Range("A1").Worksheet.UsedRange.SpecialCells(xlCellTypeFormulas, xlErrors).Offset(0, -2).Clear
'
' clean up the formula
Range("F1:F" & Range("D65536").End(xlUp).Row).clear
'
End Sub
我希望有帮助
菲利普