VBA check if columns are the same - vba

I have two Sheets in Excel that I need to check if the columns are the same in both sheets before processing them.
I have created a macro to do this check, but I'm wondering if there is a better way to achieve this.
Sub CheckColumns()
Sheets("Source1").Select
Range("A1").Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.Copy
Sheets("Sheet1").Select
Range("A1").Select
ActiveSheet.Paste
Sheets("Source2").Select
Range("A1").Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.Copy
Sheets("Sheet1").Select
Range("A2").Select
ActiveSheet.Paste
Range("A3") = "=IF(A1=A2,0,1)"
Range("A3").Copy
Range("A2").Select
Selection.End(xlToRight).Select
ActiveCell.Offset(1, 0).Range("A1").Select
Range(Selection, Selection.End(xlToLeft)).Select
ActiveSheet.Paste
Range("A4") = "=SUM(3:3)"
If Range("A4").Value = 0 Then
MsgBox "Same Columns"
Else
MsgBox "different Columns"
End If
End Sub

First of all you need to avoid selection; How to avoid using Select in Excel VBA macros
Specificaally about your code; I would try comparing two arrays as it always faster to work with arrays and also it doesn't need a dummy-sheet. However, your approach, except the selection part is faster in my mind. So I would include the explicit version of your approach shortly.
Sub CheckColumns()
Dim arrS1 As Variant, arrS2 As Variant
Dim LastRow As Long
With Worksheets("Source1")
LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
arrS1 = .Range("A1:A" & LastRow)
End With
With Worksheets("Source2")
LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
arrS2 = .Range("A1:A" & LastRow)
End With
If UBound(arrS1) <> UBound(arrS2) Then
MsgBox "Different Columns"
Exit Sub
End If
same = True
For i = LBound(arrS1) to UBound(arrS1)
If arrS1(i) <> arrS1(i) Then
same = False
Exit For
End If
Next i
If same = True Then
MsgBox "Same Column"
Else
MsgBox "Item " & i & " does not match. Stopped checking further"
End If
End Sub
This is the explicit version of your method:
Sub CheckColumns()
Dim rngrS1 As Range, rngS2 As Range, rngSH As Range
Dim LastRow1 As Long, LastRow2 As Long
With Worksheets("Source1")
LastRow1 = .Cells(.Rows.Count, "A").End(xlUp).Row
Set rngS1 = .Range("A1:A" & LastRow)
End With
With Worksheets("Source2")
LastRow2 = .Cells(.Rows.Count, "A").End(xlUp).Row
Set rngS2 = .Range("A1:A" & LastRow)
End With
If LastRow1 <> LastRow2 Or rngS1(1) <> rngS2(1) Then
'Second condition checks names of the columns
MsgBox "Different Columns"
Exit Sub
End If
With Worksheets("Sheet1")
Set rngSH = .Range("A1:A" & LastRow1)
End With
rngSH.Value = rngS1.Value
Set rngSH = rngSH.Offset(0,1)
rngSH.Value = rngS2.Value
Set rngSH = rngSH.Offset(0,1)
rngSH.formula "=IF(A1=B1,0,1)"
Worksheets(Sheet1).Range("D2") = "Sum(C:C)"
If Worksheets(Sheet1).Range("D2").Value <> 0 Then
MsgBox "Different Columns"
Else
MsgBox "Same Columns"
End If
End Sub

