对象'_Global'的方法'范围'选择范围时失败的错误VBA

时间:2013-01-02 20:18:54

标签: excel vba

所以我使用这个宏来仅提取执行回归所需的数据,并且样本集包含了相当多的无用信息以满足我的需求。当我尝试从CCDetail工作簿中选择列时 - 我得到对象'_Global'失败'的''范围'错误。有关为什么会这样的想法?

Sub ExtractCCDetail()

Dim WorkbookName As String
Dim CCDetail As Workbook
Dim Harvester As Workbook
Dim RAWData As Worksheet
Set CCDetail = Workbooks(2)
Set Harvester = ThisWorkbook

WorkbookName = CCDetail.Name
CCDetail.Activate
Set RAWData = Worksheets("Department Totals")
RAWData.Select
    'This is where the code will break
    Range( _
        "D:D,E:E,F:F,M:M,X:X,Y:Y,Z:Z,AA:AA,AC:AC,AD:AD,AE:AE,AF:AF,BD:BD,BF:BF," _
        ).Select
        Selection.Copy
    Harvester.Activate
    Sheets.Add After:=Sheets(Worksheets.Count), Count:=1
    ActiveSheet.Name = WorkbookName
    ActiveSheet.Paste
End Sub

*作为旁注 - 我已经测试了手动执行此操作,我没有遇到任何问题。我也尝试过调用

ActiveSheet.Range (wanted Range)

RAWData.Range (wanted range)

但这些都没有奏效。

1 个答案:

答案 0 :(得分:5)

问题是你的Range的参数中有一个额外的逗号。试试这个:

Range("D:D,E:E,F:F,M:M,X:X,Y:Y,Z:Z,AA:AA,AC:AC,AD:AD,AE:AE,AF:AF,BD:BD,BF:BF").Copy

如果您想稍微清理代码并避免使用Selects等,请尝试以下操作:

Sub ExtractCCDetail()

Dim WorkbookName As String
Dim CCDetail As Workbook
Dim Harvester As Workbook
Dim RAWData As Worksheet

Set CCDetail = Workbooks(2)
Set Harvester = ThisWorkbook

WorkbookName = CCDetail.Name

Set RAWData = CCDetail.Worksheets("Department Totals")

RAWData.Range("D:D,E:E,F:F,M:M,X:X,Y:Y,Z:Z,AA:AA,AC:AC,AD:AD,AE:AE,AF:AF,BD:BD,BF:BF").Copy

Dim wksCopy As Worksheet
Set wksCopy = Harvester.Sheets.Add(After:=Sheets(Worksheets.Count), Count:=1)

With wksCopy
    .Paste
    .Name = WorkbookName
End With

End Sub