Copying cell value(s) based on values in adjecent cell - vba

I've got a beautiful Excel file which automatically imports values from CSV files into my worksheet, the data is pasted in the first empty row of my sheet.
The thing is that data can come from 3 different sources, say the column G is filled with either a 1, a 2 or a 3.
Based on the value in said column i'd like to paste the other values of that row to the first empty cell in a specific range in a different sheet. The sheet name is dependent on the Value in Column C, for which I created the following code:
Sub Lastcell()
Dim LR As String
Dim SheetName As String
LR = Cells(Rows.Count, "B").End(xlUp).Row
SheetName = Range("C" & LR).Value
If SheetExists(SheetName) Then
Else
Sheets.Add(After:=Sheets(Sheets.Count)).name = SheetName
End If
End Sub
Function SheetExists(SheetName As String, Optional Wb As Workbook) As Boolean
If Wb Is Nothing Then Set Wb = ThisWorkbook
On Error Resume Next
SheetExists = (LCase(Wb.Sheets(SheetName).name) = LCase(SheetName))
On Error GoTo 0
End Function
So I know which worksheet I’m copying to, now I want to select which row it goes to.
Say, if the value in the last cell of column G is 1, I want to copy the whole row to the first empty cell in row C, starting from C5.
if the value in the last cell of column G is 2, I want to copy the whole row to the first empty cell in row H, starting from H5.
if the value in the last cell of column G is 3, I want to copy the whole row to the first empty cell in row M, starting from M5.
My question is: How can i select a different paste range based on the value of a cell. Cell value is 1, paste to last empty cell in column A Cell value is 2, Paste to last empty cell in column B Cell value is 3, Paste to last empty cell in column C?

Something like this?
Sub tgr()
Dim wb As Workbook
Dim wsData As Worksheet
Dim wsDest As Worksheet
Dim LR As Long, NR as long
Dim DestCol As String
Set wb = ActiveWorkbook
Set wsData = wb.ActiveSheet
LR = wsData.Cells(wsData.Rows.Count, "G").End(xlUp).Row
On Error Resume Next
Set wsDest = wb.Sheets(wsData.Cells(LR, "C").Value)
On Error GoTo 0
If Not wsDest Is Nothing Then
Select Case wsData.Cells(LR, "G").Value
Case 1: DestCol = "C"
Case 2: DestCol = "H"
Case 3: DestCol = "M"
End Select
'Destination sheet and columns are now defined
'Copy over what you want to the destination
NR = wsDest.Cells(wsDest.Rows.Count, DestCol).End(xlUp).Row
If NR < 5 Then NR = 5
wsDest.Cells(NR, DestCol).Resize(, 6).Value = wsData.Cells(LR, "A").Resize(, 6).Value
End If
End Sub

Related

Hiding row based on variable row number in different sheet

I'm trying to write a loop that searches every filled cell in column "J" in sheet2, and hides the corresponding row in sheet1. For example, if cell J1 was "30", row 30 in sheet1 would be hidden. Here's what I have so far:
Sub test()
Dim myrng As Range
Dim ws As Worksheet
Dim i As Integer
Dim lrow As Long, value As Long
Dim cell As Variant
Set ws = Sheet2
lrow = ws.Range("J" & Rows.Count).End(xlUp).Row
For i = 1 To lrow
value = ws.Cells(i, 10).value
cell = "A" & value
Sheet1.[cell].EntireRow.Hidden = True
Next i
End Sub
Everything is working except for the line "Sheet1.[value].entirerow.hidden=true". I'm probably using incorrect syntax. Any thoughts/help would be much appreciated!
Thanks,
Kim

VBA, Advanced filter workbook, populate into common columns across worksheets

