Copy corresponding row VBA - vba

I'm using a VBA to copy all the unique values from one sheet to another sheet. My VBA looks like this:
Sub UniqueListSample()
Application.ScreenUpdating = False
Dim lastrow As Long
Dim i As Long
Dim dictionary As Object
Set dictionary = CreateObject("scripting.dictionary")
Set shee = ThisWorkbook.Sheets("Sheet1")
lastrow = shee.Cells(Rows.Count, "B").End(xlUp).Row
On Error Resume Next
For i = 1 To lastrow
If Len(Sheet1.Cells(i, "B")) <> 0 Then
dictionary.Add shee.Cells(i, "B").Value, 1
End If
Next
Sheet3.Range("A3").Resize(dictionary.Count).Value = _
Application.Transpose(dictionary.keys)
Application.ScreenUpdating = True
End Sub
This takes all the unique values from Sheet 1 column B and moves them to sheet 3 column A. What I'm now trying to add is a function that takes the same rows from column C in sheet 1 and paste them into sheet 3 column B.
Is there an easy way to add this to the existing VBA?

please check this:
Option Explicit
Sub UniqueListSample()
Application.ScreenUpdating = False
Dim lastrow As Long
Dim i As Long
Dim dictionary As Object
Dim shee As Worksheet
Set dictionary = CreateObject("scripting.dictionary")
Set shee = ThisWorkbook.Sheets("Sheet1")
lastrow = shee.Cells(Rows.Count, "B").End(xlUp).Row
On Error Resume Next
For i = 1 To lastrow
If Len(Sheet1.Cells(i, "B")) <> 0 Then
dictionary.Add shee.Cells(i, "B").Value, shee.Cells(i, "c").Value
End If
Next
With Sheet3
.Range("A3").Resize(dictionary.Count).Value = _
Application.Transpose(dictionary.keys)
For i = 1 To dictionary.Count
.Cells(i + 2, 2) = dictionary(Sheet3.Cells(i + 2, 1).Value)
Next
End With
Application.ScreenUpdating = True
End Sub

If you just want one column you can utilise the Item. I prefer to avoid the "On Error" statement - the method below will not error if the same key is used (it will just overwrite).
Sub UniqueListSample()
Application.ScreenUpdating = False
Dim lastrow As Long
Dim i As Long
Dim dictionary As Object
Dim shee As Worksheet
Set dictionary = CreateObject("scripting.dictionary")
Set shee = ThisWorkbook.Sheets("Sheet1")
lastrow = shee.Cells(Rows.Count, "B").End(xlUp).Row
With dictionary
For i = 1 To lastrow
If Len(Sheet1.Cells(i, "B")) <> 0 Then
If Not (.Exists(shee.Cells(i, "B").Value)) Then
.Item(shee.Cells(i, "B").Value) = shee.Cells(i, "C").Value
End If
End If
Next
Sheet3.Range("A3").Resize(.Count).Value = Application.Transpose(.keys)
Sheet3.Range("B3").Resize(.Count).Value = Application.Transpose(.items)
End With
Application.ScreenUpdating = True
End Sub

Related

Assign column to an array VBA

I have this code. DataSet is set as a variant.
DataSet = Selection.Value
Works fine but is there a way I can change it to just column A, specifically cells A2 to A502? Ive tried setting that as the range but it doesn't work. It also needs to ignore blank spaces because not all of the cells will have content. I am trying to eliminate the need to highlight the cells as the entries will only be in that specific range.
Try these 2 versions:
Option Explicit
Public Sub getNonemptyCol_ForLoop()
Dim dataSet As Variant, fullCol As Variant, i As Long, j As Long
Dim lrFull As Long, lrData As Long, colRng As Range
Set colRng = ThisWorkbook.Worksheets(1).Range("A2:A502")
fullCol = colRng
lrFull = UBound(fullCol)
lrData = lrFull - colRng.SpecialCells(xlCellTypeBlanks).Count
ReDim dataSet(1 To lrData, 1 To 1)
j = 1
For i = 1 To lrFull
If Len(fullCol(i, 1)) > 0 Then
dataSet(j, 1) = fullCol(i, 1)
j = j + 1
End If
Next
End Sub
Public Sub getNonemptyCol_CopyPaste() 'without using a For loop
Dim dataSet As Variant, ws As Worksheet
Application.ScreenUpdating = False
Set ws = ThisWorkbook.Worksheets(1)
With ws.UsedRange
ws.Activate
.Range("A2:A502").SpecialCells(xlCellTypeConstants).Copy
.Cells(1, (.Columns.Count + 1)).Activate
ActiveSheet.Paste
dataSet = ws.Columns(.Columns.Count + 1).SpecialCells(xlCellTypeConstants)
'dataSet now contains all non-blank values
ws.Columns(.Columns.Count + 1).EntireColumn.Delete
.Cells(1, 1).Activate
End With
Application.ScreenUpdating = True
End Sub
Assign with dynamic column.
Sub SetActiveColunmInArray()
Dim w As Worksheet
Dim vArray As Variant
Dim uCol As Long
Dim address As String
Set w = Plan1 'or Sheets("Plan1") or Sheets("your plan name")
w.Select
uCol = w.UsedRange.Columns.Count
address = w.Range(Cells(1, 1), Cells(1, uCol)).Cells.address
vArray = Range(address).Value2
End Sub

