Is there any way to dynamically select an excel column using VBA? - excel

Task: I need to copy a cell value from E12 to the range E23:E25. I achieved this easily using a simple copy and paste statement in the editor. But the range isn't always fixed. I have managed to capture the start point of this range as: Set rangeStart = Range("E12").End(xlDown).Offset(6, 0). I am unable to use this as a starting point for a range selection statement as follows:
Range("E23:E" & Range("A23").End(xlDown).Row).Select
That is how I'm selecting the range to be filled with data in the next step via a paste statement. How do I edit the first half of that range call to something more dynamic? Using rangeStart instead of E23:E.
I have just started working with Excel VBA, so this might be a very basic question to ask. Any help would be appreciated.

First I'd like to address the point that using Select is in most cases highly discouraged. Since you're only looking to paste a value into other cells, you can simply use a line like the following example:
Range("A1:A10").Value = Range("C2:C11").Value
or
Range("A1:A10").Value = 1
This would fill the A1:A10 range with either the values from C2:C11 or the integer 1, respectively. Note the two ranges in the first line are of the same size.
Now, a dynamic approach to your problem could be something along the following example
'Initialise two range variables
Dim SourceRange As Range, TargetRange As Range
'And integers for target rows
Dim fRow As Long, lRow As Long
With ThisWorkbook 'Assuming the code needs to be performed on the Workbook that hosts the macro
'Determine target rows
fRow = 23 'You have not specified how the first row should be determined
lRow = .Cells(fRow, "E").End(xlDown).Row
'Populate range vars
Set SourceRange = .Range("E12")
Set TargetRange = .Range(.Cells(fRow, "E"),.Cells(lRow, "E"))
'Paste values to target range
TargetRange.Value = SourceRange.Value
End With
Note that, since you haven't specified how this should be determined instead, the code above is hard-coded to have a target range in column E that starts at row 23.

