Excel 更改代码以使用选择填充数组

Excel 更改代码以使用选择填充数组,excel,vba,Excel,Vba,我有一个工作代码,它做它应该做的。 我只想更改myStrings变量的填充方式 发件人: myStrings=Array(“Test23”、“Test-12”、“54-Test”) 致: myStrings=Selection.Value 如果我运行这个,我会得到一个运行时错误9;下标超出范围 目标是选择一些包含文本的单元格,总是同一列,只是不同的行,VBA宏应该从工作簿中删除每个工作表中包含该文本的所有行 我是VBA新手,我从不同的来源组合了这个,我不知道如何修复这个错误 我感谢任何帮助,或者

我有一个工作代码,它做它应该做的。 我只想更改
myStrings
变量的填充方式

发件人:

myStrings=Array(“Test23”、“Test-12”、“54-Test”)

致:

myStrings=Selection.Value

如果我运行这个,我会得到一个运行时错误9;下标超出范围

目标是选择一些包含文本的单元格,总是同一列,只是不同的行,VBA宏应该从工作簿中删除每个工作表中包含该文本的所有行

我是VBA新手,我从不同的来源组合了这个,我不知道如何修复这个错误

我感谢任何帮助,或者如果它做同样的事情,甚至是一个不同的解决方案

多谢各位

Option Explicit

Sub LoopThroughWorksheets()

Dim sh As Worksheet

For Each sh In ThisWorkbook.Worksheets

Dim calcmode As Long
Dim ViewMode As Long
Dim myStrings As Variant
Dim FoundCell As Range
Dim I As Long
Dim myRng As Range

     Set myRng = sh.Range("A:N")

     myStrings = Array("Test23", "Test-12", "54-Test")

With Application
    calcmode = .Calculation
    .Calculation = xlCalculationManual
    .ScreenUpdating = False
End With

       With sh

        .Select

        ViewMode = ActiveWindow.View
        ActiveWindow.View = xlNormalView


        .DisplayPageBreaks = False

            With myRng

            For I = LBound(myStrings) To UBound(myStrings)
                Do
                    Set FoundCell = myRng.Find(What:=myStrings(I), _
                                               After:=.Cells(.Cells.Count), _
                                               LookIn:=xlValues, _
                                               LookAt:=xlWhole, _
                                               SearchOrder:=xlByRows, _
                                               SearchDirection:=xlNext, _
                                               MatchCase:=False)
                    If FoundCell Is Nothing Then
                        Exit Do
                    Else
                        FoundCell.EntireRow.Delete
                    End If
                Loop
            Next I

        End With

    End With

With Application
    .ScreenUpdating = True
    .Calculation = calcmode
End With

    ActiveWindow.View = ViewMode

Next sh

MsgBox ("Completed")

End Sub

从工作表加载时,数组始终是二维数组。即使只有一列或一行。您需要这样对待它。请注意,您可以对其进行转置以将其返回到1D。请注意,转置是一个昂贵的操作,不必要,并且仅在选择单个列时返回1D数组。正如Scott所说,只需添加第二维度参考。无论如何,在继续之前,您应该检查选择范围的形状,您永远不知道您的用户可能会做什么。。。