选择已使用范围的列(不包括标题,但使用特定标题作为目标)

时间:2018-06-22 08:43:12

标签: excel vba excel-vba

我正在尝试制作一个宏,以使用ID标头作为目标来选择特定的列。我不会使用列数,因为ID列可以在电子表格和其他电子表格之间改变。所以我使用了.find函数。

最终目的是复制此列

错误消息:

  

运行时错误'1004':应用程序定义的错误或对象定义的错误。

非常感谢您的帮助,如果您有达到目标的其他策略,请分享。

Sub SelectCol ()

Dim WorkSH As Worksheet 

Dim TargetCell As Range
Dim FirstCell As Range
Dim LastCell As Range
Dim ColToCopy As Range

Dim RowNbr As Long 
Dim ColNbr As Long

Set WorkSh = ActiveSheet 

Set TargetCell = WorkSh.UsedRange.Find ("Id")

TargetCell.Select

Set FirstCell = ActiveCell.Offset( 1,0 ) 

ColNbr = FirstCell.Column

' If Possible I want to remove "c" and replace it with rhe Var "ColNbr"

RowNbr = WorkSh.Cells( WorkSh.Rows.Count, "C"). End(XlUp).Row


'line doesn't work even if I set this cells basically like this Cells(5, 8957) 'Which is very bizzare

Set LastCell = Cells (RowNbr, ColNbr) 

Set ColToCopy = Range ( FirstCell, LastCell ) 

ColToCopy.Copy
End Sub

2 个答案:

答案 0 :(得分:1)

您的代码对我来说实际上可以正常运行。就是说,我整理了一下:

Sub SelectCol()

Dim TargetCell As Range
Dim RowNbr As Long

With ThisWorkbook.ActiveSheet
    Set TargetCell = .UsedRange.Find("Id")
    If Not TargetCell Is Nothing Then
        RowNbr = .Cells(.Rows.Count, TargetCell.Column).End(xlUp).Row
        .Range(TargetCell.Offset(1, 0), .Cells(RowNbr, TargetCell.Column)).Copy
    End If
End With
End Sub

所需变量较少,因为我尝试不使用一次性变量。

With ThisWorkbook.ActiveSheet确保您正在处理自己认为的工作表。此外,它允许使用此Set TargetCell = .UsedRange.Find("Id")而不是更长的

Set TargetCell = ThisWorkbook.ActiveSheet.UsedRange.Find("Id")

If Not TargetCell Is Nothing测试是否找到了"Id",因为如果找不到RowNbr,将无法对其进行设置。 TargetCell.Column = 0。

答案 1 :(得分:0)

“应用程序定义的错误或对象定义的错误”表示对象存在错误。在您的代码中,您有以下内容:

Dim TargetCell, FirstCell, LastCell, ColToCopy As Range

这意味着TargetCellFirstCellLastCell被声明为Variant类型而不是Range Objects类型的变量。要将它们声明为范围对象,请执行以下操作:

Dim TargetCell As Range
Dim FirstCell As Range
Dim LastCell As Range
Dim ColToCopy As Range