Определить колонку vba excel

Свойства Column и Columns объекта Range в VBA Excel. Возвращение номера первого столбца и обращение к столбцам смежных и несмежных диапазонов.

Range.Column — свойство, которое возвращает номер первого столбца в указанном диапазоне.

Свойство Column объекта Range предназначено только для чтения, тип данных — Long.

Если диапазон состоит из нескольких областей (несмежный диапазон), свойство Range.Column возвращает номер первого столбца в первой области указанного диапазона:

Range(«B2:F10»).Select

MsgBox Selection.Column ‘Результат: 2

Range(«E1:F8,D4:G13,B2:F10»).Select

MsgBox Selection.Column ‘Результат: 5

Для возвращения номеров первых столбцов отдельных областей несмежного диапазона используется свойство Areas объекта Range:

Range(«E1:F8,D4:G13,B2:F10»).Select

MsgBox Selection.Areas(1).Column ‘Результат: 5

MsgBox Selection.Areas(2).Column ‘Результат: 4

MsgBox Selection.Areas(3).Column ‘Результат: 2

Свойство Range.Columns

Range.Columns — свойство, которое возвращает объект Range, представляющий коллекцию столбцов в указанном диапазоне.

Чтобы возвратить один столбец заданного диапазона, необходимо указать его порядковый номер (индекс) в скобках:

Set myRange = Range(«B4:D6»).Columns(1)  ‘Возвращается диапазон: $B$4:$B$6

Set myRange = Range(«B4:D6»).Columns(2)  ‘Возвращается диапазон: $C$4:$C$6

Set myRange = Range(«B4:D6»).Columns(3)  ‘Возвращается диапазон: $D$4:$D$6

Самое удивительное заключается в том, что выход индекса столбца за пределы указанного диапазона не приводит к ошибке, а возвращается диапазон, расположенный за пределами исходного диапазона (отсчет начинается с первого столбца заданного диапазона):

MsgBox Range(«B4:D6»).Columns(7).Address  ‘Результат: $H$4:$H$6

Если указанный объект Range является несмежным, состоящим из нескольких смежных диапазонов (областей), свойство Columns возвращает коллекцию столбцов первой области заданного диапазона. Для обращения к столбцам других областей указанного диапазона используется свойство Areas объекта Range:

Range(«E1:F8,D4:G13,B2:F10»).Select

MsgBox Selection.Areas(1).Columns(2).Address ‘Результат: $F$1:$F$8

MsgBox Selection.Areas(2).Columns(2).Address ‘Результат: $E$4:$E$13

MsgBox Selection.Areas(3).Columns(2).Address ‘Результат: $C$2:$C$10

Определение количества столбцов в диапазоне:

Dim c As Long

c = Range(«D5:J11»).Columns.Count

MsgBox c  ‘Результат: 7

Буква вместо номера

Если в качестве индекса столбца используется буква, она соответствует порядковому номеру этой буквы на рабочем листе:

  • "A" = 1;
  • "B" = 2;
  • "C" = 3;

и так далее.

Пример использования буквенного индекса вместо номера столбца в качестве аргумента свойства Columns объекта Range:

Range(«G2:K10»).Select

MsgBox Selection.Columns(2).Address ‘Результат: $H$2:$H$10

MsgBox Selection.Columns(«B»).Address ‘Результат: $H$2:$H$10

Обратите внимание, что свойство Range("G2:K10").Columns("B") возвращает диапазон $H$2:$H$10, а не $B$2:$B$10.


0 / 0 / 0

Регистрация: 16.09.2010

Сообщений: 9

1

Excel

Получение номера выделенной колонки

21.03.2011, 13:50. Показов 28302. Ответов 11


Студворк — интернет-сервис помощи студентам

Как получить номер выделенной колонки, т.е. выделил колону ‘С’, а он мне выдал, колонка ‘3’, а не ‘C:C’
Заранее спасибо



0



3944 / 2858 / 665

Регистрация: 08.06.2007

Сообщений: 9,666

Записей в блоге: 4

21.03.2011, 14:03

2

Selection.Column возвращает номер самой левой колонки выделения. Если выделение состоит из нескольких областей, то возвращается информация о первой выделенной области.



0



Masalov

22 / 5 / 1

Регистрация: 05.09.2010

Сообщений: 370

21.03.2011, 14:38

3

