Please help me for this problem:
I use this vba from this link:
Sub test()
Dim rng1 As Range, rng2 As Range, rngName As Range, i As Integer, j As Integer
For i = 1 To Sheets("Sheet2").Range("B" & Rows.Count).End(xlUp).Row
Set rng1 = Sheets("Sheet2").Range("B" & i)
For j = 1 To Sheets("Sheet1").Range("C" & Rows.Count).End(xlUp).Row
Set rng2 = Sheets("Sheet1").Range("C" & j)
Set rngName = Sheets("Sheet1").Range("B" & j)
If rng1.Value = rng2.Value Then
rngName.Copy Destination:=Worksheets("Sheet2").Range("E" & i)
End If
Set rng2 = Nothing
Next j
Set rng1 = Nothing
Next i
End Sub
Can somebody show me how to combine rngName.Copy with
Selection.PasteSpecial Paste:=xlPasteFormulas, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
I would like to earn, that the rngName.Copy copy only text, because I have special color, text format, comment etc. in the cells, where the vba paste the changed values and I would like to stay these.
Do you mean this?
rngName.Copy
Worksheets("Sheet2").Range("E" & i).PasteSpecial Paste:=xlPasteFormulas, _
Operation:=xlNone, SkipBlanks:=False, Transpose:=False
You may also want xlPasteValues instead of xlPasteFormulas. In this case, a simpler and better way is to take the value without using copy/paste:
Worksheets("Sheet2").Range("E" & i).Value = rngName.Value
All of the methods above conserve the formatting of the destination.
Related
I am very new to macro . Iam using this code for concatenating two column values into one column. This code today failed , for 10 first rows of the sheet , and it worked for the rest of the rows.Why happened like this , i havent changed anything at all !
Thanks.
Sub FixCrossSell()
Dim wb As Workbook
Dim lr As Long
Set wb = ThisWorkbook
wb.Worksheets("CrossSell").Activate
Cells(2, 1).Value = "=B2&E2"
lr = Cells(Rows.Count, 2).End(xlUp).Row
Range("A2").Select
Selection.Copy
Range("A3:A" & lr).Select
Selection.PasteSpecial Paste:=xlPasteFormulas, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
Application.Calculate
Range("A2:A" & lr).Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
End Sub
Try this:
Sub FiXCrossSell()
Dim lr As Long
With Worksheets("CrossSell")
lr = .Cells(Rows.Count, 2).End(xlUp).Row
With .Range("A2:A" & lr)
.FormulaR1C1 = "=rc2&rc5"
.Value = .Value
End With
End With
End Sub
Probably just count the cells in column B, then place the Formula in Column A
Sub Button1_Click()
Dim LstRw As Long, Rng As Range, Sh As Worksheet
Set Sh = Sheets("CrossSell")
With Sh
LstRw = .Cells(.Rows.Count, "B").End(xlUp).Row
Set Rng = .Range("A2:A" & LstRw)
Rng = "=B2&E2"
End With
End Sub
Ah.. I see someone else answered this while I was thinking about it.
I have seen some examples but they have been using .Select and .Activate. I am trying to learn how to not use those anymore because everyone says you should try to stay away from them.
I want to take a row, then copy it to the first blank row on the other sheet. I was close but it just isn't working.
UsdRws = Range("A" & Rows.Count).End(xlUp).Row
With Sheets("Totals by Department")
.Range("A1:Z" & UsdRws).autofilter Field:=1, Criteria1:="1450"
.Range("A2:Z" & UsdRws).SpecialCells(xlCellTypeVisible).EntireRow.COPY
End With
Set NextRow = Range("A" & Sheets(2).UsedRange.Rows.Count + 1)
Sheets(2).NextRow.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
Application.CutCopyMode = False
Set NextRow = Nothing
The first part copies perfectly, I really just need help pasting it over on the other sheet. I will also take other recommendations for cleaning the code up. Like I said I am trying to learn to write better. The second part is messy because I have been adding and editing it but now I am lost.
Your "NextRow" object is a Range object, but you are calling it as if it were a method or property of Sheets(2).
Try removing the Sheets(2). and just start with Next Row.
Set NextRow = Sheets(2).Range("A" & Sheets(2).UsedRange.Rows.Count + 1)
NextRow.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
Application.CutCopyMode = False
' UsdRws is equal the last used row on whichever sheet is active at the moment that this code runs
UsdRws = Range("A" & Rows.Count).End(xlUp).Row
' this code properly references ranges on a specific worksheet, regardless of which worksheet is active
With Sheets("Totals by Department")
.Range("A1:Z" & UsdRws).autofilter Field:=1, Criteria1:="1450"
.Range("A2:Z" & UsdRws).SpecialCells(xlCellTypeVisible).EntireRow.COPY
End With
' NextRow is reference to a cell on whichever sheet is active at the moment that this code runs
' but the row referenced is same as the first emply cell on Sheets(2)
Set NextRow = Range("A" & Sheets(2).UsedRange.Rows.Count + 1)
' NextRow is already a range .... so it should be NextRow.PasteSpecial ......
Sheets(2).NextRow.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
Application.CutCopyMode = False
Set NextRow = Nothing
this may be what you want
With Sheets("Totals by Department")
UsdRws = .Range("A" & .Rows.Count).End(xlUp).Row
.Range("A1:Z" & UsdRws).autofilter Field:=1, Criteria1:="1450"
.Range("A2:Z" & UsdRws).SpecialCells(xlCellTypeVisible).EntireRow.COPY
End With
Set NextRow = Sheets(2).Range("A" & Sheets(2).UsedRange.Rows.Count + 1)
NextRow.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
Application.CutCopyMode = False
Set NextRow = Nothing
Please help me with the following problem:
I have 3 ranges each on a different sheet.
I have to copy every range (till its last row with data and paste values with all of them on sheet "Rezultat" (in order so they will not paste on each other)
This is my code:
Sub MultipleRangesPaste()
Dim rng1 As Range, rng2 As Range, rng3 As Range, MultipleRng As Range
With ThisWorkbook.Sheets("REZULTAT")
Set rng1 = Sheets("NEVOI PERSONALE").Range("F2:H" & Range("H" & Rows.Count).End(xlUp).Row)
Set rng2 = Sheets("RATE").Range("F2:H" & Range("H" & Rows.Count).End(xlUp).Row)
Set rng3 = Sheets("CARDURI").Range("G2:I" & Range("I" & Rows.Count).End(xlUp).Row)
Set MultipleRng = .Range(rng1 & rng2 & rng3) ' AT THIS LINE DEBUG SAID IT IS A PROBLEM
End With
MultipleRng.Copy
With ThisWorkbook.Sheets("REZULTAT").Range("A2")
.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
Application.CutCopyMode = False
End With
End Sub
My idea is pretty much as the one of #Shai Rado, but I did not write the whole code (that pleasure was intended for the OP) and I have a function, that locates the last used row, based on a column:
Option Explicit
Sub MultipleRangesPaste()
Dim rng1 As Range
Dim rng2 As Range
Dim rng3 As Range
Dim MultipleRng As Range
Dim lngRowSource As Long
Dim lngRowTarget As Long
Dim lngRows As Long
With ThisWorkbook.Sheets("REZULTAT")
Set rng1 = Sheets("NEVOI PERSONALE").Range("F2:H" & Range("H" & Rows.Count).End(xlUp).Row)
Set rng2 = Sheets("RATE").Range("F2:H" & Range("H" & Rows.Count).End(xlUp).Row)
Set rng3 = Sheets("CARDURI").Range("G2:I" & Range("I" & Rows.Count).End(xlUp).Row)
End With
rng1.Copy
With ThisWorkbook.Sheets("REZULTAT").Range("A2")
.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
Application.CutCopyMode = False
End With
rng2.Copy
'here locate the last row of column A in ThisWorkbook.Sheets("REZULTAT") and paste from there
rng3.Copy
'here locate the last row of column A in ThisWorkbook.Sheets("REZULTAT") and paste from there
End Sub
Public Function last_row(Optional str_sheet As String, Optional column_to_check As Long = 1) As Long
Dim shSheet As Worksheet
If str_sheet = vbNullString Then
Set shSheet = ThisWorkbook.ActiveSheet
Else
Set shSheet = ThisWorkbook.Worksheets(str_sheet)
End If
last_row = shSheet.Cells(shSheet.Rows.Count, column_to_check).End(xlUp).Row
End Function
I usually use application.Union, but it doesn't work on multiple ranges from different worksheets. So in this case, you have to do it manually, copy>>paste each range, into the next available row.
Sub MultipleRangesPaste()
Dim rng1 As Range, rng2 As Range, rng3 As Range, MultipleRng As Range
Dim NextRow As Long
Set rng1 = Sheets("NEVOI PERSONALE").Range("F2:H" & Sheets("NEVOI PERSONALE").Cells(Sheets("NEVOI PERSONALE").Rows.Count, "H").End(xlUp).Row)
Set rng2 = Sheets("RATE").Range("F2:H" & Sheets("RATE").Cells(Sheets("RATE").Rows.Count, "H").End(xlUp).Row)
Set rng3 = Sheets("CARDURI").Range("G2:I" & Sheets("CARDURI").Cells(Sheets("CARDURI").Rows.Count, "I").End(xlUp).Row)
With ThisWorkbook.Sheets("REZULTAT")
' find current next empty row on Column A
NextRow = .Cells(.Rows.Count, "A").End(xlUp).Row + 1
rng1.Copy
.Range("A" & NextRow).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
Application.CutCopyMode = False
' find current next empty row on Column A
NextRow = .Cells(.Rows.Count, "A").End(xlUp).Row + 1
rng2.Copy
.Range("A" & NextRow).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
Application.CutCopyMode = False
' find current next empty row on Column A
NextRow = .Cells(.Rows.Count, "A").End(xlUp).Row + 1
rng3.Copy
.Range("A" & NextRow).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
Application.CutCopyMode = False
End With
End Sub
I'm having trouble copying specific Rows with vba.
Here my Code:
Dim color1 As Integer
Dim color2 As Integer
Dim lines As Integer
Workbooks.Open Filename:="D:\01 January.xlsm", _
UpdateLinks:=0
lines = WorksheetFunction.CountA(Range("U:U")) - 1
Dim i As Integer
For i = 6 To lines + 6
color1 = Cells(i, 21).Value
color2 = Cells(i, 22).Value
If IsNumeric(Cells(i, 21)) Then
Select Case color1 & color2
Case Evaluate("=White") & Evaluate("=Blue")
Rows(i & ":" & i).Select
Case Evaluate("=Yellow") & Evaluate("=Yellow")
Rows(i & ":" & i).Select
Case Evaluate("=Yellow") & Evaluate("=Green")
Rows(i & ":" & i).Select
End Select
End If
Next i
Selection.Copy
Windows("Test.xlsm").Activate
Rows("11:11").Select
Selection.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
Selection.PasteSpecial Paste:=xlPasteFormulas, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
End Sub
So as you might see, I am trying to select Rows, that meet the criteria in the January.xlsm and paste them afterwards into the test.xlsm
At the moment it only pastes the last selected row and not all of them.
I'm pretty new to vba, so I would really need your help here. What I got in my mind, is to put all the needed rows into an array and then copy it into the other workbook. But no idea if thats good or just rubish and if that would work, I can't find a solution...
Thanks for all your help!
The reason it only pastes the last row is because you're looping through selecting the individual rows but not doing anything with them. See amended code.
I've removed the redundant selections in the case statement and provided a range/union combo to create your custom range to ensure you're only pasting to the worksheet once.
Dim color1 As Integer
Dim color2 As Integer
Dim lines As Integer
Workbooks.Open Filename:="D:\01 January.xlsm", _
UpdateLinks:=0
lines = WorksheetFunction.CountA(Range("U:U")) - 1
Dim i As Integer
Dim rngUnion As Range
Dim booCopy As Boolean
For i = 6 To lines + 6
booCopy = True
color1 = Cells(i, 21).Value
color2 = Cells(i, 22).Value
If IsNumeric(Cells(i, 21)) Then
Select Case color1 & color2
Case Evaluate("=White") & Evaluate("=Blue")
Case Evaluate("=Yellow") & Evaluate("=Yellow")
Case Evaluate("=Yellow") & Evaluate("=Green")
Case Else
booCopy = False
End Select
End If
If booCopy = True Then
If rngUnion Is Nothing Then
Set rngUnion = Rows(i & ":" & i)
Else
Set rngUnion = Union(rngUnion, Rows(i & ":" & i))
End If
End If
Next i
If Not rngUnion Is Nothing Then
rngUnion.Copy
Windows("Test.xlsm").Activate
With Rows("11:11")
.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
.PasteSpecial Paste:=xlPasteFormulas, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
End With
Application.CutCopyMode = False
End If
End Sub
The reason this only pastes the last selected row is because you are not copying and pasting within the loop. If you move the Selection.Copy/Paste within the loop the code should work. A better way to do this would be to avoid copying and pasting entirely and directly set the values of the rows. See code below:
Dim i As Integer
For i = 6 To lines + 6
color1 = Cells(i, 21).Value
color2 = Cells(i, 22).Value
If IsNumeric(Cells(i, 21)) Then
Select Case color1 & color2
Case Evaluate("=White") & Evaluate("=Blue"):
Workbooks("Test").Sheets("Sheet1").Rows(i).Value = _
Workbooks("01 January").Sheets("Sheet1").Rows(i).Value
...
End Select
End If
Next i
You can just update the sheet or workbook names as necessary but this method is substantially faster than copying and pasting.
should you have a large number of rows to be copied and paste it's safer not to rely neither on Union() nor Address() methods and switch to a "helper" column where to first mark the row for copying and then copy and paste in one shot. This is also much faster then the two methods above
you can also take advantage of SpecialCells() method to filter "numeric" cells only:
Dim lines As Long
Dim cell As Range
Workbooks.Open Filename:="D:\01 January.xlsm", UpdateLinks:=0
lines = WorksheetFunction.CountA(Range("U:U")) - 1
With Range(Cells(6, "U"), Cells(lines + 6, "U")) '<--| reference your relevant range in column "U"
For Each cell In .SpecialCells(xlCellTypeConstants, xlNumbers) '<--| loop through "numeric" cells only
Select Case cell.Value & cell.Offset(, 1).Value
Case Evaluate("=White") & Evaluate("=Blue"), Evaluate("=Yellow") & Evaluate("=Yellow"), Evaluate("=Yellow") & Evaluate("=Green")
cell.Offset(, 2).Value = 1 '<--| mark row for copying&pasting
End Select
Next
With .Offset(, 2) '<-- consider column "W" cells corresponding to referenced cells
If WorksheetFunction.CountA(.Cells) > 0 Then '<--| if there's at least one row marked for copy&paste
.SpecialCells(xlCellTypeConstants, xlNumbers).EntireRow.Copy '<--| copy all marked rows
With Workbooks("Test.xlsm").ActiveSheet.Rows("11:11") '<--| reference target range
.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
.PasteSpecial Paste:=xlPasteFormulas, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
End With
Application.CutCopyMode = False '<--| clear clipboard
End If
.ClearContents '<--| clear "helper" column
End With
End With
My program works by calling a number of macros as such:
Sub Start()
Call ClearAll
Call Sales_Download
Call Copy_Sales
Call Receipt_Download
Call Copy_Receipt
Call Copy1
Call Sales_Summary
Call Copy2
Call Receipt_Summary
End Sub
My program breaks at the copy2, which is essentially an exact replica of copy1 wich works fine. When copy2 is ran by itself it works perfectly, but when I attempt to run the entire program it debugs. The bolded line is where the debug happens.
Sub Copy2()
' Copies all data from Receipt Download tab for each location, and saves in a seperate folder
Dim i As Long
Dim lngLastRow As Long, lngPasteRow As Long
'Find the last row to search through
lngLastRow = Sheets("Receipt_Download").Range("J65535").End(xlUp).Row
'Initialize the Paste Row
lngPasteRow = 2
Dim rng As Range
Dim c As Range
Dim endrow
Dim strName As String
Dim ws As Worksheet
Dim j As Long
endrow = Sheets("names").Range("A65000").End(xlUp).Row
Set rng = Sheets("names").Range("A2:A" & endrow)
j = 1
FBO = strName
For Each c In rng
For i = 2 To lngLastRow
strName = c.Value
If Sheets("Receipt_Download").Range("J" & i).Value = strName Then
Sheets("Receipt_Download").Select
Range("A" & i & ":IV" & i).Copy
Sheets("Summary").Select
Range("A" & lngPasteRow & ":IV" & lngPasteRow).Select
ActiveSheet.Paste
lngPasteRow = lngPasteRow + 1
End If
Next i
j = j + 1
Sheets("Receipt_Download").Select
Rows("1:1").Select
Selection.Copy
Sheets("Summary").Select
Rows("1:1").Select
ActiveSheet.Paste
Columns("D:E").Select
Selection.NumberFormat = "m/d/yyyy"
Sheets("Summary").Select
Range("B25000").Select
ActiveCell.FormulaR1C1 = "Grand Total"
Range("B25000").Select
Selection.Font.Bold = True
Columns("G:G").Select
Selection.Insert Shift:=xlToRight
Range("G1").Select
ActiveCell.FormulaR1C1 = "=IF(RC[-2]=0,""0"",RC[-1])"
Range("G1").Select
Selection.AutoFill Destination:=Range("G1:G24950")
Range("G25000").Select
ActiveCell.FormulaR1C1 = "=SUM(R[-24950]C:R[-1]C)"
Range("G25000").Select
Selection.Copy
Range("F25000").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Columns("G:G").Select
Application.CutCopyMode = False
Selection.Delete Shift:=xlToLeft
Sheets("Summary").Select
Range("F25000").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Names").Select
With Columns("B")
.Find(what:="", after:=.Cells(1, 1), LookIn:=xlValues).Activate
End With
ActiveSheet.Paste
Sheets("Summary").Select
Range("b1:b30000").Select
For Each Cell In Selection
If Cell.Value = "" Then
Cell.ClearContents
End If
Next Cell
Range("b1:b30000").Select
Selection.SpecialCells(xlCellTypeBlanks).EntireRow.Delete
Sheets("Summary").Select
Range("D2").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Names").Select
***With Columns("C")
.Find(what:="", after:=.Cells(1, 1), LookIn:=xlValues).Activate***
End With
ActiveSheet.Paste
Sheets("Summary").Select
Range("A1:Z5000").Select
Selection.Copy
Workbooks.Add
ActiveSheet.Paste
Range("A1").Select
Application.CutCopyMode = False
Selection.Copy
Application.CutCopyMode = False
File = "C:\Documents and Settings\user\Desktop\New FBO\" & strName & "\" & strName & " Receipts.xls"
ActiveWorkbook.SaveAs Filename:=File, _
FileFormat:=xlNormal, Password:="", WriteResPassword:="", _
ReadOnlyRecommended:=False, CreateBackup:=False
ActiveWorkbook.Close
IngPasteRow = IngPasteRow + 1
Sheets("Summary").Select
Selection.ClearContents
Next c
End Sub
I would really appreciate any help, I am certainly no VBA master and this has been quite troublesome.
Replace this part of your code
Sheets("Summary").Select
Range("D2").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Names").Select
With Columns("C")
.Find(what:="", after:=.Cells(1, 1), LookIn:=xlValues).Activate
End With
ActiveSheet.Paste
with
Dim lRow As Long
With Sheets("Names")
lRow = .Range("C" & .Rows.Count).End(xlUp).Row + 1
Sheets("Summary").Range("D2").Copy .Range("C" & lRow)
End With
Now try it.
Also few tips
Avoid .Select and .Activate They are a major cause of errors
Indent and appropriately comment your code. Your code is very difficult to read. If you don't indent/comment your code, you will realize that you will not recognize your OWN code if you visit it say after a week :)
In support of Siddharth's answer above, I have take a portion of your code (up to where your break happens) and have indented and avoided the .Select and .Activate that he mentions. Hopefully this gives you a good start on how to make your code more readable for debugging and understanding.
For Each c In rng
For i = 2 To lngLastRow
strName = c.Value
If Sheets("Receipt_Download").Range("J" & i).Value = strName Then
Sheets("Receipt_Download").Range("A" & i & ":IV" & i).Copy _
Destination:=Sheets("Summary").Range("A" & lngPasteRow & ":IV" & lngPasteRow)
lngPasteRow = lngPasteRow + 1
End If
Next i
j = j + 1
Sheets("Receipt_Download").Rows("1:1").Copy Destination:=Sheets("Summary").Rows("1:1")
With Sheets("Summary")
.Columns("D:E").NumberFormat = "m/d/yyyy"
With .Range("B25000")
.Formula = "Grand Total"
.Font.Bold = True
End With
.Columns("G:G").Insert Shift:=xlToRight
With Range("G1")
.FormulaR1C1 = "=IF(RC[-2]=0,""0"",RC[-1])"
.AutoFill Destination:=Range("G1:G24950")
End With
With ("G25000")
.FormulaR1C1 = "=SUM(R[-24950]C:R[-1]C)"
.Copy
End With
.Range("F25000").PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
.Columns("G:G").Delete Shift:=xlToLeft
.Range("F25000").Copy Destination:=Sheets("Names").Columns("B").Find(what:="", after:=Sheets("Names").Cells(1, 1), LookIn:=xlValues)
End With