Excel VBA - select a dynamic cell range - excel

I want to be able to dynamically select a range of cells (the heading row), where the row is 1 but the columns with be for 1 to last column, where "A" is the first Column and where "M" is the last column. I know how to find the last column, but I don't know how to modified the below range to input the first and last column as "A" and "M".
Range("A1:M1").Select

If you want to select a variable range containing all headers cells:
Dim sht as WorkSheet
Set sht = This Workbook.Sheets("Data")
'Range(Cells(1,1),Cells(1,Columns.Count).End(xlToLeft)).Select '<<< NOT ROBUST
sht.Range(sht.Cells(1,1),sht.Cells(1,Columns.Count).End(xlToLeft)).Select
...as long as there's no other content on that row.
EDIT: updated to stress that when using Range(Cells(...), Cells(...)) it's good practice to qualify both Range and Cells with a worksheet reference.

sub selectVar ()
dim x,y as integer
let srange = "A" & x & ":" & "m" & y
range(srange).select
end sub
I think this is the simplest way.

So it depends on how you want to pick the incrementer, but this should work:
Range("A1:" & Cells(1, i).Address).Select
Where i is the variable that represents the column you want to select (1=A, 2=B, etc.). Do you want to do this by column letter instead? We can adjust if so :)
If you want the beginning to be dynamic as well, you can try this:
Sub SelectCols()
Dim Col1 As Integer
Dim Col2 As Integer
Col1 = 2
Col2 = 4
Range(Cells(1, Col1), Cells(1, Col2)).Select
End Sub

I like to used this method the most, it will auto select the first column to the last column being used. However, if the last cell in the first row or the last cell in the first column are empty, this code will not calculate properly. Check the link for other methods to dynamically select cell range.
Sub DynamicRange()
'Best used when first column has value on last row and first row has a value in the last column
Dim sht As Worksheet
Dim LastRow As Long
Dim LastColumn As Long
Dim StartCell As Range
Set sht = Worksheets("Sheet1")
Set StartCell = Range("A1")
'Find Last Row and Column
LastRow = sht.Cells(sht.Rows.Count, StartCell.Column).End(xlUp).Row
LastColumn = sht.Cells(StartCell.Row, sht.Columns.Count).End(xlToLeft).Column
'Select Range
sht.Range(StartCell, sht.Cells(LastRow, LastColumn)).Select
End Sub

Related

Trying to reference and pull all cells that have a blank in another column

I am brand new to VBA as a disclaimer.
I have data I am inputting into one sheet (Emptys) and am trying to grab a cell from another sheet (report) in the same row that has a blank in a certain column.
For example:
Sample Report
I am trying to pull the value from the column A if the cell in the same row of column M is empty and reference that to a different sheet.
I am also trying to skip any rows that have a value in them and only pull the data from the rows that have a blank in column M.
I have tried a few things and I am in a bit over my head.
All that I have gotten to work is this basic formula:
=IF( Report!M2= "",Report!A2, "" )
I still have to sort out empties manually this way.
I feel like I was on the right track here but not sure where I went wrong:
Dim myrange
Dim id
myrange = Sheets("Report").Range("M2:M")
id = Sheets("Empty_Slots").Range("A2:A")
For Each cell In myrange
If IsEmpty(cell) Then
id = Sheets("Report").Range("A2:A")
End If
Next cell
Any help and explanation would be greatly appreciated!
You may access row numbers of those blank cells and use them in worksheet 2:
Sub Macro1()
Dim wk1 As Worksheet
Dim wk2 As Worksheet
Dim LR As Long
Dim rng As Range
Set wk1 = Worksheets("Sheet1")
Set wk2 = Worksheets("Sheet2")
With wk1
LR = .Range("A" & .Rows.Count).End(xlUp).Row 'last non blank cell in column a
For Each rng In .Range("M2:M" & LR).SpecialCells(xlCellTypeBlanks) 'array of blank cells in column M
wk2.Range("A" & rng.Row).Interior.Color = vbYellow 'do something with column A from worksheet2 based on row numbers from column M in worksheet 1
Next rng
End With
Set wk1 = Nothing
Set wk2 = Nothing
End Sub
The code loops trough each blank cell in column M from Sheet1 and pulls the row number. Then in worksheet 2 it uses that row number in column A.
After executing code, I've colored cells in sheet2 but based on sheet1

Working with the Columns function - Excel VBA