You could declare two arrays and compare that way...
Sub Compare()
Dim FirstSheet As Variant, SecondSheet As Variant
Dim a As Long, b As Long
FirstSheet = Sheets("Source1").Range("A1:" & _
Mid(Sheets("Source1").Range("A1").End(xlToRight).Address, 2, _
InStr(Right(Sheets("Source1").Range("A1").End(xlToRight).Address, _
Len(Sheets("Source1").Range("A1").End(xlToRight).Address) - 2), "$")) & 1)
SecondSheet = Sheets("Source2").Range("A1:" & _
Mid(Sheets("Source2").Range("A1").End(xlToRight).Address, 2, _
InStr(Right(Sheets("Source2").Range("A1").End(xlToRight).Address, _
Len(Sheets("Source2").Range("A1").End(xlToRight).Address) - 2), "$")) & 1)
On Error Resume Next
For a = 1 To WorksheetFunction.Max(Sheets("Source1").Range("A1:" & _
Mid(Sheets("Source1").Range("A1").End(xlToRight).Address, 2, _
InStr(Right(Sheets("Source1").Range("A1").End(xlToRight).Address, _
Len(Sheets("Source1").Range("A1").End(xlToRight).Address) - 2), "$")) & 1).Cells.Count, _
Sheets("Source1").Range("A1:" & Mid(Sheets("Source1").Range("A1").End(xlToRight).Address, 2, _
InStr(Right(Sheets("Source1").Range("A1").End(xlToRight).Address, _
Len(Sheets("Source1").Range("A1").End(xlToRight).Address) - 2), "$")) & 1))
If FirstSheet(1, a) <> SecondSheet(1, a) Then b = b + 1
Next
On Error GoTo 0
If b = 0 Then
MsgBox "Same Columns"
Else
MsgBox "different Columns"
End If
End Sub

Related

Vba deleting all data

