Excel VBA Copy and pasting cells with certain values in a range from one worksheet to another - excel

I am trying to loop through a range of cells and copy and paste the values of the ones that are not blank or do not contain an "X" (as well as the cell two to the right of it) to columns on another worksheet. I am hoping that the cells I paste them to will retain the pre-formatted conditional formatting set up prior to having stuff pasted to them. What I have so far is not working, and does not account for the cell two adjacent to the copy cell or just pasting the value without formatting. It would be great if then I could sort the first of the pairs of cells by alphabetically (also not accounted for). Thanks for any help!
Sub Wire_List_Export()
Application.ScreenUpdating = False
Dim copySheet As Worksheet
Dim pasteSheet As Worksheet
Dim c As Range
Dim j As Integer
Set copySheet = Worksheets("LV Schedule")
Set pasteSheet = Worksheets("test")
For Each c In copySheet.Range("G274:G10000")
If Not c = "X" Or Not IsEmpty(c) Then
copySheet.Cells(c).Copy pasteSheet.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0)
End If
Next c
End Sub

Is this what you are looking for?
Sub Wire_List_Export()
'Declarations.
Dim RngCopyRange As Range
Dim IntOffsetCopy As Integer
Dim RngPasteRange As Range
Dim RngCell As Range
'Turning off screen updating.
Application.ScreenUpdating = False
'Setting variables.
Set RngCopyRange = Worksheets("LV Schedule").Range("G274:H10000")
Set RngPasteRange = Worksheets("test").Range("A1:B9727")
'Copying the range.
RngCopyRange.Copy
'Pasting the range (only values, skipping blank cells).
RngPasteRange.PasteSpecial Paste:=xlPasteValues, _
Operation:=xlNone, _
SkipBlanks:=True, _
Transpose:=False
'Turning off cut-copy mode.
Application.CutCopyMode = False
'Turning on screen updating.
Application.ScreenUpdating = True
End Sub

Related

How to copy cells of specific colour of a worksheet and paste them in another workbook

