VBA to search value then transfer data from one worksheet - excel

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.

Related

Renaming sheets to value from cell X depending on value on cell Y on the same row

My goal is to create a new worksheet and name it depending on a value in a drop down list and loop it for every "yes" in the list.
The last string is not working and I have no idea how to loop the renaming process to fetch the correct name.
For example: If cell I65 has the value of "AP" I want the newly generated sheet to be named to the value in A65.
Dim rng As Range, cell As Range, was As Worksheet
Set rng = Range("A1:A3")
Sheets("Setup").Select
For Each cell In Range("I48:I85")
If cell = "AP" Then
Sheets("AP").Select
Sheets("AP").Copy Before:=Sheets(1)
Dim AP(2) As Worksheet
Set AP(2) = ActiveWorkbook.Sheets("AP (2)")
AP(2).Name = Worksheets("Setup").Range("A48:A85").Value
End If
Next cell
Though I did not fully understand what you are trying to do, This statement looks suspicious:
AP(2).Name = Worksheets("Setup").Range("A48:A85").Value
you are trying to rename a worksheet with a range of values? -not allowed.
use a single cell like this or concatenate the values in the range before you remane.
AP(2).Name = Worksheets("Setup").Range("A48").Value
Have a look to the following code.
(1) Range("A48:A85").Value returns an array of values which cannot be used as a name. I have used the Offset-function to get the cell in col A of the same row.
(2) No need to use Select. Read (and understand) How to avoid using Select in Excel VBA
(3) Always qualify all worksheets, ranges and so on. With other words: Tell VBA which worksheet from which workbook you are using.
(4) I have used ActiveWorkbook in the With-clause, but I don't like it. Make up your mind on which workbook you are working. If it is the workbook the code lives, use ThisWorkbook instead. It it is another workbook, it's better to assign it to a workbook variable (eg when you open it). Especially in larger project, don't rely on Activeworkbook.
(5) You are declaring your variable AP as array with 2 elements. I guess you just wanted to name the variable similar to the new created sheet, but using an array and writing AP(2) is highly confusing. Just name it AP2 (or newWs or APCopy)
Dim ws As Worksheet, cell As Range
With ActiveWorkbook ' <-- Better change that.
Set ws = .Sheets("Setup")
For Each cell In ws.Range("I48:I85")
If cell = "AP" Then
.Sheets("AP").Copy Before:=.Sheets(1)
Dim AP2 As Worksheet
Set AP2 = .Sheets("AP (2)")
AP2.Name = cell.Offset(0, -8).Value
End If
Next cell
End With

VBA coding - copying a range of cells in 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.

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.

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

Using excel formula to copy a column between workbooks if first cell contains any info

I'm tyring to look for a way to return a range of cells with just the lookup function. Is this really possible?
Basically like this:
=LOOKUP([MasterBook.xlsm]Sheet3!$A:$A,?)
I just want the function to look in the main workbook through all of Column A and return all cells for Column A that have something in them.
EDIT for poster below:
Sure. I have two workbooks; one workbook is essentially a local product that has a "master" sheet on top and then individual worksheets following it that have all of their information extracted from the master sheet. The second workbook is a local copy of a product that I send to a non-local entity higher up the food chain. Basically I need to pull information from the individual sheets in my first workbook and put it in the appropriate columns in the second workbook. I have a macro that gets the info from my sheets in the one workbook over to the other, but the second workbook is formatted differently. I was looking for a way to use a formula if possible.
The macro I am referring to is:
Sub CopyTest()
Dim sourceColumn As Range, targetColumn As Range
Set sourceColumn = Workbooks("Local Workbook.xlsm").Worksheets("Sheet3").Columns("A")
Set targetColumn = Workbooks("Nonlocal Workbook.xlsm").Worksheets("Sheet1").Columns("A")
sourceColumn.Copy Destination:=targetColumn
End Sub
All this does is pull the specified column from one sheet and put it in the column on the second book; but it just pastes it starting in the first block. Since the non-local book is formatted differently, the column I need to transfer to doesn't start until Row 9. shrug I have ideas abuot what I'm trying to do with this, but my ideas tend to exceed my technical ability (which occasionally makes it difficult to explain). :)
Depending on how different your workbooks are formatted. Here is two way to handle this:
Adapt your macro
Instead of copying the whole column, you can copy paste, only the values you want to.
Here is an example:
Sub CopyTest()
Dim rSource As Range, rTarget As Range
Dim lEnd As Long
lEnd = Range("A65536").End(xlUp).Row
Set rSource = Workbooks("Local Workbook.xlsm").Worksheets("Sheet3").Range("A1:A" & lEnd)
Set rTarget = Workbooks("Nonlocal Workbook.xlsm").Worksheets("Sheet1").Range("A9")
rSource.Copy Destination:=rTarget
End Sub
Use a formula
If your data are not in the same order, you'd better use a VLOOKUP formula.
See how it works.
Don't hesitate to post another question with what you've built for some help. Please give as much details as possible so we could help you the best way.
[EDIT] Another try following the comments
Option Explicit
Dim wTarget As Workbook
Sub mainCopy()
Dim bGo As Boolean
bGo = True
'Add a new workbook to copy the data - do you want the user to select one?
Set wTarget = Application.Workbooks.Add()
Do While bGo
CopyTest
bGo = MsgBox("Do you want to import data from another workbook?", vbYesNo, "Continue?")
Loop
End Sub
Sub CopyTest()
Dim rSource As Range, rTarget As Range
Dim lEnd As Long, lCol As Long
Dim ws As Worksheet
Dim vFile As Variant
vFile = Application.GetOpenFilename("Excel-files,*.xls", _
1, "Select One File To Open", , False)
'if the user didn't select a file, exit sub
If TypeName(vFile) = "Boolean" Then Exit Sub
Workbooks.Open vFile
For Each ws In ActiveWorkbook.Worksheets
'do you need to copy the columns separately?
' For lCol = 1 To 10
'find the last cell of the 10th column
lEnd = ws.Cells(65536, 10).End(xlUp).Row
Set rSource = ws.Range("A1:J" & lEnd)
'How can we define the target worksheet?
Set rTarget = wTarget.Worksheets("Sheet1").Range("A9")
rSource.Copy Destination:=rTarget
' Next lCol
Next ws
End Sub

Resources