I have been looking around the site for a while for an answer to this question but no luck just yet. I have this code where I loop through a row of numbers and depending on what number is in the cell at the time, determines what I copy and paste to the sheet. I am using Columns for this because it is the only way I can make my code dynamic. It works but when I paste I would like to paste in cells lower than where it's pasting right now. I was wondering if Columns had a way of specifying what column and where to paste my data.
Code:
Dim sh As Worksheet
Dim rw As Range
Dim row As Range
Dim cell As Range
Dim RowCount As Integer
Set rw = Range("A5:CG5")
Set sh = ActiveSheet
For Each row In rw.Rows
For Each cell In row.Cells
Select Case cell.Value
Case "2"
ThisWorkbook.Worksheets("Sheet1").Range("E27:E51").Copy Destination:=Sheets("Sheet2").Columns(4)
End Select
Next cell
Next row
Your problem can be solved as Jeeped said, use Destination:=Sheets("Sheet2").Cells(27, 5) or Destination:=Worksheets(2).Range("E27")
Since you want to learn a little bit more, i made an example explanation:
https://msdn.microsoft.com/en-us/vba/excel-vba/articles/range-column-property-excel
On the link it is explained that .Column:
Column A returns 1, column B returns 2, and so on.
And the same is with the .Rows
Use .Cells https://msdn.microsoft.com/pt-br/library/office/ff194567.aspx So you can use the .Cells(Rows,Columns) or .Cells(Index from a Range) or the entire Object:
With Worksheets("Sheet1").Cells.Font
.Name = "Arial"
.Size = 8
End With
So an example if you want to turn your spreadsheet dynamical: to copy from range $E$27 to last row with something written from column $E on Sheet1 To
the last column with nothing written on row 1 on Sheet2.
Sub test()
'Declare variables here
Dim sht1, sht2 As Worksheet
'sht1 has the data and sht2 is the output Worksheet, you can change the names
last_row = Worksheets(1).Range("E65536").End(xlUp).Row
last_column = Worksheets(2).Cells(1, sht1.Columns.Count).End(xlToLeft).Column
'Data add
For i = 27 To last_row
'Start from Row 27
Worksheets(2).Cells(i - 26, last_column + 1) = Worksheets(1).Cells(i, 5)
Next i
MsgBox "Data Updated"
End Sub
And an example of a basic dynamical workbook with i=i+1 and For loops split a single row of data into multiple unique rows into a new sheet to include headers as values and cell contents as values

Find text in one column, if true then match the text in the column next to it with a column on a separate sheet and insert a formula

Here's what I have:
Response Flow
I have one sheet called Response Flow that has Response, Y/N and a Total. If the Response has a Y next to it I want to match the Response Name with the Response Name on Sheet 2 ("Campaigns") and insert a formula in the column next to the response name on Sheet 2 using VBA code. Below is what I have so far.
Sub Volume_Calc()
Dim LastRowR As Long
Dim LastRowC As Long
Dim LastRowI As Long
Dim LastRowA As Long
Dim rngFoundCell As Range
Dim cell As Range
Dim text As String
Dim FindRow As Range
LastRowR = Range("C65536").End(xlUp).Row
LastRowC = Range("K65536").End(xlUp).Row
LastRowI = Range("I65536").End(xlUp).Row
LastRowA = Range("A65536").End(xlUp).Row
Set FindRow = Worksheets("ResponseFlow").Range("C:C").Find(What:="Y",
LookIn:=xlValues)
Do While FindRow = True
If Application.Match(Worksheets("Campaigns").Range("K6"),
Worksheets("ResponseFlow").Range("A4:A" & LastRowA), 0) Then
Worksheets("Campaigns").Range("I6:I" & LastRowI).Formula = "=INDEX(ResponseFlow!$B$3:$B$145,MATCH(Campaigns!$K6,ResponseFlow!$A$3:$A$145,0))"
End If
Loop
End Sub
What you're intending to do seems like it'd be easier to do in Excel without VBA, but if you insist on having some macro insert formulas, this might be an easy approach. First put the dynamic formula you want to be pasting in to the right of the columns with a Y/N, SOMEWHERE in your sheet. In my example below I used Cell("Z1"). Make sure it's dynamic so that if you were to copy/paste formula into another cell, it would adjust correctly.
Again make sure whatever dynamic match formula you want to the right of your values is somewhere and configured to be dynamic. In my example it's on Response ws in cell Z1.
Sub Volume_Calc()
Dim Resp_WS As Worksheet: Set Resp_WS = Worksheets("ResponseFlow")
Dim CAMP_WS As Worksheet: Set CAMP_WS = Worksheets("Campaigns")
Dim rCell As Range
Dim cCell As Range
'Loops through Response Sheeet column "C" looking for values of "Y"
For Each rCell In Intersect(Resp_WS.Range("C:C"), WResp_WS.UsedRange).Cells
If UCase(rCell.Value) = "Y" Then
'When finds a cell with Y, it then loops through Campaigns Sheet column "I"
'looking for a value that matches one column to the left where the "Y" was found
For Each cCell In Intersect(CAMP_WS.UsedRange, CAMP_WS.Range("I:I")).Cells
'When match is found, the macro will insert the formula to the right
'of the cell in Campaigns, with the dynamically updated formula in cell Z1
If cCell.Value = rCell.offset(0,-1).Value Then
cCell.Offset(0, 1).FormulaR1C1 = Resp_WS.Range("Z1").FormulaR1C1
End If
Next cCell
End If
Next rCell
End Sub