В некоторых случаях (н/р для сборки формул) необходимо знать буквенный эквивалент номера. Я написал функцию, ее иногда и использую. (Наверно есть и другие решения)

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Function НомерКолонкиСимволами(N)
  If N > 0 And N < 27 Then
    НомерКолонкиСимволами = Chr(N + 64)
    Exit Function
  End If
  x = Fix(N / 26)
  t = N - x * 26
  If t = 0 Then
    t = 26
    x = x - 1
  End If
  НомерКолонкиСимволами = Chr(x + 64)
  НомерКолонкиСимволами = НомерКолонкиСимволами & Chr(t + 64)
End Function



0



Laidi

0 / 0 / 0

Регистрация: 19.12.2010

Сообщений: 7

21.03.2011, 16:08

4

Мне кажется так проще :-)

Visual Basic
1
2
    n = Selection.Column()
    MsgBox n



0



pashulka

4131 / 2235 / 940

Регистрация: 01.12.2010

Сообщений: 4,624

21.03.2011, 16:16

5

В некоторых случаях, даже при вводе формул(функций) можно использовать номер столбца, например :

Использование WorksheetFunction :

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
iCellsOne = Cells(1, 1).Address
iCellsTwo = Cells(5, 1).Address
xRange = Range(iCellsOne & ':' & iCellsTwo)
iWFS = Application.Sum(xRange)
 
'или так :
 
iWFS = Application.Sum(Range(Cells(1, 1).Address & ':' & Cells(5, 1).Address))
 
'Ввод формулы/функции :
 
iCellsOne = Cells(1, 1).Address(RowAbsolute:=False, ColumnAbsolute:=False)
iCellsTwo = Cells(5, 1).Address(RowAbsolute:=False, ColumnAbsolute:=False)
 
Cells(6, 1).Value = '=SUM(' & iCellsOne & ':' & iCellsTwo & ')'
Cells(6, 1).Formula = '=SUM(' & iCellsOne & ':' & iCellsTwo & ')'
Cells(6, 1).FormulaLocal = '=СУММ(' & iCellsOne & ':' & iCellsTwo & ')'



0



pashulka

4131 / 2235 / 940

Регистрация: 01.12.2010

Сообщений: 4,624

21.03.2011, 20:42

6

Для получения буквенного обозначения столбца, можно использовать ActiveCell (более подробно можно прочитать в самом первом ответе)

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
'Вариант I(a).
 
iClmn = ActiveCell.Column
iAdr = ActiveCell.Address(RowAbsolute:=False, ColumnAbsolute:=False)
 
If iClmn > 26 Then
   iClmNa = Left(iAdr, 2)
Else
   iClmNa = Left(iAdr, 1)
End If
 
'Вариант I(b).
 
iClmn = ActiveCell.Column
iAdr = ActiveCell.Address
 
If iClmn > 26 Then
   iClmNa = Mid(iAdr, 2, 2)
Else
   iClmNa = Mid(iAdr, 2, 1)
End If

To Laidi
Нет не проще, так как несмотря на постановку вопроса, автору как раз и НЕ НУЖЕН номер столбца … прочитайте более внимательно сам вопрос, а не его заголовок



0



0 / 0 / 0

Регистрация: 16.09.2010

Сообщений: 9

22.03.2011, 10:30

 [ТС]

7

всем спасибо



0



mmos

4 / 4 / 2

Регистрация: 06.03.2011

Сообщений: 151

22.03.2011, 12:04

8

Проверенный преобразователь номера столбца в его текстовое обозначение:

Visual Basic
1
2
3
4
5
If NomerStolbca < 27 Then
NaimenStolbca = Chr(64 + NomerStolbca)
Else
NaimenStolbca = Chr(64 + (NomerStolbca - 1)  26) & Chr(65 + (NomerStolbca - 1) Mod 26)
End If

Носи на здоровье!



0



palva

3944 / 2858 / 665

Регистрация: 08.06.2007

Сообщений: 9,666

Записей в блоге: 4

22.03.2011, 12:48

9

Можно так:

Visual Basic
1
2
s = ActiveCell.Address
s = Mid(s, 2, InStr(2, s, '$') - 2)



0



Wulf007

23.01.2013, 11:09

10

Может, кому будет полезно:
Скрытие диапазона столбцов при номирации столбцов числом:

Скрывает только один столбец (как указать «с до» не нашёл)

Visual Basic
1
YYYY.Columns (ХХХХ).EntireColumn.Hidden = True

Где YYYY – что-нибудь
ХХХХ – колонка из YYYY
Кое-кто перебирает все значения, скрывая столбцы

Разбирался всего день. Но ответ нашел.
Вот как надо.

Visual Basic
1
2
3
4
 With Worksheets("YYYY")
               .Range(.Cells(7, столбец_от), _
               .Cells(7, столбец_до)).EntireColumn.Hidden = True
End With

ilich87

1 / 1 / 0