I have workbook A with many columns and headers, I would like to separate this data and populate into workbook B based on header name(workbook B has 4 sheets of different pre populated column headers)
1) Workbook A (many columns), filter for all its unique values in col 'AN' (ie. col AN has 20 unique values but ~3000 rows each for each unique set).
2) There is workbook B, with pre populated columns in 4 sheets, not all are the same headers as in workbook A. Here is where the unique values from col AN from workbook A with their respective records will be populated, one after the other.
The goal here is to populate these 4 sheets with data from Workbook A, sorting by each unique column AN value, with its records into the prepopulated workbook B.
This code so far just filters my main 'AN' column uniquely and just gets unique values, I need unique values along with records.
Sub Sort()
Dim wb As Workbook, fileNames As Object, errCheck As Boolean
Dim ws As Worksheet, wks As Worksheet, wksSummary As Worksheet
Dim y As Range, intRow As Long, i As Integer
Dim r As Range, lr As Long, myrg As Range, z As Range
Dim boolWritten As Boolean, lngNextRow As Long
Dim intColNode As Integer, intColScenario As Integer
Dim intColNext As Integer, lngStartRow As Long
Dim lngLastNode As Long, lngLastScen As Long
' Finds column AN , header named 'first name'
intColScenario = 0
On Error Resume Next
intColScenario = WorksheetFunction.Match("First name", .Rows(1), 0)
On Error GoTo 0
If intColScenario > 0 Then
' Only action if there is data in column E
If Application.WorksheetFunction.CountA(.Columns(intColScenario)) > 1 Then
lr = .Cells(.Rows.Count, intColScenario).End(xlUp).Row
' Copy unique values from the formula column to the 'Unique data' sheet, and write sheet & file details
.Range(.Cells(1, intColScenario), .Cells(lr, intColScenario)).AdvancedFilter xlFilterCopy, , r, True
r.Offset(0, -2).Value = ws.Name
r.Offset(0, -3).Value = ws.Parent.Name
' Delete the column header copied to the list
r.Delete Shift:=xlUp
boolWritten = True
End If
End If
'I need to take the rest of the records with this though.
' Reset system settings
With Application
.Calculation = xlCalculationAutomatic
.ScreenUpdating = True
.Visible = True
End With
End Sub
Adding sample pictures
Workbook A sample, I want to unique filter the 'job column' to get all like records together:
Workbook sample B,
Sheet 1 (note there will be multiple sheets).
As you can see workbook A has been sorted by the 'job' column.
you could use the following code:
edited to account for workbook "B" worksheets headers in row 2 (instead of row 1 as per OP example)
Option Explicit
Sub main()
Dim dsRng As Range
Dim sht As Worksheet
Dim AShtColsList As String, BShtColsList As String
Set dsRng = Workbooks("A").Worksheets("ShtA").Range("A1").CurrentRegion '<--| set your entire data set range in workbook "A" worksheet "ShtA" (change "A" and "ShtA" to your actual names)
dsRng.Sort key1:=dsRng.Range("AN1"), order1:=xlAscending, Header:=xlYes '<--| sort data set range on its 40th column (which is "AN", beginning it from column "A")
With Workbooks("B") '<--| refer "B" workbook
For Each sht In .Worksheets '<--| loop through its worksheets
GetCorrespondingColumns dsRng, sht, AShtColsList, BShtColsList '<--| build lists of corresponding columns indexes in both workbooks
CopyColumns dsRng, sht, AShtColsList, BShtColsList '<--| copy listed columns between workbooks
Next sht
End With
End Sub
Sub GetCorrespondingColumns(dsRng As Range, sht As Worksheet, AShtColsList As String, BShtColsList As String)
Dim f As Range, c As Range
Dim iElem As Long
AShtColsList = "" '<--| initialize workbook "A" columns indexes list
BShtColsList = "" '<--| initialize workbook "B" current sheet columns indexes list
For Each c In Sht.Rows(2).SpecialCells(xlCellTypeConstants, xlTextValues) '<--| loop through workbook "B" current sheet headers in row 2 *******
Set f = dsRng.Rows(1).Find(what:=c.value, lookat:=xlWhole, LookIn:=xlValues) '<--| look up data set headers row for workbook "B" current sheet current column header
If Not f Is Nothing Then '<--| if it's been found ...
BShtColsList = BShtColsList & c.Column & "," '<--| ...update workbook "B" current sheet columns list with current header column index
AShtColsList = AShtColsList & f.Column & "," '<--| ...update workbook "A" columns list with corresponding found header column index
End If
Next c
End Sub
Sub CopyColumns(dsRng As Range, sht As Worksheet, AShtColsList As String, BShtColsList As String)
Dim iElem As Long
Dim AShtColsArr As Variant, BShtColsArr As Variant
If AShtColsList <> "" Then '<--| if any workbook "B" current sheet header has been found in workbook "A" data set headers
BShtColsArr = Split(Left(BShtColsList, Len(BShtColsList) - 1), ",") '<--| build an array out of workbook "B" current sheet columns indexes list
AShtColsArr = Split(Left(AShtColsList, Len(AShtColsList) - 1), ",") '<--| build an array out of workbook "A" corresponding columns indexes list
For iElem = 0 To UBound(AShtColsArr) '<--| loop through workbook "A" columns indexes array (you could have used workbook "A" corresponding columns indexes list as well)
Intersect(dsRng, dsRng.Columns(CLng(AShtColsArr(iElem)))).Copy Sht.Cells(2, CLng(BShtColsArr(iElem))) '<--| copy data set current column into workbook "B" current sheet corresponding column starting from row 2 *******
Next iElem
End If
End Sub
and should really need to have each unique name rows set in workbook "B" sheets separated by a blank row, you can write a quite simple SubSeparateRowsSet() and call it right after CopyColumns() call in main()

Select a range with merged calls in first column

