使用特定的工作表并选择范围;运行时错误91

时间:2017-02-17 16:57:23

标签: excel vba excel-vba

我试图在一个工作表中获取某个列,并且(最终还没有编写代码)将其复制到另一个工作簿中的另一个工作表。我收到运行时错误91,当我试图找到解决方法时,我将得到1004的运行时错误。

Sub User_Rolee()
    Dim UserRoleWkb As Workbook, ConfigWkb As Workbook, UserRoleWkst As Worksheet, ConfigWkst As Worksheet
    Set UserRoleWkb = Workbooks.Open("C:\Users\clara\Desktop\S_User_Role_Map_TEMPLATE_V2_BLANK.xlsx")
    Set ConfigWkb = ActiveWorkbook
    'Set ConfigWkb = Workbooks.Open("C:\Users\clara\Desktop\Configuration Workbook - Paramaribo.xlsm")
    Set UserRoleWkst = UserRoleWkb.Sheets("Users")
    Set ConfigWkst = ConfigWkb.ActiveSheet
    Dim rng, rnga As Range

    With ConfigWkst
        Set rng = .Columns(2).Find(What:="Procurement Agent")
        Set rnga = .rng.Offset(1) 'runtime error 91
        Set rngar = .Range(rnga, rnga.End(xlDown)).Select
    End With        
End Sub

1 个答案:

答案 0 :(得分:0)

根据我的上述评论,请尝试以下代码:

(请参阅前一行中的评论,您也从未在任何地方定义rngar。)

Option Explicit

Sub User_Rolee()

Dim UserRoleWkb As Workbook, ConfigWkb As Workbook, UserRoleWkst As Worksheet, ConfigWkst As Worksheet
Dim rng As Range, rnga As Range, rngar  As Range

Set UserRoleWkb = Workbooks.Open("C:\Users\clara\Desktop\S_User_Role_Map_TEMPLATE_V2_BLANK.xlsx")
Set ConfigWkb = ThisWorkbook

'Set ConfigWkb = Workbooks.Open("C:\Users\clara\Desktop\Configuration Workbook - Paramaribo.xlsm")
Set UserRoleWkst = UserRoleWkb.Sheets("Users")
Set ConfigWkst = ConfigWkb.Worksheets("Sheet1") '<-- modify "Sheet1" to your sheet's name

With ConfigWkst
    Set rng = .Columns(2).Find(What:="Procurement Agent")

    If Not rng Is Nothing Then '<-- find was successful
        Set rnga = rng.Offset(1)
        Set rngar = Range(rnga, rnga.End(xlDown))
        rngar.Copy '<-- copy the Range
    End If
End With
End Sub