Vba代码获取错误“范围类的选择方法失败”

时间:2018-01-17 06:35:41

标签: excel vba excel-vba runtime-error

在下面的代码中,我在指示的行上收到错误“Select Method of Range Class Failed”。

我正在尝试将Worksheet A Workbook XY的一些固定范围复制到所有打开的工作簿的Worksheet A。请帮我解决这些问题。此外,建议采用更好或更优化的方法。提前致谢。

Sub Macro1()
    Dim wbs As Workbooks
    Dim wb As Workbook
    Dim ws11111 As Worksheet
    Set wbs = Application.Workbooks
    For Each wb In wbs
    Set ws11111 = wb.Worksheets("A")

  '' ERROR BREAKS ON NEXT LINE:
    wb.Worksheets("A").Rows("1:1").Select
  '' ERROR: "Select Method of Range Class Failed"

    Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
    Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
    Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
    Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
    Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
    Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
    Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
    Next wb
    Windows("XY.xlsx").Activate
    Worksheets("A").Select
    Workbooks("XY.xlsx").Worksheets("A").Range("E2:M6").Select
    Selection.Copy
    For Each wb In wbs
        wb.Worksheets("A").Range("E2:M6").Select
        ActiveSheet.Paste
    Next wb
    Windows("XY.xlsx").Activate
    Worksheets("A").Select
    Workbooks("XY.xlsx").Worksheets("A").Columns("D:D").Select
    Application.CutCopyMode = False
    Selection.Delete Shift:=xlToLeft
    Workbooks("XY.xlsx").Worksheets("A").Rows("9:9").Select
    Selection.Copy
    For Each wb In wbs
        wb.Worksheets("A").Rows("8:8").Select
        ActiveSheet.Paste
    Next wb
End Sub

1 个答案:

答案 0 :(得分:0)

如果要在某个范围内使用.Select方法,则必须确保按顺序选择相应的工作簿工作表

wb.Activate
ws11111.Activate
ws11111.Rows("1:1").Select

正如您所看到的,.Select方法的使用可能有点单调乏味且速度也很慢。这就是为什么我建议你在有机会的时候看看这个问题:How to avoid using Select in Excel VBA