If you have
Set rangeStart = Range("E12").End(xlDown).Offset(6, 0)
You can also have
Set rangeEnd = Range(rangeStart, Range("E" & Range("A23").End(xlDown).Row)
which will form a range from the first cell to the second cell.
But read the link posted by Vitaliy.

Related

How do I make a Range of a certain area, that has been filtered out?

So first of all, I wanna write a VBA Code, which allows me to pick a certain range of an Excel sheet, to then copy SOME of the needed values to another worksheet. The issue with this is, that in the Excel sheet of which i take Information from, has some filters applied.
So i found the solution with the method (?) .SpecialCells(xlCellTypeVisible) but the Problem again is, that it works for 1 column, but not for Ranges with more than one column. For Ranges with more than one column, it only picks the first row
Dim rng As Range
Set rng = src.Worksheets("l04").Range(src.Worksheets("l04").Range("Z7:AK7"), src.Worksheets("l04").Range("Z7:AK7").End(xlDown)).SpecialCells(xlCellTypeVisible)
My expected result from this Line of Code should be, that the Range rng is set from Z7 to AK7 all the way down to the maximum number of rows, but only those which are visible.
Edit1: Changed SpecialCell --> SpecialCells
Dim cell As Range
Dim lastRow As Long
With src.Worksheets("104")
lastRow = .Cells(.Rows.Count, "Z").End(xlUp).row
With .Range("Z7:AK" & lastRow)
For Each cell In .Columns(1).SpecialCells(xlCellTypeVisible)
Debug.Print Intersect(.Cells, cell.EntireRow).Address ' change this to what you actually need to grab from each visible cell
Next
End With
End With
Based on some clues in your question, you may find that using the Intersect Method is advantageous.
Dim rng as Range
With src.Worksheets("l04")
'gets all visible cells within the used range on your sheet
set rng = .UsedRange.SpecialCells(xlCellTypeVisible)
'Use the Intersect method to select specific columns
set rng = Intersect(rng, .range("AB:AB, AD:AD"))
End With
Note: This will not select down to last row (i.e. row 1,048,576), only to the last row with data in the specified range.

Paste same value across multiple cell in different sheet

I have to copy paste some data from a sheet to another in excel using VBA.
I have been able to copy-paste the first set of data from sheet A to sheet B without issues.
I am now at the point where I need to copy the same cell value in sheet A into a range in sheet B
What I tried was to define the lastcell in sheet B and the first cell in sheet B in order to define the range where the value in sheet A should be copied.
This is the code for lastrow (which is working fine)
Last_Row2 = Sheets("Records").Range("a1").End(xlDown).Row
code for starting cell
legrng = Sheets("Records").Cells(Rows.count, 4).End(xlUp).Offset(1)
code for pasting the value into the range
Range("LegRng & Last_row2").Copy Destination = "cell value in sheet A"
I am receiving an error here:
Range("LegRng & Last_row2").Copy Destination = "cell value in sheet A"
the error is : Method 'Range of object_global' failed
Could you please tell me what I am doing wrong?
thank you for the help/explanation
You have a couple of errors
First, you try to refer to the range which has name LegRng & Last_row2. Such range doesn't exist in your worksheet, it can't exist because this name is illegal.
If you want to set reference to the range containing more than one cell you do it this way:
Sheets("Records").Range(startCell, endCell)
So first you need to set references to startCell and endCell (I assume you want last cell to be also in column 4):
Set startCell = Sheets("Records").Cells(Rows.count, 4).End(xlUp).Offset(1)
Set endCell = Sheets("Records").Cells(Last_Row2, 4)
You can fill range with value using its property Value
rng.Value = "value"
So, at the end your code should look like that:
With Sheets("Records")
Last_Row2 = .Range("a1").End(xlDown).Row
Set startCell = .Cells(Rows.count, 4).End(xlUp).Offset(1)
Set endCell = .Cells(Last_Row2, 4)
.Range(startCell, endCell).value = "cell value in sheet A"
End With
If not wrapped within an If Statement that tests if startCell.Row is less then Last_Row2, the accepted answer will cause issues if re-run, the code will place the value from sheet A in the next cell each time the macro is re-run.
You should always define and assign your variables.
Using Resize allows you to not need endCell.
Removing Offset from the startCell ensures the correct count for Resize
Sub FillInBlankCellsWithValue()
Dim Last_Row2 As Long, startCell As Range
With Sheets("Records")
Last_Row2 = .Range("a1").End(xlDown).Row
Set startCell = .Cells(Rows.Count, 4).End(xlUp)
'Use the If statement to test that the startCell.Row is less then the Last_Row2
If startCell.Row < Last_Row2 Then
'Offset to the first empty cell and resize by subtracting the startCell.Row
'from Last_Row2, to set the range for the value from SheetA.
startCell.Offset(1).Resize(Last_Row2 - startCell.Row).Value = Sheets("SheetA").Range("A1")
'Change the worksheet and paste value's cell range, as needed
End If
End With
End Sub

Excel VBA: How to clear contents for specified cells when another cell contains specific text or string

I'm having some trouble trying to find VBA code to delete multiple specific cells if a certain cell contains a specific text. This spreadsheet can run close to 100k rows as well, but will vary depending on the data pull.
The specific VBA would be able to do the following:
If Cell J3 equals #N/A, Blank, or 0, then clear contents of cells J3:K3 and P3:X3, and then repeat til it reaches the bottom of column J.
Thanks in advance
How to clear contents for specified cells when another cell contains specific text or string
Dim cellToClear As Range
Dim cellToCheck As Range
Dim specificText As String
If cellToCheck.Value = specificText Then cellToClear.ClearContents
"I'm having some trouble trying to find VBA code "
These links contain VBA code that you can use when you no longer have trouble trying. They contain examples you can paste into your project and modify for your needs.
This link has examples of how to read the contents of a cell.
A range is a group of one or more cells in a worksheet. You can perform an operation on a range and it will affect all the cells inside the range. This link has examples of how to work with a range.
A loop is when the program repeats the same sequence of steps, usually until a specific condition is met. You can find examples of different loops here.
I prefer placing values into an array if you are going to be changing a bunch of cells in a routine. This generally makes the process much quicker.
Start out by setting your worksheet and range objects. Please take note that the below code is currently using index 1 for the worksheet here: Set ws = ThisWorkbook.Worksheets(1). If this is not the worksheet you are personally needing, then you will need to change this.
Then place the cell contents of the entire range into an array. As I mentioned earlier, this process is quicker than making adjustments to individual cells 1 at a time.
Loop the array, checking for either the specific error value #N/A or the other criteria. If this criteria is a match, you will enter another loop that quickly loops through the 'columns' in the row that will delete the values from only the columns you specified.
Once finished, rewrite the array back to the worksheet.
Sub main()
Dim ws As Worksheet, rng As Range, dataArr() As Variant
Set ws = ThisWorkbook.Worksheets(1)
Set rng = ws.Range("J3:X" & ws.Cells(ws.Rows.Count, "J").End(xlUp).Row)
' Place the entire contents of worksheet range into an array
dataArr = rng.Value
Dim i As Long, x As Long, clearRow As Boolean
For i = LBound(dataArr) To UBound(dataArr)
If IsError(dataArr(i, 1)) Then
If dataArr(i, 1) = CVErr(xlErrNA) Then clearRow = True
ElseIf dataArr(i, 1) = vbNullString Or dataArr(i, 1) = 0 Then
clearRow = True
End If
' Loop thru the columns (x) of the current row (i)
If clearRow Then
For x = 1 To 15
Select Case x
Case 1, 2, 7 To 15
dataArr(i, x) = ""
End Select
Next x
clearRow = False
End If
Next i
' Re-write the entire array back to the worksheet in one step
rng.Value = dataArr
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

How to selecting a range with data on excel with vba

How can i modify the code below to select data from any worksheets and copy they to another worksheet for example select and copy data from Worksheets("uno") and paste they to Worksheets("duo"). Because the code below selects data only on activesheet
Set tbl = ActiveCell.CurrentRegion
tbl.Resize(tbl.Rows.Count, tbl.Columns.Count).Select
I have a code to copy data from any sheet to another for example
Worksheets("uno").Range("A5:T5,A7:T56,W5,Y5,W7:W56,Y7:Y56").Copy _
Worksheets("duo").Range("B4")
But i want to copy a range with data and ignore blank cells because the range A5:T5 it doesn't have always all cells with data concretely the last cells of this range, two or three of those, and also the same on range A7:T56.
My problem is how to select a range with data and ignore the blank cells inside the range A7:T56 concretely the last rows and the last columns which haves blank cells
Well, for the first part, where "the code selects data only on the activesheet", you just need to activate the correct sheet (for example: "Worksheets("uno").Activate") before executing "Set tbl = ActiveCell.CurrentRegion".
I am not really sure if I understand you correctly, but these are my thoughts:
If you don't want to activate worksheet "uno" you need to create a reference to that worksheet to have a direct access to it:
Dim wkb As Excel.Workbook
Dim wks As Excel.Worksheet
Set wkb = Excel.Application.Workbooks("<name of your workbook>")
Set wks = wkb.Worksheets("uno")
If you now use the following code:
wks.Range("<your range>").Copy
you have just copied your selected cells, now you can paste it wherever you want.
As for the part with avoiding empty cells:
Generally speaking, you need to create a method of checking whether relevant cells are empty or not before you add them to your range.
Personally, I would avoid trying to copy the whole range as such. Instead I would:
1) loop through all relevant cells in your range one by one
2) for each cell check if it's empty
3) if empty, go to next cell
4) if not empty, copy that cell and paste to the target worksheet
5) jump to next relevant cell
6) when you reach the cell which is just after your last cell, quit looping
I would use the above defined wks object.
Note that a Range object can be treated as a collection of strings, so you can iterate using For... Next loop (For Each loop does not guarantee the index order).
Something like this should do:
Dim rng As Range
Set rng = wks.Range("<your range>")
Dim numOfItems As Integer, itm, i As Integer
numOfItems = rng.Count
For i = 1 To numOfItems
itm = rng.item(i)
If itm <> "" Then
'set value of the corresponding cell in your target worksheet to itm
'<relevant cell>.Value = itm
Else
'do nothing
End If
Next i
I hope it's at least a little bit helpful.

Resources