VBA coding - copying a range of cells in Excel - excel

Apologies if this is a simple thing to do, but I'm re-learning VBA after years of non-use. I have a worksheet where I need to find a specific cell within that workbook based on the text within that cell. I then need to copy the whole row that contains this cell, and the three rows below, making a range of four entire rows. Any help would be appreciated.

You have not indicated where you wish to paste the material, but:
Sub qwerty()
Dim s As String, sh As Worksheet, r As Range
s = "happiness"
For Each sh In Sheets
Set r = Cells.Find(What:=s)
If Not r Is Nothing Then
r.Resize(4, 1).EntireRow.Copy
End If
Next sh
End Sub
Here we are searching for happiness.

Related

Excel VBA - how to select column AND row of active cell?

I have been struggling with VBA code that selects entire row and column of active cell. I tried many codes, but all of them failed. I don't want to make any changes to range, I need to just select it.
How selection after macro should look like:
Selected column and row
Last version of code I came up with, still not working. Any ideas how to achieve it or fix it?
Private Sub CommandButton7_Click()
Dim Column As range
Set Column = ActiveCell.EntireColumn
Dim Row As range
Set Row = ActiveCell.EntireRow
Dim rng As range
With ActiveSheet
Set rng = Union(.range(Column), .range(Row))
End With
rng.Select
Unload Me
End Sub
You were close, but this can done simply with:
With ActiveCell
Union(.EntireRow, .EntireColumn).Select
End With
Or just a one-liner:
Union(ActiveCell.EntireRow, ActiveCell.EntireColumn).Select

Excel List of Blank Cells

So I have a big excel sheet with a bunch of empty cells in various locations. I want an easy to work with list of which cells are empty. I was hoping to make a new worksheet that was populated with the locations of the empty cells. I wanted to have this to just populate the cells I want it to. I kept the header from the worksheet I will be checking and added a blank cells count, so I want the following cells in the column to be populated by the list of empty cell locations.
Now I know I can use =ISBLANK to test if a cell is empty or not, but I only care about the cells that return TRUE. So I figure I'll need a loop. And I want the location of the cell so I can use =CELL. And to make this most readable I want to do this on a column by column basis.
But I want to populate a spreadsheet with this information in a manner similar to how functions work (I just want to copy and paste it to other cells and columns). But it's pretty clear that I am going to need VBA.
My question is how can I create a macro to populate my spreadsheet with a list of empty cells? How do I apply it to the cells?
I assume you have data in sheet1, I have used sample range// Range("A1:c15") however you can define range as per need and blank cells address will be published in next sheet.
Sub FindBlank()
Dim rng As Range
dim i as long
For Each rng In Sheet1.Range("A1:c15").SpecialCells(xlCellTypeBlanks)
i = i + 1
Sheet2.Cells(i, 1) = rng.Address
Next
End Sub
If you want a list of the cells that are empty, you can use Range().SpecialCells(xlCellTypeBlank):
Sub getEmptyCellAddresses()
Dim rng As Range
Dim ws as Worksheet
Set ws = Sheets("Sheet1") ' CHANGE AS NECESSARY
Set rng = ws.Range("A1:A15").SpecialCells(xlCellTypeBlanks) ' Edit/change range as necessary
ws.Cells(1, 2).Value = rng.Cells.Address ' Change `ws.cells(1, 2)` to whatever destination you like
End Sub
Edit: Ah, beaten by 16 seconds by #RamAnuragi ...but anyways, they're slightly different ways to tackle the question so I'll leave it.
Edit: For funsies, here's another way to put them all in a column, one row per cell...and more, per your comments.
Sub listEmptyCells()
Dim emptyAddresses() As String
Dim i As Long
Dim ws As Worksheet
Dim rng As Range
Set ws = Sheets("Sheet1") ' CHANGE AS NECESSARY
Set rng = ws.Range("A1:A15")
If WorksheetFunction.CountBlank(rng) = 0 Then
MsgBox ("No empty cells in the range")
Exit Sub
End If
emptyAddresses() = Split(rng.SpecialCells(xlCellTypeBlanks).Address, ",")
For i = LBound(emptyAddresses) To UBound(emptyAddresses)
ws.Cells(i + 1, 2).Value = emptyAddresses(i)
Next i
End Sub

VBA to search value then transfer data from one worksheet

a little stuck on this VBA. Havent done VBA in a while so might need to cut me some slack :)
Introduction
Working on a Doc that manages the skills and competencies of several employees in my organisation. All worksheets (with the exception of home have identical layout and cell organisation)
Problem Statement
I need a VBA that searches one particular cell (B2) for a factory location (i.e. York) if this cell = York, I then need it to copy and paste a list of values (i.e. B2) into a range of cells on another worksheet in the same workbook named "York". I then need this to loop through all worksheets in the doc (kinda like looping through all employees; each employee will have a new worksheet) for the cell value York and copy and paste those cells into the next empty row on the worksheet York. I cannot seem to get the loop to run through, but after writing the code I couldnt even get the copy paste function to work.
Anyone up for the challenge.
This is my current code. Very poor I know.
Sub testv2()
Dim ws As Worksheet
Dim sh As Worksheet
Dim rng As Range
Dim c As Range
Set ws = Sheets("MATRIX - MASTER")
"Matrix-master was template copy for all skills"
Set rng = ws.Range("$B$2")
For Each sh In Sheets
For Each c In rng.Cells
If rng.Value = "York" Then
ActiveWorkbook.Range("B1").Copy
Sheets("York").Select
ActiveWorkbook.Range("J6").Paste
End If
Next c
Next sh
End Sub
Any help at all would be appreciated!
I don't understand what you are tring to do.
rng is set to one cell of one sheet "$B$2" on "MATRIX - MASTER"
why do you loop it with for each?
I think you ment to write instead of: ActiveWorkbook.Range("J6").Paste
ActiveSheet.Range("B1").Copy ' source
ActiveWorkbook.Sheets("York").Range("J6").Paste ' target
range on the workbook level is used by mamed range.
Try to avoid Select... If you must, use Activate.

