I am currently facing above error when running vba as below(vba newbie here). Would you please see what is causing this error? I am using this script to parse information from a text file in excel with around 65000 rows.
When I click 'debug' , it highlighted this row
If Cells(i, 2).Value = "Type: Error" And Cells(i + 5, 2).Value = " STATUS : FAILURE" Then"
Thank you.
Sub color()
Dim i As Long
Dim j As Long
j = 0
ActiveSheet.Name = "Raw data"
sheets.Add.Name = "Error"
Range("A1:B1").Value = Array("DN", "Error details")
Worksheets("Raw data").Activate
For i = 1 To Rows.Count
If Cells(i, 2).Value = "Type: Error" And Cells(i + 5, 2).Value = " STATUS : FAILURE" Then
ActiveSheet.Cells(i, 2).Select
ActiveCell.Offset(-1, 0).Copy
Worksheets("Error").Range("A2").Offset(j, 0).PasteSpecial xlPasteAll
ActiveCell.Offset(6, 0).Copy
Worksheets("Error").Range("B2").Offset(j, 0).PasteSpecial xlPasteAll
j = j + 1
ElseIf Cells(i, 2).Value = "Type: Error" And Cells(i + 4, 2).Value = "Caused by ConnectException: Connection timed out" Then
ActiveSheet.Cells(i, 2).Select
ActiveCell.Offset(-1, 0).Copy
Worksheets("Error").Range("A2").Offset(j, 0).PasteSpecial xlPasteAll
ActiveCell.Offset(3, 0).Copy
Worksheets("Error").Range("B2").Offset(j, 0).PasteSpecial xlPasteAll
j = j + 1
End If
Next i
End Sub
As an alternative to iterating all the rows use Find and FindNext.
Option Explicit
Sub colorError()
Dim wsErr As Worksheet, wsData As Worksheet
Dim fnd As Range, first As String
Dim j As Long, x As Long, y As Long, c As Long
' data
Set wsData = ActiveSheet ' or Sheets(1)
wsData.Name = "Raw Data"
' error sheet
Set wsErr = Sheets.Add(after:=Sheets(Sheets.Count))
wsErr.Name = "Error" & Sheets.Count
wsErr.Range("A1:B1").Value2 = Array("DN", "Error details")
j = 1
Application.ScreenUpdating = False
wsData.Activate
' scan raw data column B
With wsData.Columns(2)
Set fnd = .Find("Type: Error", lookat:=xlWhole, LookIn:=xlValues, MatchCase:=False)
If Not fnd Is Nothing Then
first = fnd.Address
Do
fnd.Interior.color = vbYellow
x = 0
If Application.Trim(fnd.Offset(5)) = "STATUS : FAILURE" Then
x = 6 ' offset to copy
y = 5
c = RGB(255, 200, 200) ' pink
ElseIf Trim(fnd.Offset(4)) = _
"Caused by ConnectException: Connection timed out" Then
x = 3 ' offset to copy
y = 4
c = RGB(255, 200, 0) ' orange
End If
' copy to errors
If x > 0 Then
j = j + 1
fnd.Offset(-1).Copy wsErr.Cells(j, "A")
fnd.Offset(x).Copy wsErr.Cells(j, "B")
' color raw data
fnd.Offset(x).Interior.color = c
fnd.Offset(y).Interior.color = vbYellow
End If
Set fnd = .FindNext(fnd)
If fnd.Row + 6 > wsData.Rows.Count Then
MsgBox "Aborted at row " & fnd.Row, vbCritical, "End of Sheet"
Exit Do
End If
Loop While fnd.Address <> first
End If
End With
Application.ScreenUpdating = True
MsgBox j - 1 & " rows written to " & wsErr.Name, vbInformation
End Sub
Related
I have a sheet with details regarding orders. In column G a specific value indicates what container (shipping container) the order is packed in.screenshot
I would like all duplicate container no. to be highlighted with different colors and their row with them.
Meaning: that when I have "container no. X" the entire row connected to X is one color and rows connected to "container no. Y" is another color and so on.
I would also like an automatic update of colors when something changes or when I hit "update values" in the data bar
Blank cells in column G should not to be colored.
Is this possible and if so, can someone help me out. I am very much a beginner with VBA.
Sub ColorCompanyDuplicates()
'Updateby Extendoffice
Dim xRg As Range
Dim xTxt As String
Dim xCell As Range
Dim xChar As String
Dim xCellPre As Range
Dim xCIndex As Long
Dim xCol As Collection
Dim I As Long
On Error Resume Next
If ActiveWindow.RangeSelection.Count > 1 Then
xTxt = ActiveWindow.RangeSelection.AddressLocal
Else
xTxt = ActiveSheet.UsedRange.AddressLocal
End If
Set xRg = Application.InputBox("please select the data range:", "Kutools for Excel", xTxt, , , , , 8)
If xRg Is Nothing Then Exit Sub
xCIndex = 2
Set xCol = New Collection
For Each xCell In xRg
On Error Resume Next
If xCell.Value <> "" Then
xCol.Add xCell, xCell.Text
If Err.Number = 457 Then
xCIndex = xCIndex + 1
Set xCellPre = xCol(xCell.Text)
If xCellPre.Interior.ColorIndex = xlNone Then xCellPre.Interior.ColorIndex = xCIndex
xCell.Interior.ColorIndex = xCellPre.Interior.ColorIndex
ElseIf Err.Number = 9 Then
MsgBox "Too many duplicate companies!", vbCritical, "Kutools for Excel"
Exit Sub
End If
On Error GoTo 0
End If
Next
End Sub
This code does number 1 and 3.
Also, it only uses bright colors.
Sub ColorCompanyDuplicates()
Dim row_start As Long, last_row As Long, color_index As Long
Dim R As Long, last_col As Long, col As Long
Dim used_range As Range, paint_row As Boolean
'CONFIG -------------------------
row_start = 5 'first row of the data set
paint_row = True 'set to false if you want to paint only the column
'--------------------------------
color_index = 33
Set used_range = ActiveSheet.UsedRange
last_col = _
used_range.Columns.Count + used_range.Column - 1
last_row = _
Cells(Rows.Count, 7).End(xlUp).Row
'clean existing rows in container names
For R = row_start To last_row
If Range("g" & R) <> "" Then
Range("g" & R).Value = Split(Range("g" & R).Value, " ")(0)
End If
Next R
'paint duplicates
For R = row_start To last_row
'if the next container name is the same and is not null then paint
If Cells(R, 7) = Cells(R + 1, 7) And Cells(R, 7) <> "" Then
If paint_row Then
For col = used_range.Column To last_col
Cells(R, col).Interior.ColorIndex = color_index
Next col
Else
For col = used_range.Column To last_col
Cells(R, col).Interior.ColorIndex = 0
Next col
Cells(R, 7).Interior.ColorIndex = color_index
End If
'FOR THE LAST ONE in the group
'if previews container name is the same and is not null then paint
ElseIf Cells(R, 7) = Cells(R - 1, 7) And Cells(R, 7) <> "" Then
If paint_row Then
For col = used_range.Column To last_col
Cells(R, col).Interior.ColorIndex = color_index
Next col
Else
For col = used_range.Column To last_col
Cells(R, col).Interior.ColorIndex = 0
Next col
Cells(R, 7).Interior.ColorIndex = color_index
End If
'and change color for the next group
color_index = color_index + 1
'avoid dark colors
If color_index = 46 Then
color_index = 33
End If
End If
Next R
'add row numbers to containers name
For R = row_start To last_row
If Range("g" & R) <> "" Then
Cells(R, 7) = Cells(R, 7) & " ROW:" & R
End If
Next R
End Sub
I would suggest for number 2 just create a refresh button or a command shortcut.
So how do i put this i am a vba rookie and i have been trying to make an excel file and the purpose is that it should be an inventory of all items one sheet is for putting items in and other is for giving them away. But that is not the problem, the thing is i wanted to have a page called "databaseinventory" where all products that are taken out are writen down but my value is doing strange. (look at the image)
So this is the input screen and if i type this
this is the output on a different sheet but i don't want it to be 0
I noticed if i change the input and add 3 rows it works but that prevents me of typing more then one product
this is the output that i want to have and i really don't know what is wrong with the code
Sub Btn_Clickweggegeven()
Dim x As Long
Dim Givenaway As Worksheet
Dim Inventory As Worksheet
Dim productn As String
Dim erow As Long
Dim rng As Range
Dim rownumber As Long
Dim row As Long
Dim wsData As Worksheet
Dim wsIn As Worksheet
Dim nextRow As Long
Dim BtnText As String
Dim BtnNum As Long
Dim strName As String
x = 2
Do While Cells(x, 1) <> ""
' go through each item on list
productn = Cells(x, 1)
' if item is not new then add quanity to total Inventory
With Worksheets("Inventory").Range("A:A")
Set rng = .Find(What:=productn, _
After:=.Cells(.Cells.Count), _
LookIn:=xlValues, _
LookAt:=xlWhole, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False)
'if item is new add item to the bottom of Inventory list
If rng Is Nothing Then
erow = Worksheets("Inventory").Cells(1, 1).CurrentRegion.Rows.Count + 1
Worksheets("Inventory").Cells(erow, 1) = Worksheets("Givenaway").Cells(x, 1)
Worksheets("Inventory").Cells(erow, 2) = Worksheets("Givenaway").Cells(x, 2)
Worksheets("Inventory").Cells(erow, 3) = Worksheets("Givenaway").Cells(x, 3)
Worksheets("Inventory").Cells(erow, 4) = Worksheets("Givenaway").Cells(x, 4)
GoTo ende
Else
rownumber = rng.row
End If
End With
Worksheets("Inventory").Cells(rownumber, 2).Value = Worksheets("Inventory").Cells(rownumber, 2).Value _
- Worksheets("Givenaway").Cells(x, 2).Value
Worksheets("Inventory").Cells(rownumber, 4).Value = Worksheets("Inventory").Cells(rownumber, 4).Value _
+ Worksheets("Givenaway").Cells(x, 2).Value
ende:
x = x + 1
Loop
'after complete delete items from Givenaway list
Worksheets("Givenaway").Select
row = 2
Do While Cells(row, 1) <> ""
Range(Cells(row, 1), Cells(row, 3)).Select
Selection.Delete
Loop
Set wsIn = Worksheets("Givenaway")
Set wsData = Worksheets("Databaseinventory")
With wsData
nextRow = .Cells(.Rows.Count, "A") _
.End(xlUp).Offset(1, 0).row
End With
With wsData
With .Cells(nextRow, 1)
.Value = Now
.NumberFormat = "mm/dd/yyyy hh:mm:ss"
End With
.Cells(nextRow, 2).Value = productn
.Cells(nextRow, 3).Value = Worksheets("Databaseinventory").Cells(rownumber, 3).Value _
+ Worksheets("Givenaway").Cells(x, 2).Value
End With
End Sub
This code is deleting the value
Worksheets("Givenaway").Select
row = 2
Do While Cells(row, 1) <> ""
Range(Cells(row, 1), Cells(row, 3)).Select
Selection.Delete
Loop
before this line copies it to Databaseinventory
Cells(nextRow, 3).Value = Worksheets("Databaseinventory").Cells(rownumber, 3).Value _
+ Worksheets("Givenaway").Cells(x, 2).Value
It appears to work if you have 3 rows is because on exit from the Do While Cells(x, 1) <> "" loop the value of x will be 3. After deleting the first record then Worksheets("Givenaway").Cells(x, 2).Value will be the value for the third record.
The database update routine also need to be within the loop
Option Explicit
Sub Btn_Clickweggegeven()
Dim wb As Workbook, rng As Range
Dim wsInv As Worksheet, wsGiven As Worksheet, wsData As Worksheet
Dim iRow As Long, iDataRow As Long, iInvRow As Long
Dim sProduct As String, nValue As Single
Set wb = ThisWorkbook
Set wsGiven = wb.Sheets("GivenAway")
Set wsInv = wb.Sheets("Inventory")
Set wsData = wb.Sheets("Databaseinventory")
iDataRow = wsData.Cells(Rows.Count, 1).End(xlUp).row
iRow = 2
With wsGiven
Do While .Cells(iRow, 1) <> ""
sProduct = .Cells(iRow, 1)
nValue = .Cells(iRow, 2)
' if item is not new then add quanity to total Inventory
With wsInv.Range("A:A")
Set rng = .Find(What:=sProduct, _
After:=.Cells(.Cells.Count), _
LookIn:=xlValues, _
LookAt:=xlWhole, _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False)
End With
If rng Is Nothing Then
iInvRow = wsInv.Cells(Rows.Count, 1).End(xlUp).row + 1
wsInv.Cells(iInvRow, 1).Resize(1, 4).Value = .Cells(iRow, 1).Resize(1, 4).Value
Else
iInvRow = rng.row
wsInv.Cells(iInvRow, 2).Value = wsInv.Cells(iInvRow, 2).Value - nValue
wsInv.Cells(iInvRow, 4).Value = wsInv.Cells(iInvRow, 4).Value + nValue
End If
' write to database
iDataRow = iDataRow + 1
With wsData.Cells(iDataRow, 1)
.Value = Now
.NumberFormat = "mm/dd/yyyy hh:mm:ss"
.Offset(0, 1) = sProduct ' col B
.Offset(0, 2) = wsInv.Cells(iInvRow, 3).Value + nValue ' col C ??
End With
iRow = iRow + 1
Loop
End With
'delete from GivenAway
wsGiven.Range("A2").Resize(iRow, 3).Delete
MsgBox iRow - 2 & " records processed", vbInformation
End Sub
I need to compare 2 excel sheets (Sheet1 (old report) & Sheet2 (new report)) for differences. If there are any additions or removals in Sheet2 compared to Sheet1 I need to print that.
I found this script to find the differences but this is not including the removals in the sheet. Can you help fixing this? Below is sample example on my expectation.
Sheet1:
S.No Name Class
abc1 1st
abc2 1st
abc3 1st
Sheet2:
S.No Name Class
abc1 1st
abc2 2nd
abc4 1st
.
Comparison should tell all these:
"Row(3,3)" is changed from "1st" to "2nd"
New row inserted in "sheet2" "Row4"
"Sheet1" "Row4" is deleted in "Sheet2"
Script currently I have:
Sub Compare2Shts()
For Each cell In Worksheets("CompareSheet#1").UsedRange
If cell.Value <> Worksheets("CompareSheet#2").Range(cell.Address) Then
cell.Interior.ColorIndex = 3
End If
Next
For Each cell In Worksheets("CompareSheet#2").UsedRange
If cell.Value <> Worksheets("CompareSheet#1").Range(cell.Address) Then
cell.Interior.ColorIndex = 3
End If
Next
End Sub
Sub CompareAnother2Shts()
For Each cell In Worksheets("CompareSheet#1").Range("A1:J50000")
If cell.Value <> Worksheets("CompareSheet#2").Range(cell.Address) Then
cell.Interior.ColorIndex = 3
End If
Next
For Each cell In Worksheets("CompareSheet#2").Range("A1:J50000")
If cell.Value <> Worksheets("CompareSheet#1").Range(cell.Address) Then
cell.Interior.ColorIndex = 3
End If
Next
End Sub
Sub FindDupes() 'assuming both sheets are in same book and book is open
Dim sht1 As Worksheet
Dim sht2 As Worksheet
Dim cell1 As Range
Dim cell2 As Range
Dim str As String
str = InputBox("Type name of first sheet")
Set sht1 = Worksheets(str)
str = InputBox("Type name of second sheet")
Set sht2 = Worksheets(str)
sht1.Range("A65536").End(xlDown).Activate
Selection.End(xlUp).Activate
LastRowSht1 = ActiveCell.Row
sht2.Activate
sht2.Range("A65536").End(xlDown).Activate
Selection.End(xlUp).Activate
LastRowSht2 = ActiveCell.Row
sht1.Activate
For rowSht1 = 1 To LastRowSht1
If sht1.Cells(rowSht1, 1) = "" Then Exit Sub
For rowSht2 = 1 To LastRowSht2
If sht1.Cells(rowSht1, 1).Value = sht2.Cells(rowSht2, 1).Value Then
sht1.Cells(rowSht1, 1).Interior.ColorIndex = 3
sht2.Cells(rowSht2, 1).Interior.ColorIndex = 3
End If
Next
Next
sht1.Cells(1, 1).Select
End Sub
******** ******** ******** ******** ******** ******** ******** ********
Sub checkrev()
With Sheets("Sheet1")
Sh1LastRow = .Cells(Rows.Count, "A").End(xlUp).Row
Set Sh1Range = .Range("A1:A" & Sh1LastRow)
End With
With Sheets("Sheet2")
Sh2LastRow = .Cells(Rows.Count, "A").End(xlUp).Row
Set Sh2Range = .Range("A1:A" & Sh2LastRow)
End With
'compare sheet 1 with sheet 2
For Each Sh1cell In Sh1Range
Set c = Sh2Range.Find( _
what:=Sh1cell, LookIn:=xlValues)
If c Is Nothing Then
Sh1cell.Interior.ColorIndex = 3
Sh1cell.Offset(0, 1).Interior.ColorIndex = 3
Else
If Sh1cell.Offset(0, 1) <> c.Offset(0, 1) Then
Sh1cell.Interior.ColorIndex = 6
Sh1cell.Offset(0, 1).Interior.ColorIndex = 6
End If
End If
Next Sh1cell
'compare sheet 2 with sheet 1
For Each Sh2cell In Sh2Range
Set c = Sh1Range.Find( _
what:=Sh2cell, LookIn:=xlValues)
If c Is Nothing Then
Sh2cell.Interior.ColorIndex = 3
Sh2cell.Offset(0, 1).Interior.ColorIndex = 3
Else
If Sh2cell.Offset(0, 1) <> c.Offset(0, 1) Then
Sh2cell.Interior.ColorIndex = 6
Sh2cell.Offset(0, 1).Interior.ColorIndex = 6
End If
End If
Next Sh2cell
End Sub
******** ******** ******** ******** ******** ******** ******** ********
Sub TestCompareWorksheets()
' compare two different worksheets in the active workbook
CompareWorksheets Worksheets("Sheet1"), Worksheets("Sheet2")
' compare two different worksheets in two different workbooks
' CompareWorksheets ActiveWorkbook.Worksheets("Sheet1"), _
Workbooks("WorkBookName.xls").Worksheets("Sheet2")
End Sub
Sub CompareWorksheets(ws1 As Worksheet, ws2 As Worksheet)
Dim r As Long, c As Integer
Dim lr1 As Long, lr2 As Long, lc1 As Integer, lc2 As Integer
Dim maxR As Long, maxC As Integer, cf1 As String, cf2 As String
Dim rptWB As Workbook, DiffCount As Long
Application.ScreenUpdating = False
Application.StatusBar = "Creating the report..."
Set rptWB = Workbooks.Add
Application.DisplayAlerts = False
While Worksheets.Count > 1
Worksheets(2).Delete
Wend
Application.DisplayAlerts = True
With ws1.UsedRange
lr1 = .Rows.Count
lc1 = .Columns.Count
End With
With ws2.UsedRange
lr2 = .Rows.Count
lc2 = .Columns.Count
End With
maxR = lr1
maxC = lc1
If maxR < lr2 Then maxR = lr2
If maxC < lc2 Then maxC = lc2
DiffCount = 0
For c = 1 To maxC
Application.StatusBar = "Comparing cells " & Format(c / maxC, "0 %") & "..."
For r = 1 To maxR
cf1 = ""
cf2 = ""
On Error Resume Next
cf1 = ws1.Cells(r, c).FormulaLocal
cf2 = ws2.Cells(r, c).FormulaLocal
On Error GoTo 0
If cf1 <> cf2 Then
DiffCount = DiffCount + 1
Cells(r, c).Formula = "'" & cf1 & " <> " & cf2
End If
Next r
Next c
Application.StatusBar = "Formatting the report..."
With Range(Cells(1, 1), Cells(maxR, maxC))
.Interior.ColorIndex = 19
With .Borders(xlEdgeTop)
.LineStyle = xlContinuous
.Weight = xlHairline
End With
With .Borders(xlEdgeRight)
.LineStyle = xlContinuous
.Weight = xlHairline
End With
With .Borders(xlEdgeLeft)
.LineStyle = xlContinuous
.Weight = xlHairline
End With
With .Borders(xlEdgeBottom)
.LineStyle = xlContinuous
.Weight = xlHairline
End With
On Error Resume Next
With .Borders(xlInsideHorizontal)
.LineStyle = xlContinuous
.Weight = xlHairline
End With
With .Borders(xlInsideVertical)
.LineStyle = xlContinuous
.Weight = xlHairline
End With
On Error GoTo 0
End With
Columns("A:IV").ColumnWidth = 20
rptWB.Saved = True
If DiffCount = 0 Then
rptWB.Close False
End If
Set rptWB = Nothing
Application.StatusBar = False
Application.ScreenUpdating = True
MsgBox DiffCount & " cells contain different formulas!", vbInformation, _
"Compare " & ws1.Name & " with " & ws2.Name
End Sub
******** ******** ******** ******** ******** ******** ******** ********
Sub Match()
r1 = Worksheets("sheet1").Cells(Rows.Count, "A").End(xlUp).Row
r2 = Worksheets("sheet2").Cells(Rows.Count, "A").End(xlUp).Row
Set r3 = Worksheets("sheet1")
Worksheets("sheet2").Range("B2").Select
For a = 2 To r2
For i = 2 To r1
If Cells(a, "A") = r3.Cells(i, "A") Then
temp = r3.Cells(i, "B")
te = te & "," & temp
Else
End If
Next i
Cells(a, "B") = te
te = ""
Next a
End Sub
Sub Match2()
Dim myCon As String
Dim myCell As Range
Dim cell As Range
For Each cell In Sheet2.Range("A2:A10")
myCon = ""
For Each myCell In Sheet1.Range("A1:A15")
If cell = myCell Then
If myCon = "" Then
myCon = myCell.Offset(0, 1)
Else
myCon = myCon & ", " & myCell.Offset(0, 1)
End If
End If
Next myCell
cell.Offset(0, 1) = myCon
Next cell
End Sub
******** ******** ******** ******** ******** ******** ******** ********
Sub Duplicates()
ScreenUpdating = False
'get first empty row of sheet1
'find matching rows in sheet 2
With Sheets("Masterfile")
RowCount = 1
Do While .Range("A" & RowCount) <> ""
ID = Trim(.Range("A" & RowCount))
'compare - look for ID in Sheet 2
With Sheets("List")
Set c = .Columns("A").Find(what:=ID, _
LookIn:=xlValues, lookat:=xlWhole, MatchCase:=False)
End With
If c Is Nothing Then
.Range("B" & RowCount) = "No"
Else
.Range("B" & RowCount) = "Yes"
End If
RowCount = RowCount + 1
Loop
End With
ScreenUpdating = True
End Sub
The code you have looks overly complex.
For a non-vba solution, see below.
Sheet 1 formula:
=IF(ISERROR(VLOOKUP(A2,Sheet2!$A$2:$B$4,2,0)),"Removed",IF(VLOOKUP(A2,Sheet2!$A$2:$B$4,2,0)=B2,"Same","Changed to: " &VLOOKUP(A2,Sheet2!$A$2:$B$4,2,0)))
Sheet 2 formula:
=IF(ISERROR(VLOOKUP(A2,Sheet1!$A$2:$B$4,2,0)),"Added",IF(VLOOKUP(A2,Sheet1!$A$2:$B$4,2,0)=B2,"Same","Changed"))
I realize I may haved simplified things a bit, but you can adjust wording and whatever is needed. You can also apply conditional formatting as needed.
Struggling a bit with this code, I haven't ever had to reference one column and copy and paste to another tab in VBA so here goes..
I have an excel document with a table on it similar to below:
I need my code to look in column A find the first name, in this case, Nicola. I then want it to look at column B and check to see if she has the word "Internet" appear in any of the records stored against her, as she does the code will ignore her and move down to the next name on the list, in this case, Graham. It will then look to column B and check if he has the word "Internet". As he doesn't, the code needs to copy the Information from column A & B in relation to this persons name and paste the information into another sheet in the workbook.
Sub Test3()
Dim x As String
Dim found As Boolean
Range("B2").Select
x = "Internet"
found = False
Do Until IsEmpty(ActiveCell)
If ActiveCell.Value = x Then
found = True
Exit Do
End If
ActiveCell.Offset(1, 0).Select
Loop
If found = False Then
Sheets("Groupings").Activate
Sheets("Groupings").Range("A:B").Select
Selection.Copy
Sheets("Sheet1").Select
Sheets("Sheet1").Range("A:B").PasteSpecial
End If
End Sub
Any help would be greatly appreciated.
Thanks
Paula
Private Sub Test3()
Application.ScreenUpdating = False
Set sh1 = Sheets("Groupings") 'data sheet
Set sh2 = Sheets("Sheet1") 'paste sheet
myVar = sh1.Range("D1")
Lastrow = sh1.Range("B" & Rows.Count).End(xlUp).Row
For i = 2 To Lastrow '2 being the first row to test
If Len(sh1.Range("A" & i)) > 0 Then
Set myFind = Nothing
If WorksheetFunction.CountA(sh1.Range("A" & i, "A" & Lastrow)) > 1 Then
If Len(sh1.Range("A" & i + 1)) = 0 Then
nextrow = sh1.Range("A" & i).End(xlDown).Row - 1
Else
nextrow = nextrow + 1
End If
Set myFind = sh1.Range("B" & i, "B" & nextrow).Find(What:=myVar, LookIn:=xlFormulas, LookAt:=xlWhole)
Else
nextrow = Lastrow
Set myFind = sh1.Range("B" & i, "B" & nextrow).Find(What:=myVar, LookIn:=xlFormulas, LookAt:=xlWhole)
End If
If myFind Is Nothing Then
sh1.Range("A" & i, "B" & nextrow).Copy
sh2.Range("A" & sh2.Range("B" & Rows.Count).End(xlUp).Row + 1).PasteSpecial xlPasteValues
Application.CutCopyMode = False
End If
End If
Next
End Sub
I don't clearly see the structure of your data, but assuming the original data is in Worksheet Data, I think the following is going to do what you want (edited to search for two conditions).
Private Sub Test3()
Dim lLastRow as Long
Dim a as Integer
Dim i as Integer
Dim sText1 As String
Dim sText2 As String
sText1 = Worksheets("Data").Cells(1, 5).Value 'search text #1, typed in E1
sText2 = Worksheets("Data").Cells(2, 5).Value 'search text #2, typed in E2
lLastRow = Cells(Rows.Count, 1).End(xlUp).Row
a = 1
For i = 2 To lLastRow
If (Worksheets("Data").Cells(i, 1).Value <> "") Then
If (Worksheets("Data").Cells(i, 2).Value <> sText1 And Worksheets("Data").Cells(i + 1, 2).Value <> sText1 And Worksheets("Data").Cells(i, 2).Value <> sText2 And Worksheets("Data").Cells(i + 1, 2).Value <> sText2) Then
Worksheets("Groupings").Cells(a, 1).Value = Worksheets("Data").Cells(i, 1).Value
Worksheets("Groupings").Cells(a, 2).Value = Worksheets("Data").Cells(i, 2).Value
Worksheets("Groupings").Cells(a, 3).Value = Worksheets("Data").Cells(i + 1, 2).Value
a = a + 1
End If
End If
Next
End Sub
I have values in DEMAND row and values in the COLLECTION row, now I want BALANCE = DEMAND-COLLECTION, there are two times collection for an entry so according to the occurrence of collection the balance should arise. Can you please let me know the macro code for that.
I have DEMAND values D1:S1 COLLECTION values from D2:S2 and the balance should be there in the next row.
I came to this step after the solution I got from
Insert row base on specific text and its occurrence
I am using the following code
Sub try()
Dim c As Range
Dim lRow As Long
lRow = 1
Dim lRowLast As Long
Dim bFound As Boolean
With ActiveSheet
lRowLast = .Cells(.Rows.Count, 1).End(xlUp).Row
Do
Set c = .Range("A" & lRow)
If c.Value Like "*COLLECTION*" Then
bFound = True
ElseIf bFound Then
bFound = False
If c.Value <> "BALANCE" Then
c.EntireRow.Insert
lRowLast = lRowLast + 1
c.Offset(-1, 0).Value = "BALANCE"
c.Offset(-1, 0).Font.Color = RGB(0, 0, 0)
End If
End If
lRow = lRow + 1
Loop While lRow <= lRowLast + 1
End With
End Sub
before macro check IMAGE
After Macro I want this check image
So I would use SUMIF applied with FormulaR1C1 for that. The advantage is that we can set the formula in one step for the whole row.
Sub try()
Dim c As Range
Dim lRow As Long
lRow = 1
Dim lRowLast As Long
Dim lRowDiff As Long
Dim lRowPortion As Long
lRowPortion = 1
Dim bFoundCollection As Boolean
With ActiveSheet
lRowLast = .Cells(.Rows.Count, 1).End(xlUp).Row
Do
Set c = .Range("A" & lRow)
If c.Value Like "*COLLECTION*" Then
bFoundCollection = True
ElseIf bFoundCollection Then
bFoundCollection = False
If c.Value <> "BALANCE" Then
c.EntireRow.Insert
lRowLast = lRowLast + 1
Set c = c.Offset(-1, 0)
c.Value = "BALANCE"
End If
If c.Value = "BALANCE" Then
.Range(c, c.Offset(0, 18)).Font.Color = RGB(0, 0, 0)
.Range(c, c.Offset(0, 18)).Interior.Color = RGB(200, 200, 200)
lRowDiff = c.Row - lRowPortion
.Range(c.Offset(0, 3), c.Offset(0, 18)).FormulaR1C1 = _
"=SUMIF(R[-" & lRowDiff & "]C1:RC1, ""*DEMAND*"", R[-" & lRowDiff & "]C:RC)" & _
"-SUMIF(R[-" & lRowDiff & "]C1:RC1, ""*COLLECTION*"", R[-" & lRowDiff & "]C:RC)"
lRowPortion = c.Row + 1
End If
End If
lRow = lRow + 1
Loop While lRow <= lRowLast + 1
End With
End Sub