I am new to vba and have written some code to delete specific data and refresh 2 pivot tables. It works fine when I step through each sub but when I add the module to a button so everything is run with the press of the button all the data is deleted.
Below is the code I have written( might be a bit cumbersome but I am still learning). I Hope someone can help me.
Sub Deleteheader()
ActiveWindow.FreezePanes = False
Rows("1:4").Select
Selection.Delete Shift:=xlUp
End Sub
Sub DeleteColumns()
Dim wsAvlRpt As Worksheet, wsSetUp As Worksheet
Set wsAvlRpt = ActiveWorkbook.Worksheets("AvlRpt")
Set wsSetUp = ActiveWorkbook.Worksheets("SetUp")
ColTotal = wsAvlRpt.UsedRange.Column + wsAvlRpt.UsedRange.Columns.Count - 1
LastCol = Split(Cells(1, ColTotal).Address, "$")(1)
For i = 1 To ColTotal
ColumnName = wsAvlRpt.Cells(1, i)
Values = wsSetUp.Range("A" & Rows.Count).End(xlUp).Row
cntColName = Application.CountIf(wsSetUp.Range("A2:A" & Values), ColumnName)
If cntColName = 0 Then
wsAvlRpt.Columns(i).EntireColumn.Delete
i = i - 1
ColTotal = ColTotal - 1
End If
If ColTotal <= i Then
Exit For
End If
Next i
wsAvlRpt.Columns(7).EntireColumn.Insert
wsAvlRpt.Range("G1").Value = "Item Desc"
Columns("G:G").Select
Selection.NumberFormat = "General"
End Sub
Public Sub DeleteStatus()
Dim wsAvlRpt As Worksheet
Dim lngLastRow As Long
Dim rngAvl As Range
Set wsAvlRpt = ThisWorkbook.Worksheets("AvlRpt")
With wsAvlRpt
lngLastRow = .Range("C" & .Rows.Count).End(xlUp).Row
Set rngAvl = .Range("A2:J" & lngLastRow)
End With
Application.DisplayAlerts = False
With rngAvl
.AutoFilter field:=8, _
Criteria1:="Ongoing", _
Operator:=xlOr, _
Criteria2:="P.Label"
.Offset(0).Resize(.Rows.Count).SpecialCells(xlCellTypeVisible).Rows.Delete
End With
Application.DisplayAlerts = True
With wsAvlRpt
.AutoFilterMode = False
If .FilterMode = True Then
.ShowAllData
End If
End With
End Sub
Sub DeleteZeroInventory()
Dim wsAvlRpt As Worksheet, wsSetUp As Worksheet
Set wsAvlRpt = ActiveWorkbook.Worksheets("AvlRpt")
Set wsSetUp = ActiveWorkbook.Worksheets("SetUp")
cntZeroInventory = Application.CountIf(wsAvlRpt.Range("I:I"), "<=0.0")
If cntZeroInventory > 0 Then
Total = wsAvlRpt.Cells(Rows.Count, "A").End(xlUp).Row
wsAvlRpt.Range("$A1:J" & Total).AutoFilter field:=9, Criteria1:="<=0.0", _
Operator:=xlFilterValues
wsAvlRpt.Range("A2:J" & Total).Select
Selection.SpecialCells(xlCellTypeVisible).EntireRow.Delete
wsAvlRpt.ShowAllData
wsAvlRpt.Columns(10).EntireColumn.Insert
wsAvlRpt.Range("J1").Value = "Available Eaches"
End If
End Sub
Sub CalcEaches()
Dim LastRow As Long
Sheets("AvlRpt").Activate
LastRow = Range("I65536").End(xlUp).Row
Range("I2:I" & LastRow).Select
Selection.Offset(0, 1).Select
Selection.FormulaR1C1 = "= RC[-1] *12"
Selection = Selection.Value
End Sub
Sub AddItemDesc()
With Sheets("AvlRpt")
.Range("G2:G" & .Range("C" & Rows.Count).End(xlUp).Row).Formula = _
"=IF(ISERROR(VLOOKUP(C2,SetUp!I:J,2,FALSE)),0,VLOOKUP(C2,SetUp!I:J,2,FALSE))"
.Range("G2:G" & .Range("A" & Rows.Count).End(xlUp).Row).Value = _
.Range("G2:G" & .Range("A" & Rows.Count).End(xlUp).Row).Value
End With
End Sub
Sub DeleteStyles()
Dim wsAvlRpt As Worksheet, wsSetUp As Worksheet
Set wsAvlRpt = ActiveWorkbook.Worksheets("AvlRpt")
Dim AvlRpt As Range
Set AvlRpt = wsAvlRpt.Range("A1", Range("A1").End(xlDown).End(xlToRight))
AvlRpt.AutoFilter field:=3, Criteria1:=Array("7A37", "8A37", "CO07", "CO81"), _
Operator:=xlFilterValues
AvlRpt.CurrentRegion.Offset(1, 0).Select
With Selection
.SpecialCells(xlCellTypeVisible).EntireRow.Delete
If wsAvlRpt.FilterMode Then
wsAvlRpt.ShowAllData
End If
End With
End Sub
Sub ClearContents()
Worksheets("CloseoutData").Range("A2:J2000").Clear
End Sub
Sub CopyDeleteAvlRpt()
Application.DisplayAlerts = False
Sheets("AvlRpt").Range("A2:J2000").Copy _
Destination:=Sheets("CloseoutData").Range("A2:J2000")
Sheets("AvlRpt").Delete
Application.DisplayAlerts = True
End Sub
Sub RefreshPivots()
ThisWorkbook.RefreshAll
End Sub
Sub PivotCopyAdults()
Dim pt As PivotTable, lRow As Long
Dim oWS_Copy As Worksheet, oWS_Paste As Worksheet
Set oWS_Copy = Sheets("Adults")
Set oWS_Paste = Sheets.Add
ActiveSheet.Name = "CloseOuts Adults"
For Each pt In oWS_Copy.PivotTables
pt.TableRange2.Copy
lRow = oWS_Paste.Cells(Rows.Count, 1).End(xlUp).Row + 1
oWS_Paste.Range("A" & lRow).PasteSpecial Paste:=xlPasteValues
oWS_Paste.Range("A" & lRow).PasteSpecial Paste:=xlPasteFormats
Next pt
oWS_Paste.Cells.Columns.AutoFit
End Sub
Sub PivotCopyYouthLadies()
Dim pt As PivotTable, lRow As Long
Dim oWS_Copy As Worksheet, oWS_Paste As Worksheet
Set oWS_Copy = Sheets("Youth&Ladies")
Set oWS_Paste = Sheets.Add
ActiveSheet.Name = "CloseOuts Youth & Ladies"
For Each pt In oWS_Copy.PivotTables
pt.TableRange2.Copy
lRow = oWS_Paste.Cells(Rows.Count, 1).End(xlUp).Row + 1
oWS_Paste.Range("A" & lRow).PasteSpecial Paste:=xlPasteValues
oWS_Paste.Range("A" & lRow).PasteSpecial Paste:=xlPasteFormats
Next pt
oWS_Paste.Cells.Columns.AutoFit
End Sub

