在excel VBA中选择多个列

时间:2018-06-14 16:08:06

标签: excel vba excel-vba excel-formula

我已经在网上搜索了这个并且发现很短...我正在使用这个VBA来根据列标题选择一个列。我想要做的还是选择当前被选中的一列右边的3列。要么是这个,要么让这个VBA循环通过多个列标题。

    Sub selectingcolumnstest()

Dim xRg As Range
Dim xRgUni As Range
Dim xFirstAddress As String
Dim xStr As String
    On Error Resume Next
    xStr = "ColumnNameHere"
    Set xRg = Range("A1:CD1").Find(xStr, , xlValues, xlWhole, , , True)
    If Not xRg Is Nothing Then
        xFirstAddress = xRg.Address
        Do
            Set xRg = Range("A1:CD1").FindNext(xRg)
            If xRgUni Is Nothing Then
                Set xRgUni = xRg
            Else
                Set xRgUni = Application.Union(xRgUni, xRg)
            End If
        Loop While (Not xRg Is Nothing) And (xRg.Address <> xFirstAddress)
    End If
    xRgUni.EntireColumn.Select



End Sub

&#34; ColumnNameHere&#34;右边有3个附加列。我也想选择..(我要删除这些列)。有什么建议吗?

1 个答案:

答案 0 :(得分:0)

尝试,

Dim xStr As String, hdr as variant

xStr = "ColumnNameHere"

hdr = application.match(xStr, Range("A1:CD1"), 0)

if not iserror(hdr) then
    cells(1, hdr).resize(1, 4).entirecolumn.select
    'cells(1, hdr).resize(1, 4).entirecolumn.delete
end if