select all rows for column except header in a seperate worksheet

I've tried various ways and answers to select all of the rows except the header for a certain column and none seem to work.
I've tried using (15 is the column here):
Range(Cells(2, 15), Cells(.Cells(rows.Count, 15).End(xlUp).Row, 15)).Select
I managed to use .Activate on the worksheet with a different statement to select all, but this changes the sheet and you could visibly see all the rows being selected. This isn't possible for what I need it for. Users can't have a bunch of sheets constantly being switched in front of them, makes for a bad experience.
How can I select all of the non-blank columns after the header (first) row without using .Activate?
I need to get these values, put them in an array, and check if the current cell value is in the array. Not asking for this part, but providing it as context if it matters.
You can not select a range on a non-active worksheet.
Here is how you can set a reference to all the cells in a column except the header row.
Dim TargetRange As Range
With Worksheets("Sheet1")
Set TargetRange = .Range(.Cells(2, 15), .Cells(Rows.Count, 15).End(xlUp))
End With
The following code reads the data from the Worksheet (without using Select or Activate), and puts it in a 2-dimensional array.
Option Explicit
Sub Range_WO_Headers()
Dim Sht_Source As Worksheet
Dim Rng As Range
Dim LastRow As Long
Dim LastCol As Long
Dim Rng_Array As Variant
' modify Sheet1 according to your sheet name
Set Sht_Source = ActiveWorkbook.Worksheets("Sheet1")
' assuming the table's data starts from Cell A1
LastRow = Sht_Source.Cells(Sht_Source.Rows.Count, "A").End(xlUp).Row
LastCol = Sht_Source.Cells(1, Sht_Source.Columns.Count).End(xlToLeft).Column
' resize array according to number of columns and number of rows
ReDim Rng_Array(0 To LastRow, 0 To LastCol)
' set dynamic array from Cell A1 to last row and last column found (starting the second row)
Set Rng = Sht_Source.Range(Cells(2, 1), Cells(LastRow, LastCol))
Rng_Array = Application.Transpose(Rng)
End Sub

copy cells to different worksheet based on worksheet name

I have been looking around and i cant seem to find the same flavor of question that I have
lets say I have a worksheet that has two columns of data one column I apply a filter too and then use that to create worksheets. I want then to paste the values from the second column that to a matching worksheet
So if I had column a had values a b c c d
and column b had values name fluid id state county
I want the code to look at name and paste it to the proper worksheet in this example it would be worksheet a for fluid it would be worksheet b and so on and so forth
i am thinking its a for each formula and then loop it so
Sub C2s()
Dim contr As Control
Dim RN As Range
Dim LR As Integer
LR = Sheet3.Range("A" & Rows.Count).End(xlUp).Row
RN = Sheet3.Range("B1:B" & LR)
For Each Cell In RN
If
End If
Next
End Sub
** Edited to fix column range being allocated
This is untested, but should give you the idea of how to loop and use the offset column to process your values. The SpecialCells(xlCellTypeVisible) means it will only process the filtered records in your selection
Dim MyCell As Range,
Dim MyRange As Range
Dim WorksheetToCopyTo as string
Dim LR As Integer
LR = Sheet3.Range("A" & Rows.Count).End(xlUp).Row
Set MyRange = Sheet3.Range("A1:A" & LR)
For Each MyCell In MyRange.SpecialCells(xlCellTypeVisible)
WorksheetToCopyTo = MyCell.offset(0,1)
Select Case WorksheetToCopyTo
Case "Fluid"
<do something here>
Case "County"
<do something here>
End Select
Next MyCell

Resources