Перейти до основного матеріалу

 Як вибрати стовпець на основі заголовка стовпця в Excel?

Припустимо, у вас є великий аркуш, який містить кілька стовпців, і тепер ви хотіли б вибрати конкретний стовпець на основі імені заголовка стовпця. Щоб знайти стовпець за стовпчиком на великому аркуші, ви витратите багато часу, у цій статті я представив швидкий метод вирішення цієї роботи в Excel.

Виберіть стовпець на основі назви заголовка стовпця з кодом VBA


Виберіть стовпець на основі назви заголовка стовпця з кодом VBA

Наступний код VBA може допомогти вам вибрати стовпці на основі конкретного імені заголовка, будь-ласка, зробіть так:

1. Утримуйте клавішу ALT + F11 ключі, щоб відкрити Microsoft Visual Basic для додатків вікна.

2. Клацання Insert > Модуліта вставте наступний код у Модулі Вікно

Код VBA: Виберіть стовпець на основі назви заголовка стовпця:

Sub FindAddressColumn()
'Updateby Extendoffcie
    Dim xRg As Range
    Dim xRgUni As Range
    Dim xFirstAddress As String
    Dim xStr As String
    On Error Resume Next
    xStr = "Name"
    Set xRg = Range("A1:P1").Find(xStr, , xlValues, xlWhole, , , True)
    If Not xRg Is Nothing Then
        xFirstAddress = xRg.Address
        Do
            Set xRg = Range("A1:P1").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

примітки: У наведеному вище коді, A1: P1 - діапазон заголовків, з яких потрібно вибрати стовпці, і “ІМ'Я”У сценарії xStr = "Ім'я" - це назва заголовка, на основі якого потрібно вибрати стовпці. Будь ласка, змініть їх на свої потреби.

3. Після копіювання та вставки коду, натисніть F5 для запуску цього коду, і всі стовпці з конкретним іменем заголовка були вибрані відразу, див. знімок екрана:

Найкращі інструменти продуктивності офісу

🤖 Kutools AI Aide: Революціонізуйте аналіз даних на основі: Інтелектуальне виконання   |  Згенерувати код  |  Створення спеціальних формул  |  Аналізуйте дані та створюйте діаграми  |  Викликати функції Kutools...
Популярні функції: Знайдіть, виділіть або визначте дублікати   |  Видалити порожні рядки   |  Об’єднайте стовпці або клітинки без втрати даних   |   Раунд без Формули ...
Супер пошук: VLookup за кількома критеріями    Багатозначний VLookup  |   VLookup на кількох аркушах   |   Нечіткий пошук ....
Розширений розкривний список: Швидке створення випадаючого списку   |  Залежний спадний список   |  Виберіть розкривний список, що вибирається ....
Менеджер колонок: Додайте конкретну кількість стовпців  |  Перемістити стовпці  |  Перемкнути статус видимості прихованих стовпців  |  Порівняйте діапазони та стовпці ...
Особливості: Фокус сітки   |  Перегляд дизайну   |   Велика панель формул    Диспетчер робочих книг і аркушів   |  Бібліотека ресурсів (автотекст)   |  Вибір дати   |  Об’єднайте робочі аркуші   |  Шифрування/розшифрування клітинок    Надсилайте листи за списком   |  Супер фільтр   |   Спеціальний фільтр (фільтр жирний/курсив/закреслений...) ...
Топ-15 наборів інструментів12 текст Tools (додати текст, Видалити символи, ...)   |   50 + Графік типи (діаграма Ганта, ...)   |   40+ Практичний Формули (Розрахуйте вік на основі дня народження, ...)   |   19 вставка Tools (Вставте QR-код, Вставити зображення зі шляху, ...)   |   12 Перетворення Tools (Числа до слів, Валютна конверсія, ...)   |   7 Злиття та розділення Tools (Розширені комбіновані ряди, Розділені клітини, ...)   |   ... і більше