I am very new to VBA and I was wondering how to copy only the white cells of a worksheet and paste them to the same places but to another workbook.
Specifically, I have two workbooks with multiple sheets and they are the same, but the source workbook has some white cells filled and the destination workbook has these cells empty. I want to transfer the values from the source white cells to the destination white cells.
Also if it is possible, I want to fill the empty white cells with "0".
I have found some pieces of code to copy all coloured cells to another excel worksheet but they do not transfer to another workbook and the exact places.
Sub CopyHighlightedTransactions()
Dim TransIDField As Range
Dim TransIDCell As Range
Dim ATransWS As Worksheet
Dim HTransWS As Worksheet
Set ATransWS = Worksheets("All Transactions")
Set TransIDField = ATransWS.Range("A2", ATransWS.Range("A2").End(xlDown))
Set HTransWS = Worksheets("Highlighted Transactions")
For Each TransIDCell In TransIDField
If TransIDCell.Interior.Color = RGB(255, 0, 0) Then
TransIDCell.Resize(1, 10).Copy Destination:= _
HTransWS.Range("A1").Offset(HTransWS.Rows.Count - 1, 0).End(xlUp).Offset(1, 0)
End If
Next TransIDCell
HTransWS.Columns.AutoFit
End Sub
Thank you in advance.
If the animation above is something that you mean (if I understand you correctly), maybe you want to try the sub below :
Sub test()
Dim wbS As Worksheet: Dim wbT As Worksheet
Dim rgData As Range: Dim c As Range
Application.ScreenUpdating = False
'prepare variable for the workbook and sheet of the source and target
Set wbS = Workbooks("Source.xlsm").Sheets("Sheet1") 'change as needed
Set wbT = Workbooks("Target.xlsx").Sheets("Sheet1") 'change as needed
'the range of the data to be searched
Set rgData = wbS.Range("A1:D10") 'change as needed
'prepare the color to be searched
With Application.FindFormat
.Clear
.Interior.Color = vbWhite
End With
'start searching as c variable
Set c = rgData.Find(What:=vbNullString, SearchFormat:=True)
'loop until all cells in rgData is checked if the color is white or not
'if found white then copy the c, paste to wbT with that c address
If Not c Is Nothing Then
FirstAddress = c.Address
Do
c.Copy Destination:=wbT.Range(c.Address)
Set c = rgData.Find(What:=vbNullString, after:=c, SearchFormat:=True)
Loop While c.Address <> FirstAddress
End If
End Sub
To test the code, make a copy of your workbook (both the source and the target). Copy the sub, paste on the copied workbook then run it. Both workbooks must be opened. It will take time if your data range is big as the code will check all the cell which has white color within the rgData.
the source workbook has some white cells filled
Please remember, the code is looking for the cell which is filled with white color.
I'm curious if the test2 sub below is faster because there's no loop.
Sub test2()
Dim rgW_orig As Range: Dim rgDest As Range
Dim rgW As Range: Dim rgX As Range
Dim rgBlank As range
Application.ScreenUpdating = False
Set rgW_orig = Sheets(1).Range("A1:D10")
Set rgDest = Workbooks("Target.xlsx").Sheets(1).Range(rgW_orig.Address)
With Application.FindFormat.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorDark1
.TintAndShade = 0
.PatternTintAndShade = 0
End With
Workbooks.Add
Set rgW = ActiveSheet.Range(rgW_orig.Address)
rgW_orig.Copy Destination:=rgW
With rgW
.Replace What:="", Replacement:=True, LookAt:=xlPart, SearchOrder _
:=xlByRows, MatchCase:=False, SearchFormat:=True, ReplaceFormat:=False
Set rgX = .SpecialCells(xlConstants, xlLogical)
End With
rgW.Value = "": rgX.Value = 1
set rgBlank = rgW.SpecialCells(xlBlanks)
rgW.Value = rgW_orig.Value
rgBlank.ClearContents
rgW.Copy
rgDest.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:= _
True, Transpose:=False
Application.CutCopyMode = False
ActiveWorkbook.Close False
End Sub
The test2 macro use a new workbook as a helper, and assumes that the range of data in the Source.xlsm (where the macro reside) is the same within the range of data in the Target.xlsx.
First, it set a range the same address with rgW_orig in the new workbook as rgW variable. Then it copy the rgW_orig and paste it to rgW
Then within the new workbook (the helper workbook) :
it get all cells which filled with white color (by replacing the cell with white color with TRUE boolean), set it as rgX variable.
Next, it fill the whole range (the rgW) with blank, and fill the rgX with 1, then get all cells which has no value (blank) as rgBlank variable.
It copy again the rgW_orig into rgW, then clear the content of rgBlank. Now in this helper workbook within the rgW, the cells with value are only the one with white color, the rest are blank.
Finally it copy the rgW, paste "skip blank" into rgDest then close the helper workbook without saving.
Still not so sure though if this test2 sub is faster than the sub before.

Copy and paste values only after filtering data in vba [duplicate]

