Vba excel как выделить столбец

 

Amberalex

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

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

Всем здравствуйте! Подскажите, как с помощью VBA можно выделить определенные столбцы по их номерам?  
Т.е., например а=2, b=5, как выделить столбцы с а по b, со второго по пятый?

 

Юрий М

Модератор

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

Контакты см. в профиле

Включите макрорекордер и запишите выделение этих столбцов.

 

ran

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

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

 

Amberalex

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

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

Макрорекодер использует буквенные обозначения столбцов  
Columns(«B:F»).Select  
А мне нужно выделение столбцов и использованием числовых переменных, по их номеру.

 

Serge

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

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

{quote}{login=Amberalex}{date=26.09.2011 09:42}{thema=Выделение столбцов по номеру}{post}  
Т.е., например а=2, b=5, как выделить столбцы с а по b, со второго по пятый?{/post}{/quote}Извините, а между столбцами a и b какие идут?  
Я про третий и четвёртый…

 

Amberalex

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

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

RAN, большое спасибо, работает )  
Serge 007, не понял вопроса…

 

Serge

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

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

{quote}{login=Amberalex}{date=26.09.2011 09:52}{thema=}{post}  
Serge 007, не понял вопроса…{/post}{/quote}А что непонятного?  
У меня МЕЖДУ столбцами a и b других нет.  
a — первый, b — второй.  
У Вас не так?

 

Юрий М

Модератор

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

Контакты см. в профиле

Ага, про номера не углядел :-) Но по указанной ссылке всё есть.  
Серж, a и b — переменные :-)

 

Serge

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

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

#9

26.09.2011 21:59:06

{quote}{login=Юрий М}{date=26.09.2011 09:57}{thema=}{post}  
Серж, a и b — переменные :-){/post}{/quote}Тогда понятно…  
А я всё по старинке, в экселе…  
Пора на свалку.

<#0>

AndreA SN

1014 / 118 / 2

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

Сообщений: 1,113

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

1

05.04.2018, 14:29. Показов 15264. Ответов 2

Метки нет (Все метки)


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

Существует способ выделить строки

Visual Basic
1
    Rows("1:1").Select

хотелось бы таким же путем выделять столбцы. Что-то типа

Visual Basic
1
Columns(кол_начальное& ":" &кол_конечное).Select

где кол_начальное и кол_конечное — числа
как это реализовать?



0



Казанский

15136 / 6410 / 1730

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

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

05.04.2018, 14:32

2

Лучший ответ Сообщение было отмечено AndreA SN как решение

Решение

AndreA SN,

Visual Basic
1
2
3
range(columns(1),columns(8)).select
 
columns(1).resize(,8).select



1



1014 / 118 / 2

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

Сообщений: 1,113

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

05.04.2018, 14:33

 [ТС]

3

Спасибо, Алексей.



0




Download Article


Download Article

