Excel VBA在动态范围的工作表上运行宏

时间:2017-11-15 10:16:32

标签: excel vba excel-vba

作为我上一个问题的扩展,我试图在所有工作表中运行一个宏,你们成功地帮助我做了。 我被告知工作表名称不能硬编码,因此我将不得不修改我当前的解决方案。

Sub RemoveCarriageReturns()
Dim MyRange As Range
Dim NameList() As Variant
NameList = Array("OTCUEXTR", "OTFBCUDS", "OTFBCUEL")
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual

For i = 0 To 2
    With Worksheets(NameList(i))
        For Each MyRange In .UsedRange
            If 0 < InStr(MyRange, Chr(10)) Then
                MyRange = Replace(MyRange, Chr(10), "")
            End If
        Next MyRange
    End With
Next i

Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
End Sub

我尝试使用For循环填充数组,收集每个工作表的名称,但是我觉得在2天后茫然地盯着这个,我有限的VBA知识已经用完而且我被卡住了,我真的很感激一些关于如何让这个宏在一系列可以改变数量和名称的工作表上工作的指针。

很高兴在评论中提供您需要的更多信息

2 个答案:

答案 0 :(得分:3)

您可以这样做(或者可以使用原始代码的索引)。

Sub RemoveCarriageReturns()

Dim MyRange As Range
Dim ws As Worksheet

Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual

For Each ws In Worksheets
    With ws
        For Each MyRange In .UsedRange
            If 0 < InStr(MyRange, Chr(10)) Then
                MyRange = Replace(MyRange, Chr(10), "")
            End If
        Next MyRange
    End With
Next ws

Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic

End Sub

答案 1 :(得分:0)

Public Function GetSheetNames(ByVal wbk As workbook) As String()
    Dim names() As String
    Dim count As Integer
    Dim i As Integer

        count = wbk.Worksheets.count

        ReDim names(count - 1)
        For i = 1 To wbk.Worksheets.count
            names(i - 1) = wbk.Worksheets(i).Name
        Next

        GetSheetNames = names

    End Function

用法:GetSheetNames(Application.ActiveWorkbook)

更新:仅适用于选定的工作表:

Public Function GetActiveSheetNames(ByVal wbk As workbook) As String()
Dim names() As String
Dim count As Integer
Dim i As Integer

    count = wbk.Windows(1).SelectedSheets.count

    ReDim names(count - 1)
    For i = 1 To wbk.Windows(1).SelectedSheets.count
        names(i - 1) = wbk.Windows(1).SelectedSheets(i).Name
    Next

    GetActiveSheetNames = names

End Function