How to split and restructure cells using excel VBA - vba

The code I currently use splits:
And changes it to:
However, this is the format in which I require the data to be in:
This is a copy of my current code:
Sub SplitCells()
Dim rColumn As Range
Dim lFirstRow As Long
Dim lLastRow As Long
Dim lRow As Long
Dim lLFs As Long
Set rColumn = Columns("D")
lFirstRow = 1
lLastRow = rColumn.Cells(Rows.Count).End(xlUp).Row
For lRow = lLastRow To lFirstRow Step -1
lLFs = Len(rColumn.Cells(lRow)) - Len(Replace(rColumn.Cells(lRow), vbLf, ""))
If lLFs > 0 Then
rColumn.Cells(lRow + 1).Resize(lLFs).EntireRow.Insert xlShiftDown
rColumn.Cells(lRow).Resize(lLFs + 1).Value = Application.Transpose(Split(rColumn.Cells(lRow), vbLf))
End If
Next lRow
End Sub
Any help/comments will be appreciated.

call ResizeToFit macro at the end of your code
Add ResizeToFit right before End Sub in your current code
ie.
...
Next lRow
ResizeToFit ' or Call ResizeToFit
End Sub
...
add this code to the same module as a new sub
Sub ResizeToFit()
Application.ScreenUpdating = False
Dim i As Long
For i = Range("D" & Rows.Count).End(xlUp).Row To 1 Step -1
If IsEmpty(Range("D" & i)) Then
Rows(i & ":" & i).Delete
Else
Range("E" & i) = Split(Range("D" & i), Chr(32))(1)
Range("D" & i) = Split(Range("D" & i), Chr(32))(0)
End If
Next i
For i = 1 To 5
If i <> 4 Then
Cells(1, i).Resize(Range("D" & Rows.Count).End(xlUp).Row, 1).Value = Cells(1, i)
End If
Next
Application.ScreenUpdating = True
End Sub
Taking THIS
and running my code produces

Sub SplitCells()
Dim rColumn As Range
Dim lFirstRow As Long
Dim lLastRow As Long
Dim lRow As Long
Dim lLFs As Long
Set rColumn = Columns("D")
lFirstRow = 1
lLastRow = rColumn.Cells(Rows.Count).End(xlUp).Row
For lRow = lLastRow To lFirstRow Step -1
lLFs = Len(rColumn.Cells(lRow)) - Len(Replace(rColumn.Cells(lRow), vbLf, ""))
If lLFs > 0 Then
rColumn.Cells(lRow + 1).Resize(lLFs).EntireRow.Insert xlShiftDown
rColumn.Cells(lRow).Resize(lLFs + 1).Value = Application.Transpose(Split(rColumn.Cells(lRow), vbLf))
End If
Dim curRow As Integer
curRow = lRow + lLFs
While curRow >= lRow
If Application.CountA(Rows(curRow).EntireRow) = 0 Then
Rows(curRow).Delete
Else
rColumn.Cells(curRow).Offset(0, 1).Value = Split(rColumn.Cells(curRow), " ")(1)
rColumn.Cells(curRow).Value = Split(rColumn.Cells(curRow), " ")(0)
rColumn.Cells(curRow).Offset(0, -3).Value = rColumn.Cells(lRow).Offset(0, -3).Value
rColumn.Cells(curRow).Offset(0, -2).Value = rColumn.Cells(lRow).Offset(0, -2).Value
rColumn.Cells(curRow).Offset(0, -1).Value = rColumn.Cells(lRow).Offset(0, -1).Value
End If
curRow = curRow - 1
Wend
Next lRow
End Sub

This is just from a recorded macro so it needs cleaning up.
ActiveCell.FormulaR1C1 = "=LEFT(RC[-1],LEN(RC[-1])-5)"
Range("E1:E4").Select
Selection.FillDown
Range("F1").Select
ActiveCell.FormulaR1C1 = "=RIGHT(RC[-2],4)"
Range("F1:F4").Select
Selection.FillDown
Range("E1:F4").Select
Selection.Copy
Range("E1").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Columns("D:D").Select
Application.CutCopyMode = False
Selection.Delete Shift:=xlToLeft
You may not need the cut, paste and column delete if you're happy with Column D staying as it is and having the split parts to the right. In which case
ActiveCell.FormulaR1C1 = "=LEFT(RC[-1],LEN(RC[-1])-5)"
Range("E1:E4").Select
Selection.FillDown
Range("F1").Select
ActiveCell.FormulaR1C1 = "=RIGHT(RC[-2],4)"
Range("F1:F4").Select
Selection.FillDown
Sorry - ActiveCell is E1.

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