VBA: Looking for a value and copy and paste the value in a other sheet

I have a problem with my VBA code. The problem is that I have duplicate names - the main sheet "Manager" and the names of the sheets.
The code should go to every sheet and look for the value "Engagements ID" and then go one cell down. In every sheet the number of Engagements ID is different, so the code should search in every sheet (500 rows) - look for the value "Engagements ID" then copy and paste the cell what is one row below into my main sheet, which is called "Manager".
Thank you for help!! :) The value what I looking for is on every sheet in column B.
This is my code:
Option Explicit
Sub Check_Account()
Dim rng As Range
Dim xName As String
Dim i, j As Integer
For i = 3 To 6
xName = Cells(i, 1)
If xName = "" Then Exit Sub
On Error Resume Next
ActiveWorkbook.Sheets(xName).Select
Sheets(xName).Select
For j = 1 To 500
If rng.Cells(j, 2) = "Engagements ID" Then
rng.Offset(1, 0).Select
Selection.Copy
Sheets("Manager").Select
If Range("B" & i) = "" Then
Range("B" & i).Select
Selection.PasteSpecial Paste:=xlPasteValues,
Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
ActiveWorkbook.Sheets(xName).Select
Sheets(xName).Select
Cells(j, 2).Offset(1, 0).Select
Else
Range("B" & i).Offset(1, 0).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
ActiveWorkbook.Sheets(xName).Select
Sheets(xName).Select
Cells(j, 2).Offset(1, 0).Select
End If
End If
Next j
On Error GoTo 0
Next i
End Sub
Please try this code. I think you will like it.
Option Explicit
Sub Check_Account()
' 24 Nov 2017
Dim TabName As String
Dim Rng As Range
Dim Fnd As Range
Dim Rl As Long ' last row
Dim FirstFnd As Long
Dim i As Integer
For i = 3 To 6
' Tab names are found at Manager!A3:A6
TabName = Worksheets("Manager").Cells(i, "A").Value
If Len(TabName) = 0 Then Exit For
On Error Resume Next
With Worksheets(TabName)
If Err Then
MsgBox "Worksheet """ & TabName & """ doesn't exist.", _
vbInformation, "Missing Worksheet"
Else
Rl = .Cells(.Rows.Count, "B").End(xlUp).Row
Set Rng = Range(.Cells(1, "B"), .Cells(Rl, "B"))
Set Fnd = Rng.Find("Engagements ID", _
After:=Rng.Cells(Rng.Cells.Count), _
LookIn:=xlValues, _
LookAt:=xlPart, _
SearchOrder:=xlByColumns, _
SearchDirection:=xlNext, _
MatchCase:=False, _
MatchByte:=False)
If Not Fnd Is Nothing Then
FirstFnd = Fnd.Row
Do
With Worksheets("Manager")
Rl = .Cells(.Rows.Count, "B").End(xlUp).Row + 1
' start writing in row 2
If Rl < 2 Then Rl = 2
.Cells(Rl, "B").Value = Fnd.Offset(1).Value
End With
Set Fnd = Rng.FindNext(Fnd)
Loop While Not Fnd Is Nothing And Fnd.Row <> FirstFnd
End If
End If
End With
Next i
End Sub
I have tried and tested the code below, and I believe it does what you expected it to do:
Sub foo()
For i = 3 To 6
xName = Sheets("Manager").Cells(i, 1).Value
LastRow = Sheets(xName).Cells(Sheets(xName).Rows.Count, "B").End(xlUp).Row
For x = 1 To LastRow
If Sheets(xName).Cells(x, 2).Value = "Engagements ID" Then
Sheets("Manager").Cells(i, 2).Value = Sheets(xName).Cells(x + 1, 2).Value
End If
Next x
Next i
End Sub
This does not have any validation against possible errors, if the manager sheet does not exist, then you will get an error... But at least the code is more concise and it points you in the right direction.

VBA If with two criteria in two columns

I need to look at two cells (C and F) on a each row, and if the value for C to ends with 30 and the value for F is greater than Zero, copy and paste the row to another sheet. I've managed to get the copy and paste to work using 1 criteria, but I cannot figure out how to get both criteria to work together.
Sub compile1()
Dim x As String
Set rSearch = Sheets("Application").Range("C:C")
For Each cell In rSearch
x = cell.Value
If Right(cell, 2) = "30" And cell.Offset(, 3) > 0 Then
matchRow = cell.Row
Rows(matchRow & ":" & matchRow).Select
Selection.Copy
Sheets("sheet2").Select
ActiveSheet.Rows(matchRow).Select
ActiveSheet.Paste
Sheets("Application").Select
End If
Next
End Sub
Here you go:
Sub CP()
Dim i As Long
Dim n As Long
n = Sheets("Application").Cells(Rows.Count, 3).End(xlUp).Row
For i = 1 To n
With Sheets("Application")
If Right(Cells(i, 3), 2) = 30 And Cells(i, 6).Value > 0 Then
.Cells(i, 3).EntireRow.Copy Destination:=Sheets("Sheet3").Cells(i, 3)
.Cells(i, 6).EntireRow.Copy Destination:=Sheets("Sheet3").Cells(i, 6)
End If
End With
Next i
End Sub
I have used column 3 to count the number of rows and hence assumed this is the main column
You were missing the Next statement in your second for each loop.
The two criterias can be taken together with this line:
If y > 0 And Right(x, 2) = "30" Then
so the whole code would be...
Sub compile1()
Dim x As String
Dim y As Integer
Dim rSearch As Range
Dim rSearch1 As Range
Dim cell As Range, cell1 As Range
Dim matchRow As Integer
Set rSearch = Sheets("Application").Range("C:c")
Set rSearch1 = Sheets("Application").Range("F:F")
For Each cell In rSearch
x = cell.Value
For Each cell1 In rSearch1
y = cell1.Value
If y > 0 And Right(x, 2) = "30" Then
matchRow = cell.Row
Rows(matchRow & ":" & matchRow).Select
Selection.Copy
Sheets("sheet2").Select
ActiveSheet.Rows(matchRow).Select
ActiveSheet.Paste
Sheets("Application").Select
End If
Next cell1
Next cell
End Sub
To speed things up I'd suggest the following:
Sub Copy_Paste()
Dim x As String
Dim y As Integer
Dim WS1 As Worksheet
Set WS1 = ActiveSheet
y = 1
Do Until y > WorksheetFunction.Max(Range("C1048576").End(xlUp).Row, Range("F1048576").End(xlUp).Row)
x = Trim(Cells(y, 3).Value)
If Right(x, 2) = "30" And (IsNumeric(Cells(y, 6).Value) And Cells(y, 6).Value > 0) Then Rows(y & ":" & y).Copy: Sheets("Sheet2").Range("A" & Sheets("Sheet2").Range("C1048576").End(xlUp).Row + 1).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False: Application.CutCopyMode = False
y = y + 1
Loop
Sheets("Sheet2").Activate
Range("A1").Activate
WS1.Activate
End Sub
Try this code once - this is way too simpler and optimized processing than loops (slower)
Application.ScreenUpdating = False
Application.EnableEvents = False
Sheets("Application").AutoFilterMode = False
Dim lastrow, lastcol As Integer
lastrow = Range("F500000").End(xlUp).Row
lastcol = Sheets("Application").Range("A1").End(xlToRight).Column + 1
Sheets("Application").Cells(1, lastcol).Value = "helper"
Sheets("Application").Range(Sheets("Application").Cells(1, lastcol),Sheets("Application").Cells(lastrow, lastcol)).FormulaR1C1 = "=Right(RC[-1],2)"
Sheets("Application").Range(Range("A1"), Range("A1").End(xlToRight)).AutoFilter Field:=lastcol, Criteria1:="30"
Sheets("Application").Range(Range("A1"), Range("A1").End(xlToRight)).AutoFilter Field:=3, Criteria1:=">0"
Sheets("Application").Range(Cells(1, 1), Cells(lastrow, lastcol)).SpecialCells(xlCellTypeVisible).Copy Destination:=Sheet2.Range("A2")
Columns(lastcol).Delete
Application.ScreenUpdating = True
Application.EnableEvents = True
Here is the entire code. It works but takes ages to run. Any help to speed it up would be appreciated.
Sub Master()
Call compile1
Call compile2
End Sub
Sub compile1()
For Each cell In Sheets("Application").Range("C:C")
If Right(cell.Value, 2) = "10" Then
matchRow = cell.Row
Rows(matchRow & ":" & matchRow).Select
Selection.Copy
Sheets("Routine w credits").Select
ActiveSheet.Rows(matchRow).Select
ActiveSheet.Paste
Sheets("Application").Select
End If
Next
For Each cell In Sheets("Application").Range("C:C")
If Right(cell.Value, 2) = "20" Then
matchRow = cell.Row
Rows(matchRow & ":" & matchRow).Select
Selection.Copy
Sheets("Reactive w credits").Select
ActiveSheet.Rows(matchRow).Select
ActiveSheet.Paste
Sheets("Application").Select
End If
Next
End Sub
Sub compile2()
Set rSearch = Sheets("Application").Range("C:C")
For Each cell In rSearch
If Right(cell, 2) = "20" And cell.Offset(, 3) > 0 Then
matchRow = cell.Row
Rows(matchRow & ":" & matchRow).Select
Selection.Copy
Sheets("Reactive wo credits").Select
ActiveSheet.Rows(matchRow).Select
ActiveSheet.Paste
Sheets("Application").Select
End If
Next
For Each cell In rSearch
If Right(cell, 2) = "10" And cell.Offset(, 3) > 0 Then
matchRow = cell.Row
Rows(matchRow & ":" & matchRow).Select
Selection.Copy
Sheets("Routine wo credits").Select
ActiveSheet.Rows(matchRow).Select
ActiveSheet.Paste
Sheets("Application").Select
End If
Next
End Sub
Sub compile1()
Dim Cel As Range, Rng As Range
Set rSearch = Sheets("Application").Columns("C:C").SpecialCells(xlCellTypeConstants, 23)
For Each Cel In rSearch
If Right(Trim(Cel.Value), 2) = "30" And (Cel.Offset(, 3).Value > 0) Then
Cel.EntireRow.Copy
Sheets("Sheet2").Range("A" & Sheets("Sheet2").Range("C1048576").End(xlUp).Row + 1).Paste
Application.CutCopyMode = False
End If
Next
End Sub

How can I find data in sheet using VBA?

So I have workbook with sheets named Contacts and Help. In Help sheet I have Button which shows inputbox and asks "What client you would like to find?"
When I input name like Samuel Smith. I would like that VBA would go to Contacts sheet and find me Samuel Smith and offset to one column right and copy the Firm where Samuel Smith works. Then paste it to Help sheet and find next Samuel Smith. I would love to do this even if there were 50 Samuel Smith's in Contacts! Just don't know how to do this so any help is much appreciated!
Thank you all for your answers in advance.
Below are my custom function, that can find and return the result in Array.
From the find result you should able to solve your problem.
Hope this help !
Sub test()
'The result will be on Column C, because offset = 1
Dim nItem, Found As Variant
Found = iFind("Concatenate", Columns(2), 1)
For Each nItem In Found
MsgBox nItem
Next
End Sub
Function iFind(ByVal findText As String, ByVal nColumn As Range, ByVal offsetColumn As Single, _
Optional ByVal startRow As Single = 1, Optional ByVal caseSensitive As Boolean = False) As Variant
'Return Array of Range
'nColumn - Column to find
'offsetColumn - offset column to return
Dim WBD As Workbook
Dim WSD As Worksheet
Dim lastRow, tCount, nCount, nRow, nCol, N As Single
Dim nColRng, dataRng As Range
Dim compare As VbCompareMethod
Dim nArray As Variant
ReDim nArray(0)
Set WSD = nColumn.Parent
'Ensure only on column selected to consider lastRow
Set nColRng = nColumn.Columns(1)
nCol = nColRng.Column
'Get the lastRow
On Error Resume Next
lastRow = startRow
lastRow = nColRng.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
If lastRow < startRow Then lastRow = startRow
On Error GoTo 0
Set dataRng = Intersect(WSD.Range(WSD.Rows(startRow), WSD.Rows(lastRow)), nColRng)
tCount = Excel.Application.WorksheetFunction.CountIfs(dataRng, findText)
If tCount > 0 Then
nCount = 0
N = 0
Do While nCount < tCount
nRow = Excel.Application.Match(findText, dataRng, 0) + dataRng(1).Row - 1
If caseSensitive = True Then
compare = vbBinaryCompare
Else
compare = vbTextCompare
End If
'Add into array, only if matching case
If InStr(1, findText, WSD.Cells(nRow, nCol), compare) Then
ReDim Preserve nArray(N)
nArray(N) = WSD.Cells(nRow, nCol + offsetColumn)
N = N + 1
End If
nCount = nCount + 1
'Resize dataRng
Set dataRng = Intersect(WSD.Range(WSD.Rows(nRow + 1), WSD.Rows(lastRow)), nColRng)
Loop
End If
iFind = nArray
End Function
I worked on this hole night and now I know how to do this!
Option Explicit
'''''''
Dim Find_Inp As String
Dim Find As Variant
Dim Error_ As Integer
'''''''
Sub Test2()
On Error Resume Next
Sheet1.Select
Range("A8:G100").ClearContents
Find_Inp = InputBox("Please input Account!")
If Find_Inp = "" Then
Exit Sub
End If
MsgBox "This will take some time please wait."
Sheet2.Select
Call Macro1 'Sort macro
Call Find_Full
Exit Sub
End Sub
Function
Private Function Find_Full()
On Error GoTo ErrorHandler
'''''''
Dim Account_Column As Variant
Dim Result As Range, Result2 As Range
Dim LastAccount As Long
Dim NextAccount As Long
Dim Find_repeat As Integer
'''''''
Sheets("Contacts").Select
Account_Column = Range("G1").Select
Find = Cells.Find(What:=Find_Inp, After:=ActiveCell, LookIn:=xlValues, LookAt:= _
xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False _
, SearchFormat:=False).Activate
Find_repeat:
If Find = True Then
Set Result = ActiveCell
LastAccount = Sheet1.Cells(Rows.Count, 3).End(xlUp).Row
NextAccount = LastAccount + 1
Result.Copy 'Where the name
Sheet1.Select
Range("C" & NextAccount).PasteSpecial xlPasteValuesAndNumberFormats
Result.Offset(0, -2).Copy 'Where the firm name is
Sheet1.Select
Range("C" & NextAccount).Offset(0, 1).PasteSpecial xlPasteValuesAndNumberFormats
Sheet2.Select
Result.Offset(0, -1).Copy 'Where the email is
Sheet1.Select
Range("C" & NextAccount).Offset(0, 2).PasteSpecial xlPasteValuesAndNumberFormats
Sheet2.Select
Result.Offset(0, 9).Copy 'Where the phone number
Sheet1.Select
Range("C" & NextAccount).Offset(0, -2).PasteSpecial xlPasteValuesAndNumberFormats
Sheet2.Select
Result.Offset(0, 10).Copy 'Where the work number is
Sheet1.Select
Range("C" & NextAccount).Offset(0, -1).PasteSpecial xlPasteValuesAndNumberFormats
Sheet2.Select
Result.Offset(0, 4).Copy 'Where the firm addres is
Sheet1.Select
Range("C" & NextAccount).Offset(0, 3).PasteSpecial xlPasteValuesAndNumberFormats
Sheet2.Select
Result.Offset(0, 5).Copy 'Where the title is
Sheet1.Select
Range("C" & NextAccount).Offset(0, 4).PasteSpecial xlPasteValuesAndNumberFormats
Error_ = 0
End If
Sheet2.Select
Result.Offset(1, 0).Select
Set Result2 = ActiveCell
If Result2 = Find_Inp Then
GoTo Find_repeat
Else
Sheet1.Select
Range("A1").Select
End If
ErrorHandler:
If Error_ = 1 Then
Sheet1.Select
Range("A1").Select
MsgBox "Account was not found! Try again."
End If
Error_ = 1
End Function
Sort Macro
Private Sub Macro1()
'
' Macro1 Macro
'
'
Dim Lastrow As Long
Lastrow = Sheet2.Cells(Rows.Count, 7).End(xlUp).Row
Application.CutCopyMode = False
ActiveWorkbook.Worksheets("Contacts").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Contacts").Sort.SortFields.Add Key:=Range("G1"), _
SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Contacts").Sort
.SetRange Range("A2:AJ2106")
.Header = xlNo
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
Range("A1").Select
End Sub

VBA Excel AutoFilter Error

I am getting following error when trying to auto filter in vba:
The object invoked has disconnected from its clients.
So what i am trying to do is auto filter, search for empty spaces and delete the rows. Can anyone please help?
I have tried the standard solutions provided online e.g. option explicit etc but to no avail.
Data:
Code:
Private Sub Worksheet_Change(ByVal Target As Range)
Dim lngLastRow As Long
Dim lngLastRowD As Long
Application.ScreenUpdating = False
'Concatenate the Row A and B
lngLastRow = Cells(Rows.Count, "A").End(xlUp).Row
Worksheets(1).Range("D2:D" & lngLastRow).Value = Evaluate("=A2:A" & lngLastRow & "&""""&" & "B2:B" & lngLastRow)
lngLastRowD = Worksheets(1).Cells(Rows.Count, "D").End(xlUp).Row
Set ws = Worksheets(1)
Set Rng = Worksheets(1).Range("A2:A" & lngLastRowD)
With Rng
.AutoFilter field:=1, Criteria1:=""
.Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow.Delete
End With
ws.AutoFilterMode = False
Application.ScreenUpdating = True
ThisWorkbook.Sheets(1).Range("A2").Select
End Sub
Since Worksheets() want the name of the sheet, like "Sheet1", use sheets(1).
Why are you creating the variable ws and rng when you only use them once
I ran this and it deleted rows with no data in column A.
Private Sub Worksheet_Change()
Dim lngLastRow As Long
Dim lngLastRowD As Long
Application.ScreenUpdating = False
'Concatenate the Row A and B
lngLastRow = Cells(Rows.Count, "A").End(xlUp).Row
sheets(1).Range("D2:D" & lngLastRow).Value = Evaluate("=A2:A" & lngLastRow & "&""""&" & "B2:B" & lngLastRow)
lngLastRowD = Worksheets(1).Cells(Rows.Count, "D").End(xlUp).Row
With sheets(1).Range("A2:A" & lngLastRowD)
.AutoFilter field:=1, Criteria1:=""
.Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow.Delete
End With
sheets(1).AutoFilterMode = False
Application.ScreenUpdating = True
Sheets(1).Range("A2").Select
End Sub
In the end i restored in approaching the issue from another angle:
Dim i As Integer, counter As Integer
i = 2
For counter = 1 To lngLastRowD
If Worksheets(1).Range("A2:A" & lngLastRowD).Cells(i) = "" And Worksheets(1).Range("D2:D" & lngLastRowD).Cells(i) <> "" Then
Worksheets(1).Range("A2:A" & lngLastRowD).Range("A" & i & ":D" & lngLastRowD).Select
Selection.Delete
GoTo TheEND
Else
i = i + 1
Debug.Print "i is " & i
End If
Next