0

我需要在非连续列上运行以下代码,此处发布了有关如何为不同的代码执行此操作的代码。 将循环添加到 Excel 的 vba 代码

我需要做同样的事情:

Sub CleanAll()
    Dim rng As Range

    For Each rng In Sheets("Sheet1").Range("D2:D100").Cells 'adjust sheetname and range   accordingly
        rng.Value = TextOnly(rng.Value)
    Next
End Sub

我失败的努力

Sub CleanAll(sColRange As String)
    Dim rng As Range

    For Each rng In Sheets("Sheet1").Range(sColRange).Cells 'adjust sheetname and range accordingly
        rng.Value = TextOnly(rng.Value)
    Next
End Sub

像这样使用:

Call CleanAll("B2")
Call CleanAll("H2")

谢谢

编辑

以上调用以下

Function TextOnly(strSource As String) As String
    Dim i As Integer
    Dim strResult As String

    For i = 1 To Len(strSource)
        Select Case Asc(Mid(strSource, i, 1))
            Case 48 To 57, 65 To 90, 97 To 122: 'include 32 if you want to include space
                strResult = strResult & Mid(strSource, i, 1)
        End Select
    Next
    AlphaNumericOnly = strResult
End Function
4

1 回答 1

2

为什么不简单地将范围传递给子程序?

Sub CleanAll(range as Range)
    Dim rng As Range

    For Each rng In range.Cells 
        rng.Value = TextOnly(rng.Value)
    Next
End Sub

然后你可以通过

CleanAll(Sheets("Sheet1").Range("A1:A100"))
于 2013-04-27T01:43:30.373 回答