looping through an entire column of values and if value matches, cut and paste it to another sheet

I have columns A, B, C, D, and E with data.
My goal is to start in cell A1, loop through every single record in column A while looking for a particular value "Grey". If the text in cells is equal to "Grey" then i want to cut and paste then entire row to a newly created sheet, starting in A1. here's what my code looks like ....
Dim n As Long
Dim nLastRow As Long
Dim nFirstRow As Long
Dim lastRow As Integer
ActiveSheet.UsedRange
Set r = ActiveSheet.UsedRange
nLastRow = r.Rows.Count + r.Row - 1
nFirstRow = r.Row
Worksheets("Original").Activate
With Application
.ScreenUpdating = False
Sheets.Add.Name = "NewSheet"
Sheets("Original").Select
Range("A1").Select
Set r = ActiveSheet.UsedRange
nLastRow = r.Rows.Count + r.Row - 1
nFirstRow = r.Row
With ActiveSheet
For n = nLastRow To nFirstRow Step -1
If .Cells(n, "A") = "Grey" Then
.Cells(n, "A").EntireRow.Cut Sheets("NewSheet").Cells(i, "A")
.Cells(n, "A").EntireRow.Delete
n = n + 1
End If
Next
End With
.ScreenUpdating = True
End With
So this macro creates a new sheet - however when it gets to a cell where the value is grey it gives me an error on this line....
.Cells(n, "A").EntireRow.Cut Sheets("NewSheet").Cells(i, "A")
Error says:
Application defined or object defined error.
Anyone have any idea why?
You need to declare i, and set it. As mentioned, the first time it occurs it's looking to paste in row 0, which doesn't exist.
Also, it's best to avoid using .Select/.Activate, and work directly with the data.
How does this work?
Sub t()
Dim r As Range
Dim n As Long, i As Long, nLastRow As Long, nFirstRow As Long
Dim lastRow As Integer
Dim origWS As Worksheet, newWS As Worksheet
Set origWS = Worksheets("Original")
Set newWS = Sheets.Add
newWS.Name = "NewSheet"
Set r = origWS.UsedRange
nLastRow = r.Rows.Count + r.Row - 1
nFirstRow = r.Row
i = 1
With Application
.ScreenUpdating = False
With origWS
For n = nLastRow To nFirstRow Step -1
If .Cells(n, "A") = "Grey" Then
.Cells(n, "A").EntireRow.Copy newWS.Cells(i, "A")
.Cells(n, "A").EntireRow.Delete
i = i + 1
End If
Next
End With
.ScreenUpdating = True
End With
End Sub
You also don't need to do n = n + 1 (unless I missed something).
Edit: Changed .Cut to .Copy, per OP's wish to keep formatting.
Or you may try something like this...
Sub CopyToNewSheet()
Dim sws As Worksheet, dws As Worksheet
Application.ScreenUpdating = False
Set sws = Sheets("Original")
On Error Resume Next
Set dws = Sheets("NewSheet")
dws.Cells.Clear
On Error GoTo 0
If dws Is Nothing Then
Sheets.Add(after:=sws).Name = "NewSheet"
Set dws = ActiveSheet
End If
sws.Rows(1).Insert
On Error Resume Next
With sws.Range("A1").CurrentRegion
.AutoFilter field:=1, Criteria1:="Grey"
.SpecialCells(xlCellTypeVisible).Copy dws.Range("A1")
.SpecialCells(xlCellTypeVisible).EntireRow.Delete
End With
dws.Rows(1).Delete
Application.ScreenUpdating = True
End Sub

