Текущий столбец excel vba

Добрый день.

Помогите пжста  переделать макрос.
Сейчас действие выполняется только для столбца «А» — Cells(Rows.Count, «A»),

как сделать так что бы столбец автоматически определялся по текущей выделенной ячейке ?

Код
Option Explicit
Option Compare Text

Sub XXXX()
Dim i%, box As String
     With Sheets(1)
     box = InputBox("Укажите номер БЕ", "_", "1200")
     If box <> "" Then
        For i = 1 To Cells(Rows.Count, "A").End(xlUp).Row
            If (Left(Cells(i, 1), 4) <> "Z_BW") _
            And (Left(Cells(i, 1), 2) <> "Y_") _
            And (Left(Cells(i, 1), 3) <> "ZSA") _
            Then Cells(i, 1) = Cells(i, 1) & "_" & box
        Next
    End If
    End With
End Sub

Свойства 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. Показов 28311. Ответов 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



VBA Columns

Excel VBA Columns Property

We all are well aware of the fact that an Excel Worksheet is arranged in columns and rows and each intersection of rows and columns is considered as a cell. Whenever we want to refer a cell in Excel through VBA, we can use the Range or Cells properties. What if we want to refer the columns from Excel worksheet? Is there any function which we can use to refer the same? The answer is a big YES!

Yes, there is a property in VBA called “Columns” which helps you in referring as well as returning the column from given Excel Worksheet. We can refer any column from the worksheet using this property and can manipulate the same.

Syntax of VBA Columns:

The syntax for VBA Columns property is as shown below:

Synatx of Columns Property

Where,

  • RowIndex – Represents the row number from which the cells have to be retrieved.
  • ColumnIndex – Represents the column number which is in an intersection with the respective rows and cells.

Obviously, which column needs to be included/used for further proceedings is being used by these two arguments. Both are optional and if not provided by default would be considered as the first row and first column.

How to Use Columns Property in Excel VBA?

Below are the different examples to use columns property in excel using VBA code.

You can download this VBA Columns Excel Template here – VBA Columns Excel Template

Example #1 – Select Column using VBA Columns Property

We will see how a column can be selected from a worksheet using VBA Columns property. For this, follow the below steps:

Step 1: Insert a new module under Visual Basic Editor (VBE) where you can write the block of codes. Click on Insert tab and select Module in VBA pane.

Insert Module

Step 2: Define a new sub-procedure which can hold the macro you are about to write.

Code:

Sub Example_1()

End Sub

VBA Columns Example 1-2

Step 3: Use Columns.Select property from VBA to select the first column from your worksheet. This actually has different ways, you can use Columns(1).Select initially. See the screenshot below:

Code:

Sub Example_1()

Columns(1).Select

End Sub

VBA Columns Example 1-3

The Columns property in this small piece of code specifies the column number and Select property allows the VBA to select the column. Therefore in this code, Column 1 is selected based on the given inputs.

Step 4: Hit F5 or click on the Run button to run this code and see the output. You can see that column 1 will be selected in your excel sheet.

VBA Columns Example 1-4

This is one way to use columns property to select a column from a worksheet. We can also use the column names instead of column numbers in the code. Below code also gives the same result.

Code:

Sub Example_1()

Columns("A").Select

End Sub

VBA Columns Example 1-5

Example #2 – VBA Columns as a Worksheet Function

If we are using the Columns property without any qualifier, then it will only work on all the Active worksheets present in a workbook. However, in order to make the code more secure, we can use the worksheet qualifier with columns and make our code more secure. Follow the steps below:

Step 1: Define a new sub-procedure which can hold the macro under the module.

Code:

Sub Example_2()

End Sub

VBA Columns Example 2-1

Now we are going to use Worksheets.Columns property to select a column from a specified worksheet.

Step 2: Start typing the Worksheets qualifier under given macro. This qualifier needs the name of the worksheet, specify the sheet name as “Example 2” (Don’t forget to add the parentheses). This will allow the system to access the worksheet named Example 2 from the current workbook.

Code:

Sub Example_2()

Worksheets("Example 2")

End Sub

Worksheets Qualifier - Example 2

Step 3: Now use Columns property which will allow you to perform different column operations on a selected worksheet. I will choose the 4th column. I either can choose it by writing the index as 4 or specifying the column alphabet which is “D”.

Code:

Sub Example_2()

Worksheets("Example 2").Columns("D")

End Sub

VBA Columns Example 2-3

As of here, we have selected a worksheet named Example 2 and accessed the column D from it. Now, we need to perform some operations on the column accessed.

Step 4: Use Select property after Columns to select the column specified in the current worksheet.

Code:

Sub Example_2()

Worksheets("Example 2").Columns("D").Select

End Sub

Select property

Step 5: Run the code by pressing the F5 key or by clicking on Play Button.

VBA Columns Example 2-5

Example #3 – VBA Columns Property to Select Range of Cells

Suppose we want to select the range of cells across different columns. We can combine the Range as well as Columns property to do so. Follow the steps below:

Suppose we have our data spread across B1 to D4 in the worksheet as shown below:

VBA Columns Example 3-1

Step 1: Define a new sub-procedure to hold a macro.

Code:

Sub Example_3()

End Sub

VBA Columns Example 3-2

Step 2: Use the Worksheets qualifier to be able to access the worksheet named “Example 3” where we have the data shown in the above screenshot.

Code:

Sub Example_3()

Worksheets("Example 3")

End Sub

Use Worksheets qualifier

Step 3: Use Range property to set the range for this code from B1 to D4. Use the following code Range(“B1:D4”) for the same.

Code:

Sub Example_3()

Worksheets("Example 3").Range("B1:D4")

End Sub

Use Range property

Step 4: Use Columns property to access the second column from the selection. Use code as Columns(2) in order to access the second column from the accessed range.

Code:

Sub Example_3()

Worksheets("Example 3").Range("B1:D4").Columns(2)

End Sub

VBA Columns Example 3-5

Step 5: Now, the most important part. We have accessed the worksheet, range, and column. However, in order to select the accessed content, we need to use Select property in VBA. See the screenshot below for the code layout.

Code:

Sub Example_3()

Worksheets("Example 3").Range("B1:D4").Columns(2).Select

End Sub

Select property in VBA

Step 6: Run this code by hitting F5 or Run button and see the output.

VBA Columns Example 3-7

You can see the code has selected Column C from the excel worksheet though you have put the column value as 2 (which means the second column). The reason for this is, we have chosen the range as B1:D4 in this code. Which consists of three columns B, C, D. At the time of execution column B is considered as first column, C as second and D as the third column instead of their actual positionings. The range function has reduced the scope for this function for B1:D4 only.

Things to Remember

  • We can’t see the IntelliSense list of properties when we are working on VBA Columns.
  • This property is categorized under Worksheet property in VBA.

Recommended Articles

This is a guide to VBA Columns. Here we discuss how to use columns property in Excel by using VBA code along with practical examples and downloadable excel template. You can also go through our other suggested articles –

  1. VBA Insert Column
  2. Grouping Columns in Excel
  3. VBA Delete Column
  4. Switching Columns in Excel

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 автоматически
  • Телефонная книжка в excel
  • Текущий год vba excel