This wikiHow teaches you how to start using Visual Basic procedures to select data in Microsoft Excel. As long as you’re familiar with basic VB scripting and using more advanced features of Excel, you’ll find the selection process pretty straight-forward.

  1. 1

    Select one cell on the current worksheet. Let’s say you want to select cell E6 with Visual Basic. You can do this with either of the following options:[1]

    ActiveSheet.Cells(6, 5).Select
    

    ActiveSheet.Range("E6").Select
    
  2. 2

    Select one cell on a different worksheet in the same workbook. Let’s say our example cell, E6, is on a sheet called Sheet2. You can use either of the following options to select it:

    Application.Goto ActiveWorkbook.Sheets("Sheet2").Cells(6, 5)
    
    Application.Goto (ActiveWorkbook.Sheets("Sheet2").Range("E6"))
    

    Advertisement

  3. 3

    Select one cell on a worksheet in a different workbook. Let’s say you want to select a cell from Sheet1 in a workbook called BOOK2.XLS. Either of these two options should do the trick:

    Application.Goto Workbooks("BOOK2.XLS").Sheets("Sheet1").Cells(2,1)
    
    Application.Goto Workbooks("BOOK2.XLS").Sheets("Sheet1").Range("A2")
    
  4. 4

    Select a cell relative to another cell. You can use VB to select a cell based on its location relative to the active (or a different) cell. Just be sure the cell exists to avoid errors. Here’s how to use :

    • Select the cell three rows below and four columns to the left of the active cell:

      ActiveCell.Offset(3, -4).Select
      
    • Select the cell five rows below and four columns to the right of cell C7:

      ActiveSheet.Cells(7, 3).Offset(5, 4).Select
      
  5. Advertisement

  1. 1

    Select a range of cells on the active worksheet. If you wanted to select cells C1:D6 on the current sheet, you can enter any of the following three examples:

    ActiveSheet.Range(Cells(1, 3), Cells(6, 4)).Select
    
    ActiveSheet.Range("C1:D6").Select
    
    ActiveSheet.Range("C1", "D6").Select
    
  2. 2

    Select a range from another worksheet in the same workbook. You could use either of these examples to select cells C3:E11 on a sheet called Sheet3:

    Application.Goto ActiveWorkbook.Sheets("Sheet3").Range("C3:E11")
    
    Application.Goto ActiveWorkbook.Sheets("Sheet3").Range("C3", "E11")
    
  3. 3

    Select a range of cells from a worksheet in a different workbook. Both of these examples would select cells E12:F12 on Sheet1 of a workbook called BOOK2.XLS:

    Application.Goto Workbooks("BOOK2.XLS").Sheets("Sheet1").Range("E12:F12")
    
    Application.Goto Workbooks("BOOK2.XLS").Sheets("Sheet1").Range("E12", "F12")
    
  4. 4

    Select a named range. If you’ve assigned a name to a range of cells, you’d use the same syntax as steps 4-6, but you’d replace the range address (e.g., «E12», «F12») with the range’s name (e.g., «Sales»). Here are some examples:

    • On the active sheet:

      ActiveSheet.Range("Sales").Select
      
    • Different sheet of same workbook:

      Application.Goto ActiveWorkbook.Sheets("Sheet3").Range("Sales")
      
    • Different workbook:

      Application.Goto Workbooks("BOOK2.XLS").Sheets("Sheet1").Range("Sales")
      
  5. 5

    Select a range relative to a named range. The syntax varies depending on the named range’s location and whether you want to adjust the size of the new range.

    • If the range you want to select is the same size as one called Test5 but is shifted four rows down and three columns to the right, you’d use:
      ActiveSheet.Range("Test5").Offset(4, 3).Select
      
    • If the range is on Sheet3 of the same workbook, activate that worksheet first, and then select the range like this:
      Sheets("Sheet3").Activate ActiveSheet.Range("Test").Offset(4, 3).Select
      
  6. 6

    Select a range and resize the selection. You can increase the size of a selected range if you need to. If you wanted to select a range called Database’ and then increase its size by 5 rows, you’d use this syntax:

    Range("Database").Select Selection.Resize(Selection.Rows.Count + 5, _Selection.Columns.Count).Select
    
  7. 7

    Select the union of two named ranges. If you have two overlapping named ranges, you can use VB to select the cells in that overlapping area (called the «union»). The limitation is that you can only do this on the active sheet. Let’s say you want to select the union of a range called Great and one called Terrible:

    • Application.Union(Range("Great"), Range("Terrible")).Select
      
    • If you want to select the intersection of two named ranges instead of the overlapping area, just replace Application.Union with Application.Intersect.
  8. Advertisement

  1. 1

    Use this example data for the examples in this method. This chart full of example data, courtesy of Microsoft, will help you visualize how the examples behave:[2]

    A1: Name B1: Sales C1: Quantity
    A2: a B2: $10 C2: 5
    A3: b B3: C3: 10
    A4: c B4: $10 C4: 5
    A5: B5: C5:
    A6: Total B6: $20 C6: 20
  2. 2

    Select the last cell at the bottom of a contiguous column. The following example will select cell A4:

    ActiveSheet.Range("A1").End(xlDown).Select
    
  3. 3

    Select the first blank cell below a column of contiguous cells. The following example will select A5 based on the chart above:

    ActiveSheet.Range("A1").End(xlDown).Offset(1,0).Select
    
  4. 4

    Select a range of continuous cells in a column. Both of the following examples will select the range A1:A4:

    ActiveSheet.Range("A1", ActiveSheet.Range("a1").End(xlDown)).Select
    
    ActiveSheet.Range("A1:" & ActiveSheet.Range("A1"). End(xlDown).Address).Select
    
  5. 5

    Select a whole range of non-contiguous cells in a column. Using the data table at the top of this method, both of the following examples will select A1:A6:

    ActiveSheet.Range("A1",ActiveSheet.Range("A65536").End(xlUp)).Select
    
    ActiveSheet.Range("A1",ActiveSheet.Range("A65536").End(xlUp)).Select
    
  6. Advertisement

Ask a Question

200 characters left

Include your email address to get a message when this question is answered.

Submit

Advertisement

Video

  • The «ActiveSheet» and «ActiveWorkbook» properties can usually be omitted if the active sheet and/or workbook(s) are implied.

Thanks for submitting a tip for review!

Advertisement

About This Article

Article SummaryX

1. Use ActiveSheet.Range(«E6»).Select to select E6 on the active sheet.
2. Use Application.Goto (ActiveWorkbook.Sheets(«Sheet2»).Range(«E6»)) to select E6 on Sheet2.
3. Add Workbooks(«BOOK2.XLS») to the last step to specify that the sheet is in BOOK2.XLS.

Did this summary help you?

Thanks to all authors for creating a page that has been read 167,714 times.

Is this article up to date?

I would like to select multiple columns.

