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

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.

Related

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

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

How to alter the color of cells if they are a certain other color?

I have written a short Macro to change cells of a given colour to another colour in a workbook. This code throws no errors however it simply does nothing.
I have already tested the colour codes to see if they are correct using MsgBox ActiveCell.DisplayFormat.Interior.color
Option Explicit
Sub Recolour()
Application.ScreenUpdating = False
Dim Sheet As Worksheet
Dim Rng As Range
Dim OldColour As Variant
Dim NewColour As Variant
Dim Cell As Range
Set Rng = ActiveSheet.Range("A1:Y457")
OldColour = 128
NewColour = RGB(134, 38, 51)
For Each Sheet In ThisWorkbook.Worksheets
For Each Cell In Rng.Cells
If ActiveCell.DisplayFormat.Interior.Color = OldColour _
Then _
Set ActiveCell.DisplayFormat.Interior.Color = NewColour _
Else
Next Cell
Next Sheet
Application.ScreenUpdating = True
End Sub
This is probably something simple and daft however I need to ask.
DisplayFormat is read-only. If you want to change the property, you need to drop DisplayFormat. Also, if you are using For each Cell, then you should refer to Cell, not ActiveCell.
For Each Sheet In ThisWorkbook.Worksheets
For Each Cell In Rng.Cells
If Cell.Interior.color = OldColour Then
Cell.Interior.color = NewColour
End if
Next Cell
Next Sheet
You only need to Set object variables in VBA, your if statement is also problematic. Try:
For Each Sheet In ThisWorkbook.Worksheets
For Each Cell In Rng.Cells
If ActiveCell.DisplayFormat.Interior.color = OldColour Then
ActiveCell.DisplayFormat.Interior.color = NewColour
End if
Next Cell
Next Sheet

Copy/Paste Yellow Highlighted Cells in a new WorkSheet VBA

I'm trying to get this one done.
This macro should open a workbook (workbook names always change and there's always just one sheet to process). This works.
Set the range for the whole sheet; works fine.
And search the entire sheet for cells highlighted in yellow, and copy these cells into a new sheet... and this is where I need help!
I am really new to VBA and thats what I have so far:
Option Explicit
Sub test3()
Dim data As Variant
Dim rngTemp As Range
Dim cell As Range
'//open Workbook
data = Application.GetOpenFilename(, , "Open Workbook")
Workbooks.Open data
'// set Range ( Whole Sheet)
Set rngTemp = Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious)
If Not rngTemp Is Nothing Then
Range(Cells(1, 1), rngTemp).Select
End If
'// Search for Yellow highlighted Cells and (if you find one)
'// Copy Cell B1 + the 3rd Cell in the column (of the highlighted Cell) + the value highlighted Cell
'// and paste in new Sheet
For Each cell In rngTemp.Cells
If rngTemp.Interior.ColorIndex = 6 Then
cell.Select
Selection.Copy
Sheets.Add
Range("A1").PasteSpecial
Application.CutCopyMode = False
End If
Next
End Sub
Sub test3()
Dim wbName As string
Dim rngTemp As Range
Dim r As Range
DIM TARGETSHEET AS WORKSHEET
DIM TARGET AS RANGE
'//open Workbook
wbName = Application.GetOpenFilename(, , "Open Workbook")
if wbName = "" or wbname = "CANCEL" then exit sub
Workbooks.Open wbname
'// set Range ( Whole Sheet)
Set rngTemp = Activesheet.usedrange
SET TARGETSHEET = ACTIVEWORKBOOK.WORKSHEETS.ADD()
SET TARGET = TARGETSHEET.RANGE("A1")
'// Search for Yellow highlighted Cells and (if you find one)
'// Copy Cell B1 + the 3rd Cell in the Column (of the highlighted Cell) + the value highlighted Cell
'// and paste in new Sheet
For Each r In rngTemp
If r.Interior.ColorIndex = 6 Then
TARGET = rngtemp.parent.range("B1")
TARGET.OFFSET(0,1) = r
TARGET.OFFSTE(0,2) = rngtemp.parent.cells(3,r.column)
'I've assumed you want them across the first row
SET TARGET = TARGET.OFFSET(1,0)
End If
Next r
End Sub

Find total description and copy paste values 4 rows down

Does anyone know what other command I need to use to copy the row label "Total WI Expenses" down 4 rows below?
The following code will find the "Total WI Expenses" and copy it to a range, however, I just want to find the total and copy the data to the 4 rows down. They need to be copied and pasted as values.
Sub Test()
Dim ws As Worksheet
Set ws = ActiveSheet
Dim rw As Long, Cell As Range
For Each Cell In ActiveSheet.Range("B:B")
If Cell.Value = "Total WI Expenses" Then
Cell.EntireRow.copy
Range("A71").PasteSpecial (xlPasteValues)
Application.CutCopyMode = False
End If
Next
End Sub
I sincerely appreciate your assistance.
Instead of running a For loop over the whole(!) column you may check first, if something is in the column, and then .Find the wanted value. If you found a result, then you may use it's row number.
Instead of Copy/Paste you may just assign the Range.Value to get the values without formatting.
This code copies the whole row's values four rows below.
Sub Test()
Dim ws As Worksheet
Dim c As Range
Set ws = ActiveSheet
If WorksheetFunction.CountA(ws.Columns(2)) > 0 Then
Set c = ws.Columns(2).Find( _
What:="Total WI Expenses", _
After:=ws.Cells(1, 2), _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext)
If Not c Is Nothing Then
ws.Rows(c.Row + 4).Value = ws.Rows(c.Row).Value
End If
Set c = Nothing
End If
Set ws = Nothing
End Sub

VBA Find and replace all cells found in worksheet with format found in column

I'm looking for a vba code snippet to get me started.
I have a column in one of my worksheets that has values (non-unique). From this column I need to either
Replace all found cells in the entire workbook that have the same value with the format found in the original cell or
If the cell has no background color to assign it a new unique color background (unique is based on previous cells in the column) and find and replace all cells in the entire workbook with this format.
I don't believe I can use conditional formatting for I have too many cells that would meet the criteria and it would slow excel down to an unacceptable speed.
Alright so based on the prior comments here is what I have so far.
Sub FormatFill()
Dim sRng As Range
Dim cCell As Range
Dim nCell As Range
Dim bClr, lVal
Application.ScreenUpdating = False
Range("B1").Select
Range(Selection, ActiveCell.SpecialCells(xlLastCell)).Select
Set sRng = Selection
'Fill all legend formats
Range("A1").Select
Range(Selection, Selection.End(xlDown)).Select
For Each cell In Selection
lVal = cell.Value
bClr = cell.Interior.Color
Set cCell = sRng.Find(What:=lVal, LookIn:=xlValues, LookAt:=xlWhole, SearchOrder:=xlByRows, _
SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
If Not cCell Is Nothing Then
Set nCell = cCell
Do
cCell.Interior.Color = bClr
Set cCell = sRng.FindNext(After:=cCell)
If Not cCell Is Nothing Then
If cCell.Address = nCell.Address Then Exit Do
Else
Exit Do
End If
Loop
End If
Next
Application.ScreenUpdating = True
End Sub
I am still working out how to capture and assign the unique colors for the other values on the rest of the workbook.

Resources