如何调用多列的代码

时间:2013-04-26 19:39:38

标签: excel excel-vba vba

我需要在非连续的列上运行以下代码,这里有代码,关于如何为不同的代码执行此操作。 Add loop to vba code for excel

我需要做同样的事情:

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

1 个答案:

答案 0 :(得分: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"))