Excel VBA Copy / Paste macro: Ignore cells with Formulas

I have created a tool in excel which can take two spreadsheets, and copy the content from one to another when we do an update on the sheet itself.
The tool is purely designed to be a copy / paste tool, the current code will copy and paste values from sheet to sheet.
I have to include logic into the tool to skip cells with formulas, if the tool copies and pastes the formulas which are currently in the source sheet to the target sheet, they no longer match and throw #REF errors. Any suggestions on how to put a for loop in here or something similar to allow it to check and ignore cells with formulas? I need it only to copy / paste cells with numbers or values.
Sub CopyWorkbook()
Dim wb1 As Workbook, wb2 As Workbook
wb1.Sheets("Capex").Range("H1124:AT1173").Copy
wb2.Sheets("Capex").Range("H529:AT578").PasteSpecial Paste:=xlPasteAll
wb1.Sheets("Capex").Range("H1275:AT1284").Copy
wb2.Sheets("Capex").Range("H580:AT589").PasteSpecial Paste:=xlPasteAll
Rather than loop cell by cell you can use SpecialCells to identify the formulae
There are two options
Copy only the Constant cells to the destination
Remove any Formula cells from the destination
If your formulae occur in a single contigious block then (1) works easily, else this will result in a number of areas needing to copied over. So (2) is preferable
Your first range can be covered as so.
Dim rng1 As Range
Set rng1 = Range("H1124:AT1173")
rng1.Copy [h1275]
On Error Resume Next
[h1275].Resize(rng1.Rows.Count, rng1.Columns.Count).SpecialCells(xlFormulas) = vbNullString
On Error GoTo 0
If you really want to skip cells containing formulas, you could use this example as a start.
The code assumes that only formulas start with an equals sign.
Edit: expanding the example with the ranges in the question.
Sub example()
Dim source As Range
Dim target As Range
Set source = ActiveSheet.Range("A1:B6")
Set target = ActiveSheet.Range("D1:E6")
copy_non_formulas source:=source, target:=target
'Extended example using the ranges posted in the question
'For the sake of formatting, I omitted the fully qualified
'range names.
copy_non_formulas source:=Range("H1124:AT1173"), target:=Range("H529:AT578")
copy_non_formulas source:=Range("H1275:AT1284"), target:=Range("H580:AT589")
End Sub
Public Sub copy_non_formulas(source As Range, target As Range)
'Assumes that all formulas start with '=' and all non formulas do not
Dim i As Long
Dim j As Long
Dim c As Range
For i = 1 To source.Rows.Count
For j = 1 To source.Columns.Count
Set c = source(RowIndex:=i, ColumnIndex:=j)
If Left(c.Formula, 1) <> "=" Then
target(RowIndex:=i, ColumnIndex:=j).Value = c.Value
End If
Next j
Next i
End Sub
Can't you just use Paste:=xlPasteValues for all cells? That way no formulas get copied to the target sheet.

Macro to copy a Named Range from one Worksheet to another

I have several Named Ranges that contain constant data in one worksheet.
I have a target range where one of the Named Ranges will be copied to, on another worksheet.
The Named Range that will be copied is selected based on user input into other cells.
I have managed to create the name of the relevant Named Range in a single cell.
What I can't do (as I'm a VBA Noob who thought he could do all this without using VBA!), is create a Macro that reads the relevant cell, and then copies whatever Name Range it reads, into the target range.
Any assistance most humbly and gratefully accepted.
Let's say, the name of your range is MyRange
So to copy the range you have to do this
Range("MyRange").Copy
Now let's assume that Cell A1 of Sheet1 has the word MyRange. In such a scenario, you can retrieve the value of the cell A1 using Range("A1").Value
So
Range("MyRange").Copy
becomes
Range(Range("A1").Value).Copy
Here is a complete example. I am assuming that you want to copy to say Cell A1 of Sheet2
Sub Sample()
Dim wsI As Worksheet, wsO As Worksheet
Set wsI = ThisWorkbook.Sheets("Sheet1")
Set wsO = ThisWorkbook.Sheets("Sheet2")
wsI.Range(wsI.Range("A1").Value).Copy wsO.Range("A1")
End Sub
i am not sure if thats what you need, but, if you need just to copy the content of the A1 cell from sheet1 to sheet2 for example, just do this:
Plan2.Cells(1, 1).Value = Plan1.Cells(1, 1).Value
you may wnat to encapsulate the code into a sub as well:
Sub copyvalues()
Plan2.Cells(1, 1).Value = Plan1.Cells(1, 1).Value
End Sub
...and finally, you must to insert a button, using onclick() event to fire the sub(which you must to allocate into a module)
sorry my bad english, hope it helps you.
Public Function copyNamevalues(srcName As Name, destName As Name)
srcName.RefersToRange.Cells.Copy (destName.RefersToRange.Cells)
End Function

Resources