Покращуйте свої навички Excel за допомогою Kutools для Excel і відчуйте ефективність, як ніколи раніше. Kutools для Excel пропонує понад 300 додаткових функцій для підвищення продуктивності та економії часу.  Натисніть тут, щоб отримати функцію, яка вам найбільше потрібна...

Опис


Вкладка Office Передає інтерфейс із вкладками в Office і значно полегшує вашу роботу

  • Увімкніть редагування та читання на вкладках у Word, Excel, PowerPoint, Publisher, Access, Visio та Project.
  • Відкривайте та створюйте кілька документів на нових вкладках того самого вікна, а не в нових вікнах.
  • Збільшує вашу продуктивність на 50% та зменшує сотні клацань миші для вас щодня!
Comments (8)
No ratings yet. Be the first to rate!
This comment was minimized by the moderator on the site
Good job, works great!
This comment was minimized by the moderator on the site
Hi everyone...

How can I make it so that only the column data is selected, without the header, instead of the entire column?

Thanks
This comment was minimized by the moderator on the site
Thank you spo much saved my day !
This comment was minimized by the moderator on the site
Thanks - at first it seemed to work, but then I noticed it didn't include the first-found column - it started with the second and on.

Which is explainable: you set xRg twice, but you do not include the first one.

TBH: initially I thought it worked fine, but then that 'error' showed up and I had to figure out why....

I fixed it as follows: (in Excel the comments will turn green and show my edits: '***)

<code>

Sub FindAddressColumn()

'Updateby Extendoffcie

Dim xRg As Range

Dim xRgUni As Range

Dim xFirstAddress As String

Dim xStr As String

On Error Resume Next
xStr = "Name"
Set xRg = Range("A1:P1").Find(xStr, , xlValues, xlPart, , , True)

If Not xRg Is Nothing Then

xFirstAddress = xRg.Address

Do

If xRgUni Is Nothing Then

Set xRgUni = Range(xFirstAddress) '*** Using the first-found range

Else

Set xRgUni = Application.Union(xRgUni, xRg)

End If



Set xRg = Range("A1:P1").FindNext(xRg) '*** Now searching for the second/next ones



Loop While (Not xRg Is Nothing) And (xRg.Address <> xFirstAddress)

End If

xRgUni.EntireColumn.Select

End Sub


</code>

This now works for me, but I hope to learn from you if I overlooked anything.
This comment was minimized by the moderator on the site
Hi, Can you suggest the macro for the issue mentioned below by Shaun
This comment was minimized by the moderator on the site
Hi, looks great work. But I am getting the compile error: Argument not optional while highlighting the ". Union". What should I do?
This comment was minimized by the moderator on the site
This is great, but what if I wanted to copy say, CustomerName, OrderNumber, OrderDate, FulfillmentDate, OrderStatus from Sheet1 with many more columns.
How do I only specify the columns that are needed to be copied to another sheet? This seems to only specify one column.
I have tried some things, but the problem is more where the columns are not necesarily in the same order on the source sheet. The source data in Sheet1 is pasted from the Windows clipboard to the Excel sheet.

It may be, CustomerName, OrderDate, OrderNumber, OrderStatusm FulfillmentDate or some other order.

I need them to be copied into a new sheet in a specific order as there are formulas in Sheet2 that are applied to what is copied from Sheet1 to Sheet2.

Other than shifting columns around after pasting from Windows clipboard, I can't figure this out.

Please help if possible.

Thank you kindly for the above though.
This comment was minimized by the moderator on the site
Dim xRg As Range
Dim xRgUni As Range
Dim xFirstAddress As String
Dim xStr As String

Are variables being declared.

Hence to use the above code again for another column you would have to declare new variables.

Dim xRg2 As Range
Dim xRgUni2 As Range
Dim xFirstAddress2 As String
Dim xStr2 As String

And replace every instance of xRg with xRg2 in the code ect. Does that make sense?
There are no comments posted here yet
Please leave your comments in English
Posting as Guest
×
Rate this post:
0   Characters
Suggested Locations