在不同的工作表上运行宏但在同一工作簿上时出错

时间:2016-10-06 04:04:24

标签: vba excel-vba excel

我收到以下错误运行时

  

错误' 1004',选择范围类失败的方法

尝试在不同的工作表上运行以下代码但在同一工作簿上运行。

Sub AdministrationReport()

Dim report               As Workbook
Dim admiistration        As Workbook
Dim wbPath               As String

'report is the active workbook where data is being pasted
Set report = ActiveWorkbook ' (till here it opens new workbook - I have deleted that code to shorten the question)

' set administration to Open workbook from where data will be copied
Set administration = Workbooks.Open(wbPath)
administration.Worksheets("Administration_POWHS Standardis").Range("A2:j100").Copy Destination:=report.Worksheets("administration").Range("A2:j100")
ActiveWorkbook.Close

'this is to format report data    
Set report = ActiveWorkbook

**report.Worksheets("administration").Range("a2:d100").Select**- stuck here

With Selection
    .HorizontalAlignment = xlLeft
    .VerticalAlignment = xlCenter
    .WrapText = True
    .Orientation = 90
    .ReadingOrder = xlContext
End With

2 个答案:

答案 0 :(得分:1)

您是否尝试过添加

report.Worksheets("administration").Select

之前

report.Worksheets("administration").Range("a2:d100").Select

答案 1 :(得分:1)

您不需要Select范围,只需使用下面的With声明(它适用于您从每张工作表运行它):

With report.Worksheets("administration").Range("A2:D100")
    .HorizontalAlignment = xlLeft
    .VerticalAlignment = xlCenter
    .WrapText = True
    .Orientation = 90
    .ReadingOrder = xlContext
End With