0

我想删除 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

我究竟做错了什么?

4

2 回答 2

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
于 2013-03-13T01:54:31.640 回答
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

我希望这会有所帮助

菲利普

于 2013-03-13T12:15:31.217 回答