如何将特定列中的所有空格替换为指定的字符串?

时间:2017-03-23 18:44:38

标签: excel vba

我正在使用以下VBA代码,并总结了一些调查结果:

Sub Main()


   ReplaceBlanks
   Multi_FindReplace

End Sub


Sub ReplaceBlanks()

Dim ws As Worksheet
Dim lastrow As Long
Dim rng As Range

Set ws = Sheets("Refined")
lastrow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row

For i = 2 To lastrow
     If WorksheetFunction.CountA(ws.Range(ws.Cells(i, 17), ws.Cells(i, 21))) = 0 Then
        If Not rng Is Nothing Then
              Set rng = Union(ws.Cells(i, 1), rng)
        Else
              Set rng = ws.Cells(i, 1)
        End If
     End If
Next i

rng.EntireRow.Delete


End Sub


Sub Multi_FindReplace()
'PURPOSE: Find & Replace a list of text/values throughout entire workbook
'SOURCE: www.TheSpreadsheetGuru.com/the-code-vault

Dim fndList As Variant
Dim rplcList As Variant
Dim x As Long

fndList = Array("Mostly satisfied", "Completely satisfied", "N/A", "Not at all satisfied")
rplcList = Array("Satisfied", "Satisfied", "Satisfied", "Not satisfied")



Set sht = ActiveWorkbook.Sheets("Refined")

'Loop through each item in Array lists
  For x = LBound(fndList) To UBound(fndList)
    'Loop through each worksheet in ActiveWorkbook

        sht.Cells.Replace What:=fndList(x), Replacement:=rplcList(x), _
          LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _
          SearchFormat:=False, ReplaceFormat:=False


  Next x

End Sub

此代码生成的输出仅显示短语“满意”或“不满意”。下图显示了它的外观:

enter image description here

然而,当它完成时它也会显示一些空白单元格,我还想说“满意”(但我们只想在删除调查受访者根本没有回答任何问题的空行后执行此操作(这已经由“ReplaceBlanks”子功能完成。

我想要关注的空白单元格只是那些在Q3到U3列,然后是W3到Z3,最后是AB3到AC3向下的空白单元格(即我不知道这些列中有多少行,但至少有一个,从第3行开始。)

我不确定如何只关注这3组列,但我在第一组上尝试了以下代码:

Sub dural()
    Dim r As Range, LastRow As Long
    LastRow = Cells(Rows.Count, 2).End(xlUp).Row
    For Each r In Range("Q3:U19" & LastRow)
        If r.Text = "" Then r.Value = "Satisfied"
    Next r
End Sub

但是这个人把“满意”放在了我需要的那组以下的一千多行中!

任何提示表示赞赏,谢谢

1 个答案:

答案 0 :(得分:1)

试试这个:

Sub dural()    
    With Sheets("Refined")
        Intersect(.UsedRange, .Range("Q:U, W:Z, AB:AC")).SpecialCells(xlCellTypeBlanks).Value = "Satisfied"
    End With
End Sub

BTW:"Q3:U19" & LastRow必然会返回一些“Q3:Q19xxx”地址,xxx等于LastRow ......