Eg. I want to select column a, b, d, e, g, h

I’ve tried:

Columns("A, B, D, E, G, H").select

I get error message: Type mismatch.

Community's user avatar

asked Jan 17, 2012 at 0:49

HL8's user avatar

2

Range("A:B,D:E,G:H").Select can help

Edit note: I just saw you have used different column sequence, I have updated my answer

answered Jan 17, 2012 at 0:53

HRgiger's user avatar

HRgigerHRgiger

2,72026 silver badges37 bronze badges

2

Some things of top of my head.

Method 1.

Application.Union(Range("a1"), Range("b1"), Range("d1"), Range("e1"), Range("g1"), Range("h1")).EntireColumn.Select

Method 2.

Range("a1,b1,d1,e1,g1,h1").EntireColumn.Select

Method 3.

Application.Union(Columns("a"), Columns("b"), Columns("d"), Columns("e"), Columns("g"), Columns("h")).Select

answered Jan 17, 2012 at 1:03

GSerg's user avatar

GSergGSerg

75.3k17 gold badges160 silver badges340 bronze badges

1

Some of the code looks a bit complex to me. This is very simple code to select only the used rows in two discontiguous columns D and H. It presumes the columns are of unequal length and thus more flexible vs if the columns were of equal length.

As you most likely surmised 4=column D and 8=column H

Dim dlastRow As Long
Dim hlastRow As Long

dlastRow = ActiveSheet.Cells(Rows.Count, 4).End(xlUp).Row
hlastRow = ActiveSheet.Cells(Rows.Count, 8).End(xlUp).Row
Range("D2:D" & dlastRow & ",H2:H" & hlastRow).Select

Hope you find useful — DON’T FORGET THAT COMMA BEFORE THE SECOND COLUMN, AS I DID, OR IT WILL BOMB!!

Jose Ricardo Bustos M.'s user avatar

answered Dec 4, 2016 at 15:33

MORTON WAKELAND JR's user avatar

Working on a project I was stuck for some time on this concept — I ended up with a similar answer to Method 1 by @GSerg that worked great. Essentially I defined two formula ranges (using a few variables) and then used the Union concept. My example is from a larger project that I’m working on but hopefully the portion of code below can help some other people who might not know how to use the Union concept in conjunction with defined ranges and variables. I didn’t include the entire code because at this point it’s fairly long — if anyone wants more insight feel free to let me know.

First I declared all my variables as Public

Then I defined/set each variable

Lastly I set a new variable «SelectRanges» as the Union between the two other FormulaRanges

Public r As Long
Public c As Long
Public d As Long
Public FormulaRange3 As Range
Public FormulaRange4 As Range
Public SelectRanges As Range

With Sheet8




  c = pvt.DataBodyRange.Columns.Count + 1

  d = 3

  r = .Cells(.Rows.Count, 1).End(xlUp).Row

Set FormulaRange3 = .Range(.Cells(d, c + 2), .Cells(r - 1, c + 2))
    FormulaRange3.NumberFormat = "0"
    Set FormulaRange4 = .Range(.Cells(d, c + c + 2), .Cells(r - 1, c + c + 2))
    FormulaRange4.NumberFormat = "0"
    Set SelectRanges = Union(FormulaRange3, FormulaRange4)

answered Jan 7, 2016 at 3:18

Jonh's user avatar

JonhJonh

11113 bronze badges

As a recorded macro.

range("A:A, B:B, D:D, E:E, G:G, H:H").select

answered Mar 8, 2018 at 15:56

gavin's user avatar

gavingavin

3051 gold badge2 silver badges12 bronze badges

With these codes you can select different parts of a table.

Entire Table:
ActiveSheet.ListObjects("Table1").Range.Select

Table Header Row:
ActiveSheet.ListObjects("Table1").HeaderRowRange.Select

Table Data:
ActiveSheet.ListObjects("Table1").DataBodyRange.Select

Third Column:
ActiveSheet.ListObjects("Table1").ListColumns(3).Range.Select

Third Column (Data Only):
ActiveSheet.ListObjects("Table1").ListColumns(3).DataBodyRange.Select

Select Row 4 of Table Data:
ActiveSheet.ListObjects("Table1").ListRows(4).Range.Select

Select 3rd Heading:
ActiveSheet.ListObjects("Table1").HeaderRowRange(3).Select

Select Data point in Row 3, Column 2:
ActiveSheet.ListObjects("Table1").DataBodyRange(3, 2).Select

Subtotals:
ActiveSheet.ListObjects("Table1").TotalsRowRange.Select

For a full guide on tables see The VBA Guide To ListObject Excel Tables.

Like this post? Please share to your friends:
  • Vba excel как вывести форму
  • Vba excel как вывести на панель
  • Vba excel как вывести массивы
  • Vba excel как выбрать ячейку
  • Vba excel как выбрать ячейки