Use User-defined range as input for cell parsing

2019-08-23 20:57发布

I'm writing a macro in Excel 2010 in order to remove line breaks in multiple cells of a column. This cells need to be selected by the user. Following this previous post I was able to create an InputBox to let the user select the range but now, I am unable to process the data within the selection.
My previous code without the selection range parsed an entire column with a regexp to find a pattern in the string within the cells and change its contents. I did this with a For i To Rows.Count block of code like this:

For i = 1 To Rows.Count

    If Not IsEmpty(Cells(i, 5).Value) Then
       varString = Sheets(ActiveSheet.Name).Cells(i, 5).Text
       Sheets(ActiveSheet.Name).Cells(i,5).Value=objRegExp.Replace(varString, "$1 ")
    End If
Next i

Now I want to replace the static column so I can process only the user range. In order to achieve that I tried this:

Set selection = Application.InputBox(Prompt:= _
            "Please select a range to apply the remove break lines procedure.", _
                Title:="Remove Line Breaks", Type:=8)

If selection Is Nothing Then
    Exit Sub
End If

Set RowsNumber = selection.CurrentRegion -> This line gives me an error: "Object required"
Set RowsNumber = RowsNumber.Rows.Count

For i = 1 To RowsNumber
    If Not IsEmpty(Cells(i, 5).Value) Then 
       varString = Sheets(ActiveSheet.Name).Cells(i, 5).Text 
       Sheets(ActiveSheet.Name).Cells(i, 5).Value = objRegExp.Replace(varString, "$1 ") 'Replace pattern found with regular expression in the same line
    End If
Next i

How can I access the cells in the range returned by the InputBox?
I also tried changing RowsNumber with selection.Rows.Count but that way, although it doesn't gives an error, the cells used have blank string within them when I run the debugger. I think this is because I try to access row = 5 when the range could be less, i.e 3 if user just selects 3 cells.
I tried a For Each Next loop but then again, I know not how to access the cells withing the selection range.

1条回答
我想做一个坏孩纸
2楼-- · 2019-08-23 21:23

You can iterate through the cells of a range by using For Each loop.

Below is your code modified. I have changed the name of variable Selection to rng, because Selection is Excel library built-in function and this name should be avoided.

Sub x()
    Dim rng As Excel.Range
    Dim cell As Excel.Range


    Set rng = Application.InputBox(Prompt:= _
                "Please select a range to apply the remove break lines procedure.", _
                    Title:="Remove Line Breaks", Type:=8)

    If rng Is Nothing Then
        Exit Sub
    End If

    For Each cell In rng.Cells
        If Not IsEmpty(cell.Value) Then
           varString = cell.Text
           cell.Value = objRegExp.Replace(varString, "$1 ") 'Replace pattern found with regular expression in the same line
        End If
    Next cell

End Sub
查看更多
登录 后发表回答