I have two sheets. One has the complete data and the other is based on the filter applied on the first sheet.
Name of the data sheet : Data
Name of the filtered Sheet : Hoky
I am just taking a small portion of data for simplicity. MY objective is to copy the data from Data Sheet, based on the filter. I have a macro which somehow works but its hard-coded and is a recorded macro.
My problems are:
The number of rows is different everytime. (manual effort)
Columns are not in order.
Sub TESTTHIS()
'
' TESTTHIS Macro
'
'FILTER
Range("F2").Select
Selection.AutoFilter
ActiveSheet.Range("$B$2:$F$12").AutoFilter Field:=5, Criteria1:="hockey"
'Data Selection and Copy
Range("C3").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Sheets("Hockey").Select
Range("E3").Select
ActiveSheet.Paste
Sheets("Data").Select
Range("D3").Select
Range(Selection, Selection.End(xlDown)).Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Hockey").Select
Range("D3").Select
ActiveSheet.Paste
Sheets("Data").Select
Range("E3").Select
Range(Selection, Selection.End(xlDown)).Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Hockey").Select
Range("C3").Select
ActiveSheet.Paste
End Sub
Best way of doing it
Below code is to copy the visible data in DBExtract sheet, and paste it into duplicateRecords sheet, with only filtered values. Range selected by me is the maximum range that can be occupied by my data. You can change it as per your need.
Sub selectVisibleRange()
Dim DbExtract, DuplicateRecords As Worksheet
Set DbExtract = ThisWorkbook.Sheets("Export Worksheet")
Set DuplicateRecords = ThisWorkbook.Sheets("DuplicateRecords")
DbExtract.Range("A1:BF9999").SpecialCells(xlCellTypeVisible).Copy
DuplicateRecords.Cells(1, 1).PasteSpecial
End Sub
I suggest you do it a different way.
In the following code I set as a Range the column with the sports name F and loop through each cell of it, check if it is "hockey" and if yes I insert the values in the other sheet one by one, by using Offset.
I do not think it is very complicated and even if you are just learning VBA, you should probably be able to understand every step. Please let me know if you need some clarification
Sub TestThat()
'Declare the variables
Dim DataSh As Worksheet
Dim HokySh As Worksheet
Dim SportsRange As Range
Dim rCell As Range
Dim i As Long
'Set the variables
Set DataSh = ThisWorkbook.Sheets("Data")
Set HokySh = ThisWorkbook.Sheets("Hoky")
Set SportsRange = DataSh.Range(DataSh.Cells(3, 6), DataSh.Cells(Rows.Count, 6).End(xlUp))
'I went from the cell row3/column6 (or F3) and go down until the last non empty cell
i = 2
For Each rCell In SportsRange 'loop through each cell in the range
If rCell = "hockey" Then 'check if the cell is equal to "hockey"
i = i + 1 'Row number (+1 everytime I found another "hockey")
HokySh.Cells(i, 2) = i - 2 'S No.
HokySh.Cells(i, 3) = rCell.Offset(0, -1) 'School
HokySh.Cells(i, 4) = rCell.Offset(0, -2) 'Background
HokySh.Cells(i, 5) = rCell.Offset(0, -3) 'Age
End If
Next rCell
End Sub
When i need to copy data from filtered table i use range.SpecialCells(xlCellTypeVisible).copy. Where the range is range of all data (without a filter).
Example:
Sub copy()
'source worksheet
dim ws as Worksheet
set ws = Application.Worksheets("Data")' set you source worksheet here
dim data_end_row_number as Integer
data_end_row_number = ws.Range("B3").End(XlDown).Row.Number
'enable filter
ws.Range("B2:F2").AutoFilter Field:=2, Criteria1:="hockey", VisibleDropDown:=True
ws.Range("B3:F" & data_end_row_number).SpecialCells(xlCellTypeVisible).Copy
Application.Worksheets("Hoky").Range("B3").Paste
'You have to add headers to Hoky worksheet
end sub
it needs to be .Row.count not Row.Number?
That's what I used and it works fine
Sub TransfersToCleared()
Dim ws As Worksheet
Dim LastRow As Long
Set ws = Application.Worksheets("Export (2)") 'Data Source
LastRow = Range("A" & Rows.Count).End(xlUp).Row
ws.Range("A2:AB" & LastRow).SpecialCells(xlCellTypeVisible).Copy

Get value from SpinButton to determine the number of loops

Is there any way to get the value of a cell that is connected to a SpinButton and to determine the number of times a data will be copied.
For example everytime you press the Left or Right Button it will subtract or add a value with a minimum of 1 and maximum of 1000.
This is my code so far in copying data.
Range("D3:D10").Copy
Worksheets("Sheet2").Range("A2").PasteSpecial , Transpose:=True
The range of the cell that is associate in the SpinButton is "G7"
I want to get the value of that cell G7 to determine how many times it will copy the data from range D3 to D10.
The values is on "Sheet1". I want it to be pasted on "Sheet2".
Assuming the active sheet has the G7 and range to copy
Range("D3:D10").Copy
Worksheets("Sheet2").Range("A2:A" & 2 + [G7].Value).PasteSpecial , Transpose:=True
Application.CutCopyMode = False
Edit: paste to first available cell in sheet2
-
Sub Copy_Trspose()
Dim LstRw As Long, pRng As Range, cRng As Range, x
Dim sh As Worksheet, ws As Worksheet
Set ws = Sheets("Sheet2")
Set sh = Sheets("Sheet1")
Application.ScreenUpdating = False
With sh
Set cRng = .Range("D3:D10")
x = .Range("G7").Value
End With
With ws
LstRw = .Cells(.Rows.Count, "A").End(xlUp).Row + 1
Set pRng = .Range(.Cells(LstRw, "A"), .Cells(LstRw + x, "A"))
End With
cRng.Copy
pRng.PasteSpecial , Transpose:=True
Application.CutCopyMode = False
End Sub

cell values from filtered rows in excel using vba