I have some code that is working fine, but it is not selecting and pasting the last row of data.
Column AL has a value in every other row e.g. rows 1,3,5 (AL1:AL2,AL3:AL4, AL5:AL6 are merged cells). The other columns are not merged and have values in rows 1-6). When I run the VBA code, row 6 is not being included (all other data is being pasted correctly).
I'm trying to select the cells range and then offset by 1 row (to try and pick up row 6), but that does not seem to be working. I can't find a solution.
Dim lr As Long
Dim drng As Range 'dest range
Dim srng As Range 'source range
Dim ws As Worksheet
For Each ws In ActiveWorkbook.Worksheets
lr = ws.Range("A1").SpecialCells(xlCellTypeLastCell).Row
Set srng = ws.Range("AL1:AP" & lr)
Set drng = SumSh.Range("B" & Rows.Count).End(xlUp)(2)
Set drng = drng.Resize(srng.Rows.Count, srng.Columns.Count)
drng.Value = srng.Value
Next ws
After correcting your example code to ws.Range("AL1:AP" & lr) it ran without incident or missing any rows. The target cells in the first column were not merged but all rows were there.
Sub gettit()
Dim lr As Long
Dim drng As Range 'dest range
Dim srng As Range 'source range
Dim ws As Worksheet, SumSh As Worksheet
Set SumSh = Worksheets("Sum")
For Each ws In ActiveWorkbook.Worksheets
With ws
If .Name = "Sum" Then Exit For
lr = .Range("A1").SpecialCells(xlCellTypeLastCell).Row
Set srng = .Range("AL1:AP" & lr)
Set drng = SumSh.Range("B" & Rows.Count).End(xlUp)(2)
Set drng = drng.Resize(srng.Rows.Count, srng.Columns.Count)
drng.Value = srng.Value
End With
Next ws
End Sub
I did have to set the target worksheet as that had been left undeclared and unassigned.
I suspect your loop is not picking up the next blank row of the target worksheet because the cells in column B are not merged. In other words, it is overwriting the last row with incoming data because you are asking for the next blank cell in column B and column B always has a blank cell starting the last row.
The last iteration of the loop should be correct; albeit with a blank cell in the last row of column B. Solution: move down an extra row on the target.

Need a macro to search and update the record from one worksheet to another

I need a macro code to search the content(it may be numeric or aplhanumeric) from sheet1 in the cell 1 to 1000 and to search the same text from sheet2. and if it founds then i need to update the content corresponding to adjacent cell.
eg:
sheet1
1024 D
505A
6057 C
sheet2
1024 D
6057 C
Assuming the look up values are in column A and the value to copy is in column B.
Sub FindValues()
Dim lookUpSheet As Worksheet, updateSheet As Worksheet
Dim valueToSearch As String
Dim i As Integer, t As Integer
Set lookUpSheet = Worksheets("sheet1")
Set updateSheet = Worksheets("sheet2")
'get the number of the last row with data in sheet1 and in sheet2
lastRowLookup = lookUpSheet.Cells(Rows.Count, "A").End(xlUp).Row
lastRowUpdate = updateSheet.Cells(Rows.Count, "A").End(xlUp).Row
'for every value in column A of sheet2
For i = 1 To lastRowUpdate
valueToSearch = updateSheet.Cells(i, 1)
'look the value in column A of sheet1
For t = 1 To lastRowLookup
'if found a match, copy column B value to sheet1 and proceed to the next value
If lookUpSheet.Cells(t, 1) = valueToSearch Then
updateSheet.Cells(i, 2) = lookUpSheet.Cells(t, 2)
Exit For
End If
Next t
Next i
End Sub

Copy and Paste Largest value in a column from one workbook to another

I am attempting to first, find the the largest value in a column (C), then copy and paste that value into the next empty cell in 'Row 3' in a different (master) workbook. The macro I am running is found in the master workbook. I found this code that i believe will get the pasted cell into the correct spot, but I could use assistance in the code for how to find the largest cell in column C in the data workbook, and then copying and pasting that value.
Private Sub CommandButton1_Click()
Dim wsMaster As Worksheet, wbDATA As Workbook
Dim NextColumn As Long, LastRow As Long
Set wsMaster = ThisWorkbook.Sheets("Contract Metrics")
NextColumn = wsMaster.Range("C", 3).End(xlUp).Column + 1
Set wbDATA = Workbooks.Open("C:\Documents and Settings\Michael Palkovitz\My Documents\Test\Contracts Metrics.xlsx")
wbDATA.Close False
End Sub
Try this. First sort the column you need the value from, then get the last row and place the value into your first empty column in row 3 of your master sheet.
' Create an excel application and open the workbook containing the data
Dim app As Object
Dim wb As Object
Dim ws As Object
Set app = CreateObject("Excel.Application")
Set wb = app.Workbooks.Open("C:\Workbook1")
Set ws = wb.Sheets(1)
' Get last row with a value to use for the sort range
Dim last As Long
Dim value As Long
With ws
last = ws.Cells(ws.Rows.Count, 3).End(xlUp).row
.Range("C1:C" & last).Sort Key1:=.Range("C2"), order1:=xlAscending, Orientation:=xlTopToBottom
value = .Cells(last, 3)
End With
' Get the last filled cell and move over one to get the empty column
Dim col As Long
col = ActiveSheet.Cells(3, 1).End(xlToRight).Offset(0, 1).Column
ActiveSheet.Cells(3, col).value = value
wb.Close False
Set ws = Nothing
Set wb = Nothing
Set app = Nothing