transpose dynamic range exel VBA - excel

having 25 columns and n number rows in sheet Input_Excel as in the image "DATA" and transposing the same into another sheet as in the image "Output" in my requited specific format . My code is working perfectly when the input_excel having minimal data and giving expected output where as the data being more than 2600 is giving bad output as in the image "Wrong"
I am hanging and struggling a lot to fix the issue. please help me to find out the problem in my below code. is there any maximum limit in handling arrays in excel VBA?
Correct me if am dealing any wrong method/calling. will be a great help and thanks in advance.
Dim ws As Worksheet
Dim toWs As Worksheet
Dim vDB, vR()
Dim strShName As Variant
Dim r As Long, i As Long, n As Long, lastRow As Long, cc As Long, req_id As String
Dim k As Integer, j As Integer
Dim sc As Range, lr As Long, lc As Long, rg As Range, myRange As Range
Application.Calculation = xlCalculationManual
Application.EnableEvents = False
Application.ScreenUpdating = False
Set ws = Sheets("Input Excel")
Set sc = ws.Range("A1")
lr = sc.SpecialCells(xlCellTypeLastCell).Row
lc = sc.SpecialCells(xlCellTypeLastCell).Column
strShName = ActiveSheet.Name
If strShName = "Data" Then
Application.DisplayAlerts = False
Sheets("Data").Delete
Application.DisplayAlerts = True
End If
Sheets.Add.Name = "Data"
Columns("A:c").Select
Selection.NumberFormat = "#"
Range("A1").Select
Set rg = ws.Range("A1").CurrentRegion
Set toWs = Sheets("Data") '<~~ Result Sheet
ws.Activate
Range("D1:Y1").Select
Selection.NumberFormat = "0"
Range("A1").Select
toWs.Activate
vDB = ws.Range(sc, ws.Cells(lr, lc)).Value
r = UBound(vDB, 1)
cc = ws.Range(sc, ws.Cells(lr, lc)).Columns.Count
For i = 2 To r
If vDB(i, 1) <> "" Then ' row
For j = 4 To cc
n = n + 1
ReDim Preserve vR(1 To cc, 1 To n)
For k = 1 To 3
vR(k, n) = vDB(i, k)
Next k
vR(4, n) = vDB(1, j)
vR(5, n) = vDB(i, j)
Next j
End If
Next i
With toWs
.UsedRange.Offset(1).Clear
.Range("A2").Resize(n, 10) = WorksheetFunction.Transpose(vR)
End With
Range("A3:C3").Select
Selection.Copy
Range("A2").Select
ActiveCell.PasteSpecial
Range("A1").Value = "Sales Org"
Range("B1").Value = "Soldto"
Range("C1").Value = "TE Part Number"
Range("D1").Value = "Demand_Date"
Range("E1").Value = "Values"
toWs.Select
lastRow = Cells(Rows.Count, "A").End(xlUp).Row
Set myRange = Range("E2:E" & lastRow)
myRange.Select
On Error GoTo eh
Selection.SpecialCells(xlCellTypeBlanks).Select
Selection.EntireRow.Delete
eh:
lastRow = Cells(Rows.Count, "A").End(xlUp).Row
Set myRange = Range("d2:d" & lastRow)
Range("J1").Select
ActiveCell.FormulaR1C1 = "=IFERROR(FIND(""."",R[1]C[-6],1),0)"
Range("J1").Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
If Range("J1").Value > 0 Then
myRange.Select
Selection.Replace What:=".", Replacement:="/", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=True
End If
Range("J1").Select
Selection.ClearContents
Columns("E:E").Select
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Range("E2").Select
ActiveCell.FormulaR1C1"=
DAY(RC[-1])&""/""&MONTH(RC[-1])&""/""&YEAR(RC[-1])"
lastRow = Cells(Rows.Count, "A").End(xlUp).Row
Set myRange = Range("E2:E" & lastRow)
myRange.Select
Selection.FillDown
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone,
SkipBlanks:=False, Transpose:=False
Range("D1").Select
Application.CutCopyMode = False
Selection.Copy
Range("E1").Select
ActiveSheet.Paste
Columns("D:D").Select
Application.CutCopyMode = False
Selection.Delete Shift:=xlToLeft
Range("f2").Select
ActiveCell.FormulaR1C1 = "=IF(RC[-5]=""NA"",RC[-5],IF(LEN(RC[-5])=
2,CONCAT(""00"",RC[-5]),IF(LEN(RC[-5])=3,
CONCAT(0,RC[-5]),IF(LEN(RC[-5])=1,CONCAT(""000"",RC[-5]),RC[-5]))))"
lastRow = Cells(Rows.Count, "A").End(xlUp).Row
Set myRange = Range("F2:F" & lastRow)
myRange.Select
Selection.FillDown
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone,
SkipBlanks:=False, Transpose:=False
myRange.Select
Selection.Copy
Range("A2").Select
ActiveSheet.Paste
Columns("F:f").Select
Application.CutCopyMode = False
Selection.Delete Shift:=xlToLeft
Dim v As Integer
Range("A1").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
Range("A:E").EntireColumn.AutoFit
req_id = InputBox("Please enter request ID which is generated in your
application")
If req_id = "" Then
Application.DisplayAlerts = False
Sheets("Data").Delete
Application.DisplayAlerts = True
End If
Sheets("SaveFile").Select
End If
Range("F1").Select
ActiveCell.FormulaR1C1 = "Case_ID"
Range("F2").Select
lastRow = Cells(Rows.Count, "A").End(xlUp).Row
Set myRange = Range("F2:F" & lastRow)
myRange.Value = req_id
lastRow = Cells(Rows.Count, "A").End(xlUp).Row
Set myRange = Range("A1:F" & lastRow)
myRange.Select
Dim t As Integer
If t = 0 Then
Dim tbl As ListObject
Set tbl = ActiveSheet.ListObjects.Add(xlSrcRange, Selection, , xlYes)
tbl.TableStyle = "TableStyleMedium15"
End If
t = 1
Set myRange = Range("A2:B" & lastRow)
myRange.Replace What:="NA", Replacement:="", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Range("D1").Value = "Demand_Date"
Dim DTAddress As String
DTAddress = CreateObject("WScript.Shell").SpecialFolders("Desktop") & "\"
ActiveWorkbook.SaveAs Filename:=DTAddress & req_id &
"_Upload_LTF_Monthly", FileFormat:=6
MsgBox "Please check file is saved in your desktop and upload the same
desktop saved file"
ws.Activate
Range("D1:Y1").Select
Selection.NumberFormat = "mmm-yy"
Range("A1").Select
toWs.Activate
Application.Calculation = xlCalculationAutomatic
Application.EnableEvents = True
Application.ScreenUpdating = True
'ActiveWorkbook.Close False
End Sub
DATA
Output
Wrong

Transpose Data Range Using Arrays
Adjust the values in the constants section (Source, Target and Other).
I've added the headers to be copied to column "H". If you don't want them copied, remove the 3rd element (, "H") in tgtCols and delete the line Target(2)(k, 1) = Source(1, j).
The Code
Option Explicit
Sub transposeDataOnly()
' Source
Const srcName As String = "Input_Excel"
Const srcFirstCell As String = "A1"
Const srcFirstCol As Long = 3
' Target
Const tgtName As String = "Data"
Dim tgtCols As Variant
tgtCols = VBA.Array("C", "E", "H") ' 'VBA' ensures zero-based.
Const tgtFirstRow As Long = 2
' Other
Dim wb As Workbook
Set wb = ThisWorkbook ' The workbook containing this code.
' Write values from Source Range to Source Array.
Dim src As Worksheet
Set src = wb.Worksheets(srcName)
Dim Source As Variant
Source = src.Range(srcFirstCell).CurrentRegion.Value
' Define Jagged Target Array.
Dim ubC As Long: ubC = UBound(tgtCols)
Dim Target As Variant: ReDim Target(0 To ubC)
Dim ubS1 As Long: ubS1 = UBound(Source, 1)
Dim ubS2 As Long: ubS2 = UBound(Source, 2)
Dim Help As Variant
ReDim Help(1 To (ubS1 - 1) * (ubS2 - srcFirstCol), 1 To 1)
Dim j As Long ' Columns Array Element Counter, Source Array Columns Counter
For j = 0 To ubC
Target(j) = Help
Next j
' Write values from Source Array to arrays of Jagged Target Array.
Dim i As Long ' Source Array Rows Counter
Dim k As Long ' Arrays of Jagged Target Array Rows Counter
For i = 2 To ubS1
If Not IsEmpty(Source(i, srcFirstCol)) Then
For j = srcFirstCol + 1 To ubS2
If Not IsEmpty(Source(i, j)) Then
k = k + 1
Target(0)(k, 1) = Source(i, srcFirstCol) ' TE Part Number
Target(1)(k, 1) = Source(i, j) ' Values
Target(2)(k, 1) = Source(1, j) ' Headers
End If
Next j
End If
Next i
' Write values from Jagged Target Array to Target Range.
Dim tgt As Worksheet
Set tgt = wb.Worksheets(tgtName)
'tgt.Cells.ClearContents
For j = 0 To ubC
tgt.Cells(tgtFirstRow, tgtCols(j)).Resize(k).Value = Target(j)
Next j
End Sub

Related

Using a For loop to find a single value then execute code

the purpose of my macro is to find a certain value "MI (D)" within column B then execute code based on the surrounding cells. Sometimes there's only one value, sometimes there can be more. How can I code my for loop so it starts with the first one, then checks the column for more? Right now my code does the first one perfectly, but if there is a second, third one, etc it doesn't execute.
Dim Rng As Range
Dim cell As Variant
Dim ws As Worksheet
Set ws = ActiveSheet
Set Rng = Range("B:B").Find("MI (D)")
For Each cell In Rng
If Not Rng Is Nothing Then
Rng.Select
End If
ActiveCell.Offset(0, 1).Select
Range(ActiveCell, ActiveCell.Offset(0, 1)).Select
Selection.Copy
'For Each cell In ws.Columns(3).Cells
' If IsEmpty(cell) = True Then cell.Select: Exit For
'Next cell
Dim LastRow As Long
LastRow = Cells(Rows.Count, 1).End(xlUp).Row
Cells(LastRow, 3).Offset(1, 0).Select
Selection.PasteSpecial paste:=xlPasteValues
ActiveCell.Offset(1, 0).Select
Selection.PasteSpecial paste:=xlPasteValues
ActiveCell.Offset(1, 0).Select
Selection.PasteSpecial paste:=xlPasteValues
ActiveCell.Offset(1, 0).Select
Selection.PasteSpecial paste:=xlPasteValues
ActiveCell.Offset(-3, 0).Select
ActiveCell = ActiveCell - 1
ActiveCell.Offset(0, 1).Select
ActiveCell = ActiveCell + 25
ActiveCell.Offset(1, -1).Select
ActiveCell = ActiveCell - 1
ActiveCell.Offset(0, 1).Select
ActiveCell = ActiveCell + 25
ActiveCell.Offset(1, -1).Select
ActiveCell = ActiveCell - 11
ActiveCell.Offset(0, 1).Select
ActiveCell = ActiveCell + 50
ActiveCell.Offset(1, -1).Select
ActiveCell = ActiveCell - 11
ActiveCell.Offset(0, 1).Select
ActiveCell = ActiveCell + 50
Rng.Select
ActiveCell.Offset(0, -1).Select
Selection.Copy
'For Each cell In ws.Columns(1).Cells
' If IsEmpty(cell) = True Then cell.Select: Exit For
'Next cell
LastRow = Cells(Rows.Count, 1).End(xlUp).Row
Cells(LastRow, 1).Offset(1, 0).Select
Selection.PasteSpecial paste:=xlPasteValues
ActiveCell.Offset(1, 1).Select
Selection.PasteSpecial paste:=xlPasteValues
ActiveCell.Offset(1, -1).Select
Selection.PasteSpecial paste:=xlPasteValues
ActiveCell.Offset(1, 1).Select
Selection.PasteSpecial paste:=xlPasteValues
ActiveCell.Offset(-3, 0).Select
Selection = "ON (D)"
Selection.Copy
ActiveCell.Offset(1, -1).Select
Selection.PasteSpecial paste:=xlPasteValues
ActiveCell.Offset(1, 1).Select
Selection = "ON (I)"
Selection.Copy
ActiveCell.Offset(1, -1).Select
Selection.PasteSpecial paste:=xlPasteValues
Next cell
End sub```
[![enter image description here][1]][1]
[1]: https://i.stack.imgur.com/ltM8S.png
Find Multiple Matches (Find/FindNext)
Sub UpdateMyData()
Const SOURCE_FIRST_CELL_ADDRESS As String = "B2"
Const CRITERION As String = "MI (D)"
Const DESTINATION_COLUMN As String = "A"
Const DESTINATION_ROWOFFSET As Long = 4
Dim ws As Worksheet: Set ws = ActiveSheet ' improve!
' The Find method will fail if the worksheet is filtered:
If ws.AutoFilterMode Then ws.AutoFilterMode = False
Dim srg As Range
With ws.Range(SOURCE_FIRST_CELL_ADDRESS)
Set srg = Intersect(.Resize(ws.Rows.Count - .Row + 1), ws.UsedRange)
End With
Dim slCell As Range: Set slCell = srg.Cells(srg.Cells.Count) ' last
Dim dfCell As Range
Set dfCell = slCell.Offset(1).EntireRow.Columns(DESTINATION_COLUMN) ' first
Dim sfCell As Range
' If the cells contain values:
Set sfCell = srg.Find(CRITERION, slCell, xlFormulas, xlWhole)
' If the cells contain formulas, replace 'xlFormulas' with 'xlValues'.
' in the latter case, make sure there are no hidden rows,
' or the Find method will fail.
If sfCell Is Nothing Then
MsgBox "The criterion '" & CRITERION & "' was not found.", vbExclamation
Exit Sub
End If
Dim SourceFirstCellAddress As String
SourceFirstCellAddress = sfCell.Address
Do
WriteMyData sfCell, dfCell ' write
Set sfCell = srg.FindNext(sfCell) ' find next
Set dfCell = dfCell.Offset(DESTINATION_ROWOFFSET)
Loop Until sfCell.Address = SourceFirstCellAddress
MsgBox "Data updated.", vbInformation
End Sub
Sub WriteMyData( _
ByVal sfCell As Range, _
ByVal dfCell As Range)
Dim sData() As Variant: sData = sfCell.Offset(, -1).Resize(, 4).Value
Dim dData() As Variant: ReDim dData(1 To 4, 1 To 4)
dData(1, 1) = sData(1, 1)
dData(2, 1) = "ON (D)"
dData(3, 1) = sData(1, 1)
dData(4, 1) = "ON (I)"
dData(1, 2) = "ON (D)"
dData(2, 2) = sData(1, 1)
dData(3, 2) = "ON (I)"
dData(4, 2) = sData(1, 1)
dData(1, 3) = sData(1, 3) - 1
dData(2, 3) = sData(1, 3) - 1
dData(3, 3) = sData(1, 3) - 11
dData(4, 3) = sData(1, 3) - 11
dData(1, 4) = sData(1, 4) + 25
dData(2, 4) = sData(1, 4) + 25
dData(3, 4) = sData(1, 4) + 50
dData(4, 4) = sData(1, 4) + 50
dfCell.Resize(4, 4).Value = dData
End Sub

How to copy and paste data, in lots of 200, from horizontal to vertical?

I am trying to copy and paste data from horizontal to vertical from sheet1 to sheet3 in a lots of 200.
Say I have a list of 600 tickers. The code will copy the first 200 from sheet1 cells ("C6 till GT7") and paste it vertically in sheet3 cell A2.
I need the next lot of 200 appended in sheet3 after row 201.
My code is pasting only the last 200 in sheet 3.
Sub getbulkprices()
Application.ScreenUpdating = False
Dim wb As Workbook, ws, ws1 As Worksheet
Dim r, iLastRow As Long, plr as long
Set wb = ThisWorkbook
Set ws = wb.Sheets("Sheet1")
Set ws1 = wb.Sheets("Sheet2")
iLastRow = ThisWorkbook.Sheets("Sheet2").Cells(Rows.Count, "A").End(xlUp).Row
ThisWorkbook.Sheets("Sheet1").Range("A2:A500").ClearContents
ThisWorkbook.Sheets("Sheet3").Range("A2:B500000").ClearContents
For r = 2 To ws1.Range("A" & Rows.Count).End(xlUp).Row Step 200
ThisWorkbook.Sheets("Sheet1").Cells(2, 1).Resize(200).Value = _
ws1.Cells(r, 1).Resize(200).Value
ws.Range("C1").FormulaR1C1 = "=#RHistory(R2C1:R200C1,"".Timestamp;.Close"",""NBROWS:""&R2C2&"" INTERVAL:1D"",,""SORT:ASC TSREPEAT:NO CH:In;"",R[5]C)"
Application.Run "EikonRefreshWorksheet"
Application.Wait (Now + TimeValue("0:00:02"))
plr = ThisWorkbook.Sheets("Sheet3").Cells(Rows.Count, 1).End(xlUp).Row
ws.Range("D6:IK7").Copy
ThisWorkbook.Sheets("Sheet3").Range("A2:B" & plr + 1).PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=True
Application.CutCopyMode = False
Application.StatusBar = r & " / " & iLastRow - 1
Next r
End Sub
Consider qualifying the Rows.Count to the that same worksheet as qualifier to .Cells in the plr assignment:
plr = ThisWorkbook.Sheets("Sheet3").Cells( _
ThisWorkbook.Sheets("Sheet3").Rows.Count, 1 _
).End(xlUp).Row
Even better situate the copy and paste inside a With block to avoid repetition of worksheet:
For r = 2 To ... Step 200
...
With ThisWorkbook.Sheets("Sheet3")
plr = .Cells(.Rows.Count, 1).End(xlUp).Row
ws.Range("D6:IK7").Copy
.Range(.Cells(plr + 1, 1), _
.Cells(plr + 200, 2) _
).PasteSpecial _
Paste:=xlPasteValues, _
Operation:=xlNone, _
SkipBlanks:=False, _
Transpose:=True
End With
...
Next r
Consider even WorksheetFunction.Transpose and avoid copy/paste:
With ThisWorkbook.Sheets("Sheet3")
plr = .Cells(.Rows.Count, 1).End(xlUp).Row
.Range(.Cells(plr + 1, 1), _
.Cells(plr + 200, 2) _
) = WorksheetFunction.Transpose(ws.Range("D6:IK7"))
End With
Change the paste to
ThisWorkbook.Sheets("sheet3").Range("A" & plr + 1 & ":B" & plr + 201).PasteSpecial...

Copy and Pasting filtered data from one worksheet to another

I am new to macros. I have this below code in which I am trying to copy some filtered data from one sheet and paste in another worksheet in the end but getting error in the pasting step. I dont know how to correct that. Can someone please help me on this?
Sub MyTest()
Dim ws1 As Worksheet
Dim ws2 As Worksheet
Dim i As Long
Dim j As Long
Dim LastRow As Long
Dim r As Long
Dim str As String
Dim lRow As Long
Application.ScreenUpdating = False
Set ws1 = Sheets("Sheet2")
Set ws2 = Sheets("Sheet1")
lr1 = Cells(Rows.Count, 3).End(xlUp).Row
lr2 = Cells(Rows.Count, 2).End(xlUp).Row
For r = lr1 To 5 Step -1
ws2.Activate
str = ws2.Cells(r, "C")
i = Application.WorksheetFunction.CountIf(ws1.Columns(1), str)
If i > 1 Then ws2.Rows(r + 1 & ":" & r + i - 1).Insert
ws2.Range(Cells(r, "C"), Cells(r + i - 1, "C")) = str
ws2.Activate
ws2.Range("$A$4:$W$4").AutoFilter Field:=3, Operator:=xlFilterValues, Criteria1:=str
ws1.Activate
ws1.Range("$A$1:$D$1").AutoFilter Field:=1, Operator:=xlFilterValues, Criteria1:=str
ActiveSheet.AutoFilter.Range.Offset(1).SpecialCells(xlCellTypeVisible).Cells(1, 2).Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.SpecialCells(xlCellTypeVisible).Copy
ws2.Activate
ws2.Range("$A$4:$W$4").AutoFilter Field:=3, Operator:=xlFilterValues, Criteria1:=str
ActiveSheet.AutoFilter.Range.Offset(1).SpecialCells(xlCellTypeVisible).Cells(1, 8).Select
Selection.PasteSpecial Paste:=xlPasteValues
Application.CutCopyMode = False
Next r
End Sub

Copy data based on loop and then paste data on multiple sheets created based on array

I am creating new data which is dependent upon variable x using loop, then trying to copy the data with each iteration in X and then pasting the data on multiple sheets (variable "FundSheetNames"). Here I dont know how to exit from loop FundSheetNames without next i and then again go on to X to copy new data.
Sub peer2()
ThisWorkbook.Sheets("Peer Code").Activate
Dim X As Range, Y As Range
Set X = Sheets("Peer Code").Range("J2:J11")
Dim Sht As Worksheet
Dim sheet_names As Variant
For Each sheet_Name In Sheets("Peer Code").Range("K2:K3")
For Each Y In X
Set WS = Worksheets(sheet_Name.Text)
ThisWorkbook.Sheets("Peer Fund").Activate
Range("F7:F166").Select
Selection.ClearContents
ThisWorkbook.Sheets("Peer Code").Activate
Y.Select
Selection.Copy
Range("L2").Select
Selection.PasteSpecial Paste:=xlPasteValues
Range("N2:N161").Select
Selection.Copy
ThisWorkbook.Sheets("Peer Fund").Activate
Range("F7").EntireColumn.Hidden = False
Range("$F7").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone,
SkipBlanks:= _
False, Transpose:=False
With Sheets("Peer Fund")
Set FOUNDRANGE = .Columns("F:F").Find("*", After:=.Range("F167"), searchdirection:=xlPrevious, LookIn:=xlValues)
If Not FOUNDRANGE Is Nothing Then LR1 = FOUNDRANGE.Row
End With
Range("F166:F" & LR1 + 1).EntireRow.Select
Application.Selection.EntireRow.Hidden = False
Range("A6:W" & LR1).Select
ActiveWorkbook.Worksheets("Peer Fund").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Peer Fund").Sort.SortFields.Add2 Key _
:=Range("A2:A" & LR1), SortOn:=xlSortOnValues, Order:=xlAscending, _
DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Peer Fund").Sort
.SetRange Range("A6:W" & LR1)
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
Range("F7").EntireColumn.Hidden = False
Range("A5:W172").Select
Selection.SpecialCells(xlCellTypeVisible).Copy
WS.Activate
Range("A5").Select
Selection.PasteSpecial Paste:=xlPasteValues
Selection.PasteSpecial Paste:=xlPasteFormats
With WS
Set FOUNDRANGE = .Columns("F:F").Find("*",
After:=.Range("F167"),
searchdirection:=xlPrevious, LookIn:=xlValues)
If Not FOUNDRANGE Is Nothing Then LR2 = FOUNDRANGE.Row
End With
Range("F166:F" & LR1 + 1).EntireRow.Select
Application.Selection.EntireRow.Hidden = True
Range("F7").EntireColumn.Hidden = True
Next Y
Next sheet_Name
End Sub
Exit For
Open a new worksheet and put the code into a module. Then put in some values into column A. Put a few 5-s among the values.
The following is an example that looks for the value 5 in column A. When 5 is found it returns a message containing the address of the cell where it was found, in the Immediate window (CTRL+G).
Option Explicit
Sub FirstOccurrence()
Const Col As Variant = "A"
Const FirstRow As Long = 2
Const Criteria As Long = 5
Dim rng As Range
' Define the last non-empty cell.
Set rng = Columns(Col).Find("*", , xlValues, , , xlPrevious)
If rng Is Nothing Then Exit Sub
If rng.Row < FirstRow Then Exit Sub
' Define the column range from FirstRow to row of last non-empty cell.
Set rng = Range(Cells(FirstRow, Col), rng)
Dim cel As Range
For Each cel In rng
If cel.Value = Criteria Then
Debug.Print "Cell '" & cel.Address & "' contains the value '" _
& Criteria & "'."
Exit For
End If
Next cel
End Sub
You have just seen how the code finds just the first occurrence of 5.
Now remove the line Exit For and see the results in the Immediate window (CTRL+G).

Removing duplicates within a row

Friends,
I have an excel table that repeats for a few thousand rows. 3 categories of columns, which may repeat, such as in the second row shown below
Is there a way to have excel cycle through a row and remove the duplicates within the row, so that it ultimately looks like the second table shown below?
I am not sure but is this what you are trying?
Option Explicit
Sub Sample()
Dim wsI As Worksheet
Dim lastRow As Long, lastCol As Long, i As Long, j As Long
Dim sVal1, sVal2, sVal3
'~~> Input Sheet
Set wsI = Sheets("Sheet1")
With wsI
lastRow = .Cells.Find(What:="*", After:=.Range("A1"), _
Lookat:=xlPart, LookIn:=xlFormulas, SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious, MatchCase:=False).Row
lastCol = .Cells.Find(What:="*", After:=.Range("A1"), _
Lookat:=xlPart, LookIn:=xlFormulas, SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious, MatchCase:=False).Column
For i = 1 To lastRow
sVal1 = .Cells(i, 1).Value
sVal2 = .Cells(i, 2).Value
sVal3 = .Cells(i, 3).Value
For j = 4 To lastCol Step 3
If .Cells(i, j).Value = sVal1 And _
.Cells(i, j + 1).Value = sVal2 And _
.Cells(i, j + 2).Value = sVal3 Then
.Cells(i, j).ClearContents
.Cells(i, j + 1).ClearContents
.Cells(i, j + 2).ClearContents
End If
Next j
Next i
End With
End Sub
Here's how i solved for it. Not the prettiest but it works:
Removing duplicates phones from row
Sub PhoneDedupByRow()
Dim Loopcounter As Long
Dim NumberOfCells As Long
Application.ScreenUpdating = False
'Range starting at A1
Worksheets("Sheet1").Activate
NumberOfCells = Range("A2", Range("A2").End(xlDown)).Count
For Loopcounter = 1 To NumberOfCells
'copies each section...I need to select the proper offsets for cells with the ph#'
Range(Range("A1").Offset(Loopcounter, 10), Range("A1").Offset(Loopcounter, 19)).Copy
'This is where the past/transpose will go...push it out to a far out column to avoid errors
Range("W1").Select
Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:= _
False, Transpose:=True
Application.CutCopyMode = False
'Knowing the range is 10 cells, i added 11 because gotospecial with no blanks causes an error
Range("W1:W11").Select
Selection.SpecialCells(xlCellTypeBlanks).Select
Selection.Delete Shift:=xlUp
ActiveSheet.Range("W1:W10").RemoveDuplicates Columns:=1, Header:=xlNo
ActiveSheet.Range("W1:W10").Select
Selection.Copy
Range(Range("A1").Offset(Loopcounter, 10), Range("A1").Offset(Loopcounter, 19)).Select
Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:= _
False, Transpose:=True
Application.CutCopyMode = False
ActiveSheet.Range("W1:W10").Select
Selection.ClearContents
Next Loopcounter
Application.ScreenUpdating = True
End Sub

Resources