Регистрация: 22.01.2014

Сообщений: 10

22.01.2014, 11:35

11

Топик древний, но всё же.

Visual Basic
1
 Set rngRange = wsSheet.Columns(wsSheet.Cells(1, 1).Column)

В итоге а rngRange именно область с адресом «A:A», а для того что бы убрать $ не нужно ни чего придумывать

Visual Basic
1
addressmy = rngTRange.Address(0, 0)

даст вам именно строку «A:A» а не «$A:$A».



0



snipe

4038 / 1423 / 394

Регистрация: 07.08.2013

Сообщений: 3,541

22.01.2014, 13:41

12

Цитата
Сообщение от gas1979
Посмотреть сообщение

т.е. выделил колону ‘С’

Visual Basic
1
asd = Replace(Selection.Address, "$", "")



0



 

Zhennya2030

Пользователь

Сообщений: 21
Регистрация: 29.08.2013

#1

11.08.2014 16:13:34

Есть таблица в эксель например «Таблица1»  :)  
B2   C2 D2   E2    F2
Имя; Фамилия; Телефон; размер груди; наличие мозга

как в VBA узнать номер столбца по его названию (телефон) ?
что-то типа этого есть?

Код
Range("Таблица1") .Columns("Телефон") .column
 

Kuzmich

Пользователь

Сообщений: 7998
Регистрация: 21.12.2012

#2

11.08.2014 16:36:26

Код
Sub Telephon()
Dim Stolb As Integer
    Stolb = Rows(2).Find("Телефон", , xlValues, xlWhole).Column
End Sub
 
 

Кузьмич Спасибо!

а еще вариант естьтипа такого?
а= Range(«Таблица1″ ) .Cells(1,»Телефон» )

 

Ёк-Мок

Пользователь

Сообщений: 1775
Регистрация: 16.01.2013

#4

11.08.2014 17:03:32

Код
Sub Макрос()
For i = 2 To 6
If Cells(2, i).Value = "Телефон" Then a = Cells(2, i).Column
Next
End Sub

Удивление есть начало познания © Surprise me!
И да пребудет с нами сила ВПР.

 

Kuzmich

Пользователь

Сообщений: 7998
Регистрация: 21.12.2012

Cells(1,»Телефон» )    Что это за ячейка?

 

Zhennya2030

Пользователь

Сообщений: 21
Регистрация: 29.08.2013

#6

12.08.2014 08:27:33

скорее всего я очень плохо объясняю.
Полная задача в том, чтобы из экселя именованной таблицы, передать данные на SQL.
ну тупо пошли перебор таблицы по строкам.

Код
For i = 2 To Sheet1.Range("TAble_Table").Rows.Count
objRecordset.Fields("Phone") = Sheet1.Range("TAble_Table").Cells(i, "Telephone").Value

поэтому хотел просто в номер столбца заталкать что-то, что автоматом определяет его номер.
потому что, пользователь может поменять местами столбцы.

Думаю просто на отдельном «скрытом» листе определю их и оттуда буду брать номера.

Изменено: Zhennya203012.08.2014 10:51:42

 

забыл сказать!
Спасибо большое за помощь Kuzmich, Ёк-Мок !!!!

 

Андрей VG

Пользователь

Сообщений: 11878
Регистрация: 22.12.2012

Excel 2016, 365

#8

12.08.2014 08:50:55

Доброе время суток
Если вы используете «умную» таблицу, то можно и таким образом

Код
    Dim pLO As ListObject, iRow As Long
    Set pLO = ActiveSheet.ListObjects(1)
    For iRow = 1 To pLO.ListRows.Count
        objRecordset("Phone").Value = pLO.ListColumns("Telephone").DataBodyRange(iRow).Value
    Next
 

Успехов.

 

Zhennya2030

Пользователь

Сообщений: 21
Регистрация: 29.08.2013

#9

12.08.2014 09:41:57

Андрей VG, Спасибо большое!

title keywords f1_keywords ms.prod api_name ms.assetid ms.date ms.localizationpriority

Range.Find method (Excel)

vbaxl10.chm144128

vbaxl10.chm144128

excel

Excel.Range.Find

d9585265-8164-cb4d-a9e3-262f6e06b6b8

08/14/2019

high

Range.Find method (Excel)

Finds specific information in a range.

[!includeAdd-ins note]

Syntax

expression.Find (What, After, LookIn, LookAt, SearchOrder, SearchDirection, MatchCase, MatchByte, SearchFormat)

expression A variable that represents a Range object.

Parameters