Excel VBA - Loop to next available blank cell

I am attempting to write a small section of code to create a new worksheet and insert values from a table in a source worksheet starting at row 2, column 1 thru column 4. Once it reaches the end, I need it to loop to the next row and start over.
The issue I have is that the below code loops back to row 1 of the new worksheet and data is overridden. Is there a simple way to have my loop start on the first blank row down?
[2
Sub SAX()
Dim wsSource As Excel.Worksheet, wsData As Excel.Worksheet
Dim r As Long, c As Long
Set wsData = ThisWorkbook.Sheets.Add(After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count))
wsData.Name = "Data"
Set wsSource = ThisWorkbook.Worksheets("Header")
Application.DisplayAlerts = False
r = 2
Do Until Len(Trim(wsSource.Cells(r, 1).Value)) = 0
For c = 1 To 4
wsData.Cells(c * 1, 1).Value = wsSource.Cells(r, c).Value
Next c
ThisWorkbook.Activate
r = r + 1
Loop
Application.DisplayAlerts = True
End Sub
What you want is this, assuming (from screenshot) that you're working with a structured ListObject table:
Sub SAX()
Dim wsSource As Excel.Worksheet, wsData As Excel.Worksheet
Dim i as Long
Dim tbl As ListObject
Dim vals As Variant
With ThisWorkbook
Set wsData = Sheets.Add(After:=.Sheets(.Sheets.Count))
Set wsSource = .Worksheets("Header")
End With
wsData.Name = "Data"
'## Get a handle on the Table object
Set tbl = wsSource.ListObjects(1) 'Modify if needed
Application.DisplayAlerts = False
i = 1 'which row we start putting data on wsData
'## Iterate each row of data in the Table
For Each rng In tbl.DataBodyRange.Rows
'## Dump this row's values in to an array, and transpose it
vals = Application.Transpose(rng.Value)
'## Put the array's values in an appropriately sized range on the wsData sheet:
wsData.Cells(i, 1).Resize(UBound(vals)).Value = vals
'## Increment the destination row number:
i = i + UBound(vals)
Next
Application.DisplayAlerts = True
End Sub
Here we transpose the rng.Value so that we can drop it in a column. We store this in the vals array. We then use the vals array to determine the size of the range where the values will be placed on "Data" sheet, and also use the size of the vals array to increment our i variable, which tells us where to put the next row's data.
Or, maybe even more simply:
For i = 1 to tbl.DataBodyRange.Cells.Count
wsData.Cells(i, 1).Value = tbl.DataBodyRange.Cells(i).Value
Next
This works because a range is indexed by row/column, so we begin counting cell #1 at the top/left, and then wrap to the second row and resume counting, for example, the "cell index" is in this example table:
This can easily be put into a single row or column, just by iterating over the Cells.Count!
Try this...you actually need two Row values, one for data, one for output:
Sub SAX()
Dim wsSource As Worksheet, wsData As Worksheet
Dim lDataRow As Long, lCol As Long, lOut as Long
Set wsData = ThisWorkbook.Sheets.Add(After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count))
wsData.Name = "Data"
Set wsSource = ThisWorkbook.Worksheets("Header")
Application.DisplayAlerts = False
lDataRow = 2
lOut = 1
Do
For lCol = 1 To 4
wsData.Cells(lOut, 1) = wsSource.Cells(lDataRow, lCol)
Next lCol
lDataRow = lDataRow + 1
lOut = lOut + 1
Loop Until Len(Trim(wsSource.Cells(lDataRow, 1))) = 0
Application.DisplayAlerts = True
End Sub
It would be more efficient to create an array and write all the data at one time.
Sub SAX()
Dim Data, v
Dim x As Long, y As Long
With ThisWorkbook.Worksheets("Header")
With .Range("A1", .Range("A" & .Rows.Count).End(xlUp))
x = WorksheetFunction.RoundUp(.Cells.Count / 4, 0)
ReDim Data(1 To x, 1 To 4)
x = 1
For Each v In .Cells
If y = 4 Then
x = x + 1
y = 1
Else
y = y + 1
End If
Data(x, y) = v
Next
End With
End With
With ThisWorkbook.Sheets.Add(After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count))
.Name = "Data"
.Range("A1:D1") = Array(1, 2, 3, 4)
.Range("A2:D2").Resize(UBound(Data, 1)).Value = Data
End With
End Sub

Read cell for cell and create sheets