I have a excel file where I have used the filter on a specific column. After that it returned me 3 visible rows. Now I want to extract a cell value from visible 3 rows on same column. How to write the vba code for that.
Note: I am using UFT, vb script for connecting excel application.
Environment.value("Path1")="C:Test\Data1\"
Environment.value("FileName")="ExcelTest.xlsx"
Set obj = CreateObject("Excel.Application")
obj.visible=True
Set obj1 = obj.Workbooks.Open(Environment("Path1")&Environment("FileName"))
Set obj2=obj1.Worksheets("RESULT")
obj2.Range("L1").Autofilter 12,"abcdef"
obj2.Range("A1").Autofilter 1,Array("Bucket",2,"Material","Flags"),7
rows=obj2.usedrange.columns(1).specialcells(12).count-1
if you want to work with visible cells only.
An example in which you filter on column A, to be adapted for you data, of course:
Sub test()
Dim ws As Worksheet
Dim i As Long, LastRow As Long
Dim r As Range, Cell As Range, Range As Range
Set ws = ThisWorkbook.Sheets("Sheet1")
Set r = ws.Range("A1")
ws.AutoFilterMode = False
With r
.AutoFilter Field:=1, Criteria1:="Yourcriteria"
LastRow = ws.Cells(Rows.Count, 1).End(xlUp).Row
Set Range = ws.Range(ws.Cells(2, 1), ws.Cells(LastRow, 1))
For Each Cell In Range.SpecialCells(xlCellTypeVisible)
'whatever you need to be done
Next Cell
End With
ws.AutoFilterMode = False
End Sub

Copy Rows from Filtered Data and Insert into Existing Data

I am trying to copy rows of data (which may or may not be filtered) and INSERT it into rows above existing data (sort of a rolling schedule). Below is my code that works for unfiltered data. If I apply any filters to the data to be copied, my macro will only copy 1 cell. Can anyone provide an example of a macro that can copy both filtered and unfiltered data?
Sub DynamicRange()
'Best used when first column has value on last row and first row has a value in the last column
Dim sht As Worksheet
Dim LastRow As Long
Dim LastColumn As Long
Dim StartCell As Range
Dim SelectedRange As Range
Set sht = ActiveWorkbook.ActiveSheet
Set StartCell = Range("C9")
If IsEmpty(StartCell.Value) = True Then
MsgBox "Enter Dates to export"
Exit Sub
End If
'Find Last Row and Column
LastRow = sht.Cells(sht.Rows.Count, StartCell.Column).End(xlUp).Row
LastColumn = sht.Cells(StartCell.Row, sht.Columns.Count).End(xlToLeft).Column
'Select Range and Copy
Set SelectedRange = sht.Range(StartCell, sht.Cells(LastRow, LastColumn))
SelectedRange.Select
Selection.SpecialCells(xlCellTypeVisible).Select
Selection.Copy
'Select sheet "TRACKER" insert values above previous data
Sheets("TRACKER").Select
Range("B9").Select
Selection.Insert Shift:=xlDown
'clear selection
Application.CutCopyMode = False
End Sub
I've rewritten your sub procedure and tried to avoid the use of .Select and Selection. Relying on properties like the ActiveCell¹ and ActiveSheet¹ is haphazard at best.
Sub DynamicRange()
Dim sc As Range, sht As Worksheet
Set sht = ActiveWorkbook.Worksheets("Sheet1") '<~~ set this worksheet reference properly
'btw, if you really needed ActiveWorkbook here then you would need it with Worksheets("TRACKER") below.
With sht
Set sc = .Range("C9") 'don't really have a use for this
If IsEmpty(.Range("C9")) Then
MsgBox "Enter Dates to export"
Exit Sub
End If
With .Range(.Cells(9, 3), .Cells(9, Columns.Count).End(xlToLeft))
With Range(.Cells(1, 1), .Cells(Rows.Count, .Columns.Count).End(xlUp))
'got the range; determine non-destructively if anything is there
If CBool(Application.Subtotal(103, .Cells)) Then
'there are visible values in the cells
.Cells.Copy _
Destination:=Worksheets("TRACKER").Cells(Rows.Count, 2).End(xlUp).Offset(1, 0)
End If
End With
End With
End With
End Sub
The worksheet's SUBTOTAL function does not count hidden values so it is a good non-destructive test for the existence of visible values. You do not need to copy the Range.SpecialCells with the xlCellTypeVisible property specifically. A regular Range.Copy method will only copy visible cells. By immediately specifying the destination, there is no need to transfer the ActiveSheet property to the TRACKER worksheet; only the top-left corner of the destination need be specified.
¹ See How to avoid using Select in Excel VBA macros for more methods on getting away from relying on select and activate to accomplish your goals.

Resources