从列中删除逗号,空格和“ NULL”字符串为0(零)

时间:2018-10-28 20:58:30

标签: excel vba excel-vba

我是Excel VBA的新手。

需要帮助从名为StringName的ColumnName中将逗号,空格和NULL字符串删除为“ 0”。

首先,我尝试从名为StringName的ColumnName中删除逗号和空格,最后找到并将“ NULL”字符串替换为0(零)。

这是用于替换逗号(位于列名中的空格,称为StringName)的代码。

Sub ReplaceCharacters()

  Application.ScreenUpdating = False
    Dim lrow As Long
    lrow = Cells(Cells.Rows.Count, "A").End(xlUp).Row
  With ActiveSheet.Range("A2:A" & lrow).SpecialCells(xlCellTypeConstants, xlTextValues).Cells
      .Replace What:=",", Replacement:="", LookAt:=xlPart
      .Replace What:=" ", Replacement:="", LookAt:=xlPart
  End With

  Application.ScreenUpdating = True

End Sub

我正在努力从名为StringName的ColumnName中查找并​​将字符串“ NULL”替换为0。

在这方面我需要帮助,我已经尝试了很多,最终在这里寻求解决方案。

这是我尝试过的。

' not working
Sub UpdateWhole()
    With ActiveSheet.UsedRange
    .Replace "NULL", "0", xlWhole
    End With
End Sub

' not working
Sub FormulaRng()
    For i = 2 To 10
       Worksheets("Sheet1").Range("A2:A" & i).FormulaR1C1 = "=IF(A" & i & "=""NULL"",0,A" & i & ")"
    Next
End Sub

预先感谢

screenshot

这是要测试的样本数据

StringName
------------------
NULL
NULL  
null 
nullasdf
cbgrgNULLdf343
, asdfwe 4fdt
456fg , d55nullNULL
sdf34      df,    4fd   
NULLfgf  null
121
22
34545

Required OutPut
------------------------
0
0
0
nullasdf
cbgrgNULLdf343
asdfwe4fdt
456fgd55nullNULL
sdf34df4fd
NULLfgfnull
121
22
34545

2 个答案:

答案 0 :(得分:0)

以下修改后的过程将为您服务。在将NULL文本替换为0之前,我使用了Clean函数从文本中删除了所有不可打印的字符。

VBA代码

Public Sub ReplaceCharacters()
On Error GoTo ErrTrap
Const ProcedureName As String = "ReplaceCharacters"
Dim sheet           As Worksheet: Set sheet = ActiveSheet
Dim cell            As Range

    Application.ScreenUpdating = False

    For Each cell In sheet.UsedRange.Cells
        cell = Trim(Application.WorksheetFunction.Clean(cell))
        cell.Replace What:="NULL", Replacement:=0, LookAt:=xlWhole
        cell.Replace What:=",", Replacement:="", LookAt:=xlPart
        cell.Replace What:=" ", Replacement:="", LookAt:=xlPart
    Next cell

ExitProcedure:
    On Error Resume Next
    Application.ScreenUpdating = True
    Set sheet = Nothing
    Exit Sub

ErrTrap:
    Select Case Err.number
        Case Else
            Debug.Print "Procedure: " & ProcedureName & " |Error #: " & Err.number & " |Error Description: " & Err.description
    End Select
    Resume ExitProcedure
    Resume 'for debugging

End Sub

示例视频

screenshot

答案 1 :(得分:0)

尝试一下。

Sub test()
    Dim Ws As Worksheet
    Dim rngDB As Range

    Set Ws = ActiveSheet
    With Ws
        Set rngDB = .Range("a2", .Range("a" & Rows.Count).End(xlUp))
    End With
    With rngDB
        .Replace What:=",", Replacement:="", LookAt:=xlPart
        .Replace What:=" ", Replacement:="", LookAt:=xlPart
        .Replace What:="NULL", Replacement:="0", LookAt:=xlWhole
        .Replace What:="null", Replacement:="0", LookAt:=xlWhole
    End With


End Sub