Name Required/Optional Data type Description
What Required Variant The data to search for. Can be a string or any Microsoft Excel data type.
After Optional Variant The cell after which you want the search to begin. This corresponds to the position of the active cell when a search is done from the user interface.

Notice that After must be a single cell in the range. Remember that the search begins after this cell; the specified cell isn’t searched until the method wraps back around to this cell.

If you don’t specify this argument, the search starts after the cell in the upper-left corner of the range.

LookIn Optional Variant Can be one of the following XlFindLookIn constants: xlFormulas, xlValues, xlComments, or xlCommentsThreaded.
LookAt Optional Variant Can be one of the following XlLookAt constants: xlWhole or xlPart.
SearchOrder Optional Variant Can be one of the following XlSearchOrder constants: xlByRows or xlByColumns.
SearchDirection Optional Variant Can be one of the following XlSearchDirection constants: xlNext or xlPrevious.
MatchCase Optional Variant True to make the search case-sensitive. The default value is False.
MatchByte Optional Variant Used only if you have selected or installed double-byte language support. True to have double-byte characters match only double-byte characters. False to have double-byte characters match their single-byte equivalents.
SearchFormat Optional Variant The search format.

Return value

A Range object that represents the first cell where that information is found.

Remarks

This method returns Nothing if no match is found. The Find method does not affect the selection or the active cell.

The settings for LookIn, LookAt, SearchOrder, and MatchByte are saved each time you use this method. If you don’t specify values for these arguments the next time you call the method, the saved values are used. Setting these arguments changes the settings in the Find dialog box, and changing the settings in the Find dialog box changes the saved values that are used if you omit the arguments. To avoid problems, set these arguments explicitly each time you use this method.

Use the FindNext and FindPrevious methods to repeat the search.

When the search reaches the end of the specified search range, it wraps around to the beginning of the range. To stop a search when this wraparound occurs, save the address of the first found cell, and then test each successive found-cell address against this saved address.

To find cells that match more complicated patterns, use a For Each…Next statement with the Like operator. For example, the following code searches for all cells in the range A1:C5 that use a font whose name starts with the letters Cour. When Microsoft Excel finds a match, it changes the font to Times New Roman.

For Each c In [A1:C5] If c.Font.Name Like "Cour*" Then c.Font.Name = "Times New Roman" End If Next`

Examples

This example finds all cells in the range A1:A500 in worksheet one that contain the value 2, and changes the entire cell value to 5. That is, the values 1234 and 99299 both contain 2 and both cell values will become 5.

Sub FindValue()
    
    Dim c As Range
    Dim firstAddress As String

    With Worksheets(1).Range("A1:A500") 
        Set c = .Find(2, lookin:=xlValues) 
        If Not c Is Nothing Then 
            firstAddress = c.Address 
            Do 
                c.Value = 5 
                Set c = .FindNext(c) 
            Loop While Not c Is Nothing
        End If 
    End With
    
End Sub

This example finds all cells in the range A1:A500 on worksheet one that contain the substring «abc» and then replaces «abc» with «xyz».

Sub FindString()

    Dim c As Range
    Dim firstAddress As String

    With Worksheets(1).Range("A1:A500")
        Set c = .Find("abc", LookIn:=xlValues)
        If Not c Is Nothing Then
            firstAddress = c.Address
            Do
                c.Value = Replace(c.Value, "abc", "xyz")
                Set c = .FindNext(c)
            Loop While Not c Is Nothing
        End If
    End With

End Sub

[!includeSupport and feedback]

While you were looking for a VBA solution, this was my top result on google when looking for a formula solution, so I’ll add this for anyone who came here for that like I did:

Excel formula to return the number from a column letter (From @A. Klomp’s comment above), where cell A1 holds your column letter(s):

=column(indirect(A1&»1″))

As the indirect function is volatile, it recalculates whenever any cell is changed, so if you have a lot of these it could slow down your workbook. Consider another solution, such as the ‘code’ function, which gives you the number for an ASCII character, starting with ‘A’ at 65. Note that to do this you would need to check how many digits are in the column name, and alter the result depending on ‘A’, ‘BB’, or ‘CCC’.

Excel formula to return the column letter from a number (From this previous question How to convert a column number (eg. 127) into an excel column (eg. AA), answered by @Ian), where A1 holds your column number:

=substitute(address(1,A1,4),»1″,»»)

Note that both of these methods work regardless of how many letters are in the column name.

Hope this helps someone else.

Понравилась статья? Поделить с друзьями:
  • Определить колонки в excel
  • Определить количество строк в фильтре excel
  • Определить количество строк в таблице excel vba
  • Определить количество по значению ячейки в excel
  • Определить количество заполненных строк excel vba