deleting rows with blank cells and criteria VBA

I have columns from A - S, where I need to delete the headers and blank cells, my criteria for lookup in deleting headers are "Transaction" & "Source" but it seems it's skipping rows. I have a total of 79,000 rows but code only goes till 39,000. I've tried everything I can find over. still nothing happens.
I'm also starting the formatting and deleting on row 209 up to lastrow.
Option Explicit
Sub Project_M()
Dim lastrow As Long
Dim cc As Long
Dim dd As Long
lastrow = WorksheetFunction.CountA(Columns(1))
Application.ScreenUpdating = False
Call ClearFormats
lastrow = WorksheetFunction.CountA(Columns(1))
Columns(1).Insert shift:=xlToRight
Range("A209:A" & lastrow).Formula = "=ROW()" 'inserting dummy rows
Range("A209:A" & lastrow).Value = Range("A210:A" & lastrow).Value
Range("U209:U" & lastrow).Formula = "=IF(AND(ISERROR(SEARCH(""Transaction"",B209)),ISERROR(SEARCH(""Source"", B209))),1,0)"
Range("U209:U" & lastrow).Value = Range("U209:U" & lastrow).Value
''''' delete headers : only working till row 39,0000
Range("A209:U" & lastrow).Sort Key1:=Range("U209"), Order1:=xlAscending
cc = WorksheetFunction.CountIf(Columns(21), "0")
If cc <> 0 Then
Range("A209:U" & cc).Select
Range("A209:U" & cc).EntireRow.Delete
lastrow = lastrow - cc
End If
Range("A209:U" & lastrow).Sort Key1:=Range("A209"), Order1:=xlAscending
Range("U:U").ClearContents
Range("A:A").Delete
ActiveSheet.UsedRange.Columns.AutoFit
End Sub
Sub deleteBlank() 'not working
Dim lastrow As Integer
lastrow = Range("A" & rows.Count).End(xlUp).Row
Range("B2:B" & lastrow).SpecialCells(xlCellTypeBlanks).EntireRow.Delete
End Sub
Sub ClearFormats() ' working
Dim rng As Range
Dim lastrow As Long
Dim ws As Worksheet
lastrow = Range("A" & rows.Count).End(xlUp).Row
Application.ScreenUpdating = False
On Error Resume Next
Set rng = Range("A209:S" & lastrow).SpecialCells(xlCellTypeBlanks)
On Error GoTo 0
If Not rng Is Nothing Then
rng.ClearFormats
End If
On Error Resume Next 'not working in deleting blank cells
ws.Columns("A209:S" & lastrow).SpecialCells(xlCellTypeBlanks).EntireRow.Delete
On Error GoTo 0
End Sub
Sub DeleteExtra() ' not working
Dim Last As Long
Dim i As Long
Last = Cells(rows.Count, "A").End(xlUp).Row
For i = Last To 1 Step 1
If (Cells(i, "A209").Value) = "Transaction" And (Cells(i, "A209").Value) = "Source" And (Cells(i, "A209").Value) = "" And (Cells(i, "A209").Value) = " " Then
Cells(i, "A").EntireRow.Delete
End If
Next i
End Sub
Sub deleteBlankcells() '''not working
Dim lastrow As Long
Dim cc As Long
lastrow = WorksheetFunction.CountA(Columns(1))
Range("A209:A" & lastrow).Formula = "=ROW()" 'inserting dummy rows
Range("A209:A" & lastrow).Value = Range("A210:A" & lastrow).Value
Range("U209:U" & lastrow).Formula = "=IF(AND(ISBLANK(A209),ISBLANK(A209)),0,1)"
Range("U209:U" & lastrow).Value = Range("U209:U" & lastrow).Value
Range("A209:U" & lastrow).Sort Key1:=Range("U209"), Order1:=xlAscending
cc = WorksheetFunction.CountIf(Columns(21), "0")
If cc <> 0 Then
Range("A209:U" & cc).Select
Range("A209:U" & cc).EntireRow.Delete
lastrow = lastrow - cc
End If
Range("A209:U" & lastrow).Sort Key1:=Range("A209"), Order1:=xlAscending
Range("U:U").ClearContents
Range("A:A").Delete
End Sub
I've tried different attempts but not working. codes are commented.
Thanks!
With the help and ideas of users, I've come to this simple code and got it working.
Credits to all of them! Cheers!
Option Explicit
Sub Project_M()
Dim Last As Long
Dim i As Long
Application.ScreenUpdating = False
Last = cells(rows.Count, "A").End(xlUp).Row
Range("A209:S" & Last).UnMerge
Range("A209:S" & Last).WrapText = False
For i = Last To 209 Step -1
If (cells(i, "A").Value) = "Source" Or (cells(i, "A").Value) = 0 Or (cells(i, "A").Value) = "End of Report" Or (cells(i, "A").Value) = "Transaction" Then
cells(i, "A").EntireRow.Delete
End If
Next i
ActiveSheet.UsedRange.Columns.AutoFit
Application.ScreenUpdating = True
End Sub
Starting from the last row of the column for i = Last up to the row I want to start my formatting and deleting To 209 and Step -1 to move up.

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