How can I read in Visual Basic from column B, sheet "control" in Excel cell for cell till an empty cell?
After that I would like to generate for every cell a new sheet with the name from cells. In this:
:
you see the content of this column, which could be different from time to time. After reading it I want to generate empty sheets with names: RW_BONDS, ... .
You can do something like this.
Private Sub CommandButton1_Click()
Dim ws As Excel.Worksheet
Dim lRow As Long
Dim lastRow As Long
'Set the sheet to read from
Set ws = Application.Sheets("control")
'Set the row to start reading at
lRow = 3
lastRow = wsOwners.Cells(wsOwners.Rows.Count, "B").End(xlUp).Row
'Loop through the rows
Do While lRow <= lastRow
If ws.Range("B" & lRow).Value <> "" then
'Add a new sheet
ActiveWorkbook.Sheets.Add Before:=Worksheets(Worksheets.Count)
'Change the name to the value of column B in the current row
ActiveWorkbook.ActiveSheet.Name = ws.Range("B" & lRow).Value
End If
'Increment your row to the next one
lRow = lRow + 1
Loop
End Sub
Sub test()
Dim i As Long
i = 1
While Len(Sheets("Control").Cells(i, 2))
Worksheets.Add.Name = Sheets("Control").Cells(i, 2): i = i + 1
Wend
End Sub
EDIT answer for the comment:
Sub test()
Dim i As Long
i = 1
With Sheets("Control")
On Error Resume Next
Application.DisplayAlerts = False
While Len(.Cells(i, 2))
If Len(Sheets(.Cells(i, 2).Value).Name) = 0 Then Else Sheets(.Cells(i, 2).Value).Delete
Worksheets.Add.Name = .Cells(i, 2): i = i + 1
Wend
Application.DisplayAlerts = True
On Error GoTo 0
End With
End Sub
set ws = worksheets("Source")
row = 1
col = "B"
Do
row = row + 1
if ws.range(col & row).text = "" then exit do
worksheets.add.name = ws.range(col & row).text
Loop
End Sub
Sub createSheets()
With Worksheets("control")
iRow = 1 'Start on the first row
While Len(.Cells(iRow, 2)) > 0 'While there isn't a blank cell
Worksheets.Add.Name = .Cells(iRow,2) 'Create/rename sheet
iRow = iRow + 1
Wend
End With
End Sub

Loop through each column and delete columns with "0"

I'm not getting any errors but it's not deleting the columns with "0's". I just want to delete columns that have lots of 0's as you can read from my code. I'm not sure what could be wrong so any suggestions are welcome.
Sub Finalize()
Dim finalform As Worksheet
Dim deletename As String
Dim finalworkbook As Workbook
Dim ws As Worksheet
Dim copyrange As Range
Dim columnloop As Range
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Set finalform = Workbooks(ActiveWorkbook.Name).ActiveSheet
For a = 3 To 18
If Range("B" & a).Value <> "" Then
Workbooks.Open finalform.Range("B" & a).Value
Set finalworkbook = Workbooks(ActiveWorkbook.Name)
'Delete sheets
For b = 3 To 12
deletename = finalform.Range("D" & b).Value
If deletename <> "" Then
finalworkbook.Worksheets(deletename).Delete
End If
Next b
'Find, replace, remove
For Each ws In ActiveWorkbook.Worksheets
'Copy paste values
Set copyrange = ws.Cells
copyrange.Copy
copyrange.PasteSpecial xlPasteValues
Application.CutCopyMode = False
'Delete columns with 0
For Each columnloop In copyrange.Columns
d = 0
For c = 1 To 35
If Cells(c, columnloop.Column).Value = "0" Then
d = d + 1
End If
Next c
If d > 5 Then
columnloop.Delete
End If
Next columnloop
Next ws
End If
Next a
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
Your loop can be replaced with more efficient methods of counting. You should always start at the extents when deleting rows or columns and work toward A1 in order that you do not skip over a column during the next incrementation.
Dim c As Long, ws As Worksheet
'Find, replace, remove
For Each ws In ActiveWorkbook.Worksheets
With ws
.UsedRange.Cells = .UsedRange.Cells.Value
'Delete columns with 0
For c = .UsedRange.Columns.Count To 1 Step -1
If Application.CountIf(.Columns(c), 0) > 5 Then
.Columns(c).EntireColumn.Delete
End If
Next c
End With
Next ws
There are several other areas that could be tweaked. Once this is running to an operational standard, consider posting it on Code Review (Excel) for further improvements.