选择带有空白单元格和备用空白单元格的整个列

时间:2018-08-07 15:59:15

标签: vba excel-vba

我想选择包含要复制名称的整个列,因为知道名称列号可以在电子表格和另一个电子表格之间改变,并且中间有一些空白单元格(缺少值)

假设“名称”列是B列,所以即使我想选择整个列,即使中间有一些空白单元格,我也可以使用以下代码:

Range("B2", Range("B" & Rows.Count).End(xlup)).Select

但是“名称”列号是可变的。所以我试图做到这样:

Sub ColSelection ()

Dim NameHeader As range 

'To select the header of Name column 

Set NameHeader = ActiveSheet.UsedRange.Find("Name")

ActiveSheet.Range(NameHeader.Offset(1,0), Range(NameHeader & Rows.Count).End(xlUp)).select 

' run tim error 1004 " Methode 'Range' of object '_Global' Failed 

End sub

我想我必须用他的列地址替换第二个NameHeader。怎么做?我是否应该设置Var来存储范围NameHeader的地址,并使用它。如果是这种情况,我应该如何设置此var,我的意思是尽可能长还是Variant..ect?

谢谢:)

3 个答案:

答案 0 :(得分:3)

这是您要尝试的吗?我已经注释了代码,因此您在理解它时应该不会有问题。但是,如果您仍然这样做,则可以发布查询。

这是您要尝试的吗?

Sub ColSelection()
    Dim NameHeader As Range
    Dim ws As Worksheet
    Dim ColName As String
    Dim LRow As Long
    Dim rng As Range

    Set ws = Sheet1 '<~~ Change as applicable

    With ws
        Set NameHeader = .UsedRange.Find("Name")

        '~~> Check if we found the text
        If Not NameHeader Is Nothing Then
            '~~> Get the Column Name
            ColName = Split(Cells(, NameHeader.Column).Address, "$")(1)

            '~~> Get the last row in that range
            LRow = .Range(ColName & .Rows.Count).End(xlUp).Row

            '~~> Construct your range
            Set rng = .Range(ColName & NameHeader.Row & ":" & ColName & LRow)

            With rng
                MsgBox .Address
                '~~> Do whatever you want with the range
            End With
        End If
    End With
End Sub

屏幕截图

Imgur无法上传图像,暂时拒绝了图像。稍后将直接更新。

http://prntscr.com/kftsad

答案 1 :(得分:1)

无需查看NameHeader.Address-只需使用其.Column-像这样(请注意,复制前不必Select Range。< / p>

Sub GrabNameCol()
    Dim NameHeader As Range
    Set NameHeader = ActiveSheet.UsedRange.Find("Name")

    If Not NameHeader Is Nothing Then
        ActiveSheet.Range(NameHeader.Offset(1), Cells(Rows.Count, NameHeader.Column).End(xlUp)).Select ' or just .Copy
    End If

End Sub

答案 2 :(得分:0)

sub test1a()

Dim NameHeader As Range
Set NameHeader = ActiveSheet.UsedRange.Find(InputBox("HEADER"))
If Not NameHeader Is Nothing Then
ActiveSheet.Range(NameHeader.Offset(1), Cells(Rows.Count, NameHeader.Column).End(xlUp)).Select
End If

结束子