Insert row in excel with a value in a specific cell

I'm using this script to insert fill with rows where non-sequential is produced in a column of an excel file.
Sub InsertValueBetween()
Dim lastrow As Long
Dim gap As Long
Dim i As Long, ii As Long
Application.ScreenUpdating = False
With ActiveSheet
lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row
For i = lastrow To 3 Step -1
gap = .Cells(i, "A").Value - .Cells(i - 1, "A").Value
If gap > 1 Then
.Rows(i).Resize(gap - 1).Insert
End If
Next i
lastrow = .Cells(.Rows.Count, "A").End(xlUp).Row
.Cells(3, "A").Value = .Cells(2, "A").Value + 1
.Cells(2, "A").Resize(2).AutoFill .Cells(2, "A").Resize(lastrow - 1)
End With
End Sub
In addition to adding these new rows I want them to also have a specific value in column B. I'm trying to implement this but with no result.
Anybody could help me?
One way you could tackle this challenge is with a Range variable. Here is some heavily-commented code that walks through the process:
Sub InsertValueBetweenRev2()
Dim Target As Range '<~ declare the range variable
'... declare your other variables
'... do other stuff
For i = lastrow To 3 Step -1
gap = .Cells(i, "A").Value - .Cells(i - 1, "A").Value
If gap > 1 Then
.Rows(i).Resize(gap - 1).Insert
'the next line sets the range variable to the recently
'added cells in column B
Set Target = .Range(.Cells(i, 2), .Cells(i + gap - 2, 2))
Target.Value = "Cool" '<~ this line writes text "Cool" into those cells
End If
Next i
'... the rest of your code
End Sub
So, to sum it up, we know that gap - 1 rows are going to be added, and we know that the new rows are added starting at row i. Using that knowledge, we assign the just-added cells in column B to a Range then set the .value of that Range to whatever is needed.
a Better way of doing it with less variables and faster:
Sub InsRowWithText()
Dim LR As Long, i As Long
LR = Range("D" & Rows.Count).End(xlUp).row
For i = LR To 3 Step -1
If Range("D" & i).Value <> Range("D" & i - 1).Value Then
Rows(i).Resize(1).Insert
Range("D" & i).Value = "Test"
End If
Next i
End Sub
This is how i utilized it:
Sub InsRowWithText()
Dim strMsg As String, strTitle As String
Dim LR As Long, i As Long
Text = "ADD"
strMsg = "Warning: This is a Advanced Function, Continue? "
strTitle = "Warning: Activated Advanced Function "
If MsgBox(strMsg, vbQuestion + vbYesNo, strTitle) = vbNo Then
Exit Sub
Else
Sheets("SAP Output DATA").Select
If Range("D3").Value = Text Then
MsgBox "Detected That This Step Was Already Completed, Exiting."
Exit Sub
End If
application.ScreenUpdating = False
LR = Range("D" & Rows.Count).End(xlUp).row
For i = LR To 3 Step -1
If Range("D" & i).Value <> Range("D" & i - 1).Value Then
Rows(i).Resize(1).Insert
Range("D" & i).EntireRow.Interior.ColorIndex = xlColorIndexNone
Range(("A" & i), ("D" & i)).Value = Text
End If
Next i
End If
Range("D2").Select
Selection.End(xlDown).Select
ActiveCell.Offset(1).Select
Range(("A" & ActiveCell.row), ("D" & ActiveCell.row)).Value = Text 'last row doesnt get text for some reason.
ActiveCell.EntireRow.Interior.ColorIndex = xlColorIndexNone
ActiveCell.Offset(1).Select
Range(("D" & ActiveCell.row), ("E" & ActiveCell.row)).Interior.ColorIndex = 17 'purple
application.ScreenUpdating = True
Range("D3").Select
End Sub