I want to merge that repeating Chapters into just one cell by Chapter.
Here is how my code does the looping.
Dim label As Control
Dim itm As Object
For ctr = 1 To InfoForm.Chapter.ListCount - 1
For Each label In InfoForm.Controls
If TypeName(label) = "Label" Then
With ActiveSheet
i = i + 1
lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row + IIf(i = 1, 1, 0)
lastColumn = .Cells(i, .Columns.Count).End(xlToLeft).Column
If label <> "Chapter" Then
.Cells(lastColumn, i).Value = "Chapter " & ctr
.Cells(lastRow, i).Value = label.Caption
End If
End With
End If
Next
Next
I've tried merging it like this
.Range(Cells(1, lastColumn), Cells(1,i)).Merge
But it merges all the repeating chapters into one cell instead
Expected Result:
My method is bellow
Dim label As Control
Dim itm As Object
For ctr = 1 To InfoForm.Chapter.ListCount - 1
For Each label In InfoForm.Controls
If TypeName(label) = "Label" Then
With ActiveSheet
i = i + 1
lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row + IIf(i = 1, 1, 0)
lastColumn = .Cells(i, .Columns.Count).End(xlToLeft).Column
If label <> "Chapter" Then
.Cells(lastColumn, i).Value = "Chapter " & ctr
.Cells(lastRow, i).Value = label.Caption
End If
End With
End If
Next
Next
'this is merge method
Dim rngDB As Range, rng As Range, n As Integer
Application.DisplayAlerts = False
Set rngDB = Range("a1", Cells(1, Columns.Count).End(xlToLeft))
For Each rng In rngDB
If rng <> "" Then
n = WorksheetFunction.CountIf(rngDB, rng)
rng.Resize(1, n).Merge
rng.HorizontalAlignment = xlCenter
End If
Next rng
Application.DisplayAlerts = True
How about this?
With ActiveSheet
firstCol = 1
lastCol = .Cells(1, .Cells.Columns.Count).End(xlToLeft).Column
For i = 1 To lastCol
If .Cells(1, i) = "" Then GoTo NextCol 'skip blank cell
If firstCol = 0 And .Cells(1, i) <> "" Then firstCol = i 'set first column
If .Cells(1, i) = .Cells(1, i + 1) Then
LastColDup = i 'remember last duplicate column
Else
Application.DisplayAlerts = False
With .Range(Cells(1, firstCol), Cells(1, LastColDup + 1))
.Merge
.HorizontalAlignment = xlCenter
End With
Application.DisplayAlerts = True
firstCol = 0
LastColDup = 0
End If
NextCol:
Next i
End With
If you know the ranges before hand then you could adjust the code below. I've created this by recording a macro and then disabling/enabling alerts as appropriate. I've included a function to convert integer column values to alph equivalents.The MainLoop Intcol1 and intcol2 would be values that you would provide based on the input from the original Form.
Sub MainLoop()
Dim StrMycol_1 As String
Dim StrMycol_2 As String
Dim intcol1 As Integer
Dim intcol2 As Integer
intcol1 = 5: intcol2 = 7
StrMycol_1 = WColNm(intcol1) ' mycell.column is numeric. Function returns integer
StrMycol_2 = WColNm(intcol2) ' mycell.column is numeric. Function returns integer
'
do_merge_centre StrMycol_1, StrMycol_2
End Sub
Sub do_merge_centre(col1, col2)
Range(col1 + "1:" + col2 + "1").Select
Application.DisplayAlerts = False
With Selection
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlBottom
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
Selection.Merge
Application.DisplayAlerts = True
End Sub
'
Public Function WColNm(ColNum) As String
WColNm = Split(Cells(1, ColNum).Address, "$")(1)
End Function
Related
I have a worksheets for my projects.
the first sheet is the main one the containing all the name of the projects.
the author sheets are for every project.
in the main sheet the name of the project has hyperlink to his sheet.
when running the code I got a pop msgbox that I write the new project name (look for "project_name").
the code does stuff.
but near the end there is the hyperlink code. (look for ActiveSheet.Hyperlinks.Add....)
so my problem is:
when I choose a project name like "abcd" everything works ok. But when I choose name like "ab cd". the code runs but the hyperlink doesn't work.
I realized that having a space in the project name makes the code not work.
thanks for the help.
p.s.
The notes are in Hebrew.
Sub New_project()
'--------------------------------------------------------------------------------------------------תחילת ריצת קוד
Dim Start, Finish, TotalTime As Date
Start = Timer
'--------------------------------------------------------------------------------------------------ביטול חישובים ועדכוני מסך והתראות
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.AskToUpdateLinks = False
'--------------------------------------------------------------------------------------------------החזרת חישובים ועדכוני מסך והתראות
'Application.Calculation = xlCalculationAutomatic
'Application.ScreenUpdating = True
'Application.DisplayAlerts = True
'Application.AskToUpdateLinks = True
'--------------------------------------------------------------------------------------------------פתיחת חלונית והקלדת שם הפרויקט
'--------------------------------------------------------------------------------------------------אם לחצו cancel אז יציאה מהקוד
Dim project_name As String
project_name = InputBox("נא להקליד את שם הפרויקט החדש")
If Len(project_name) < 1 Then
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.AskToUpdateLinks = True
MsgBox ("יציאה מהקוד")
Exit Sub
End If
'--------------------------------------------------------------------------------------------------בדיקה האם שם הגיליון לפרויקט החדש כבר קיים
Dim curSheet As Worksheet
Dim ArraySheets() As String
Dim x As Variant
Dim sheet_existing As Integer
x = 0
sheet_existing = 0
For Each curSheet In ActiveWorkbook.Worksheets
If curSheet.Name Like project_name Then
Worksheets(project_name).Activate
sheet_existing = 1
Finish = Timer
TotalTime = Format((Finish - Start) / 86400, "hh:mm:ss")
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.AskToUpdateLinks = True
MsgBox ("שם הפרויקט כבר קיים" & vbNewLine & "זמן ריצת קוד: " & TotalTime)
Exit Sub
End If
Next curSheet
'iComp = StrComp(str1, str2, vbBinaryCompare)
'--------------------------------------------------------------------------------------------------הוספת גיליון חדש בסוף הקובץ
If sheet_existing = 0 Then
Sheets.Add After:=Sheets(Sheets.Count)
ActiveSheet.Name = project_name
End If
'--------------------------------------------------------------------------------------------------הוספת כותרות
Range("A1") = "#"
Range("B1") = "תאריך"
Range("C1") = "שלב"
Range("D1") = "איש קשר"
Range("E1") = "הערות"
Range("F1") = "מסמכים"
Range("G1") = "ימים"
Range("H1") = "צבירה"
'--------------------------------------------------------------------------------------------------רוחב עמודה
Columns("A").ColumnWidth = 9
Columns("B").ColumnWidth = 11
Columns("C").ColumnWidth = 30
Columns("D").ColumnWidth = 16
Columns("E").ColumnWidth = 17
Columns("F").ColumnWidth = 9
Columns("G").ColumnWidth = 6
Columns("H").ColumnWidth = 10
'--------------------------------------------------------------------------------------------------הוספת מסגרת לתאים
Dim rng1 As Range
Set rng1 = Range(Cells(1, 1), Cells(27, 8))
With rng1.Borders
.LineStyle = xlContinuous
.Color = vbBlack
.Weight = xlThin
End With
Range("A:H").HorizontalAlignment = xlCenter
Range("A:H").VerticalAlignment = xlCenter
Rows(1).Font.Bold = True
Columns(1).Font.Bold = True
Range("A1:H1").Interior.Color = RGB(0, 176, 240)
Range("A2") = 1
Range("B2") = Date
'Range("C2") = "רשום כאן את השלב הראשון"
Range("G2") = 0
Range("H2") = 0
Range("N1:Q1").Merge
Range("N2:Q12").Merge
Range("N1:Q1").Interior.Color = RGB(0, 176, 240)
Range("N1:Q1") = "הערות"
'--------------------------------------------------------------------------------------------------הוספת מסגרת לתאים
Dim rng2 As Range
Set rng2 = Range(Cells(1, 14), Cells(12, 17))
With rng2.Borders
.LineStyle = xlContinuous
.Color = vbBlack
.Weight = xlThin
End With
Range("N:Q").HorizontalAlignment = xlCenter
Range("N:Q").VerticalAlignment = xlCenter
'--------------------------------------------------------------------------------------------------ספירת גיליונות בקובץ
Dim SheetCountA As Integer
SheetCountA = Application.Sheets.Count
'--------------------------------------------------------------------------------------------------העתקת כפתור חזרה לגיליון החדש
Sheets(SheetCountA - 1).Select
ActiveSheet.Shapes.Range(Array("Rectangle 1")).Select
Selection.Copy
Sheets(SheetCountA).Select
ActiveSheet.Paste Destination:=Worksheets(SheetCountA).Range("K1")
Sheets(SheetCountA - 1).Select
Range("B1").Copy
Sheets(SheetCountA).Select
Range("B1").PasteSpecial Paste:=xlPasteFormats
Application.CutCopyMode = False
Range("A1").Select
Sheets(SheetCountA - 1).Select
Range("A1").Select
Sheets("סיכום").Select
Dim LastRowA As Integer
LastRowA = Application.CountA(Range("B:B"))
'--------------------------------------------------------------------------------------------------הוספת מספור לפרויקט החדש
Cells(LastRowA + 1, 1) = Cells(LastRowA, 1) + 1
'--------------------------------------------------------------------------------------------------הוספת היפר-לינק
ActiveSheet.Hyperlinks.Add Anchor:=Cells(LastRowA + 1, 2), Address:="", SubAddress:= _
project_name & "!A1", TextToDisplay:=project_name
Cells(LastRowA + 1, 2).HorizontalAlignment = xlCenter
Cells(LastRowA + 1, 2).VerticalAlignment = xlCenter
Range("A1").Select
'--------------------------------------------------------------------------------------------------זמן סיום ריצת קוד וחישוב
Finish = Timer
TotalTime = Format((Finish - Start) / 86400, "hh:mm:ss")
MsgBox ("הדו''ח מוכן" & vbNewLine & "זמן ריצת קוד: " & TotalTime)
'--------------------------------------------------------------------------------------------------שאלה האם לעבור לקוד שמרענן את הקובץ
Dim answer2 As Integer
answer2 = MsgBox("?האם לרענן את הקובץ", vbYesNo + vbQuestion, "מעבר לקוד הבא")
If answer2 = vbYes Then
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.AskToUpdateLinks = True
Call Refresh_file
End If
'--------------------------------------------------------------------------------------------------שמירת הקובץ
ThisWorkbook.Save
'--------------------------------------------------------------------------------------------------החזרת חישובים ועדכוני מסך והתראות
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.AskToUpdateLinks = True
End Sub
To make the hyperlink valid, you just need to wrap the sheet name in quotes, so:
ActiveSheet.Hyperlinks.Add Anchor:=Cells(LastRowA + 1, 2), Address:="", SubAddress:= _
project_name & "!A1", TextToDisplay:=project_name
becomes
ActiveSheet.Hyperlinks.Add Anchor:=Cells(LastRowA + 1, 2), Address:="", SubAddress:="'" & _
project_name & "'" & "!A1", TextToDisplay:=project_name
Hello again guys I have another tough problem for you, well may not be tough for you but it is for me. So I have one sheet with all of my data and I would like to sort by the first 3 conditions (Reject, Other, & year) Would be nice to be able to pick months too. Once the data is filtered I have it copied and sorted on another sheet so I can do some other functions and generate a table showing amount of times the vendor was rejected. There may be a simpler way to do this but currently this is the way I slapped together. If you have any other suggestions I would like to hear them.Code fails at the year sort. I keep getting all of the data from the other sheet
''Generates defect list
Sub Make_Defect_List_Yearly()
Const REJECTED_COL = 8 'Column H (DISPOSITIO)
Const DATE_COL = 13
Dim shAD As Worksheet, shVP As Worksheet
Dim adRng As Range, vpRng As Range, headers() As Variant
Dim rng As Range, cel As Range, fCell As Range, lCell As Range
Dim flg As Byte, LastRow As Long, flag As Boolean, i
Set shAD = Worksheets("AllData")
Set shVP = Worksheets("VendorProblems")
lr = shAD.Cells(Rows.Count, 1).End(xlUp).Row
Sheets("VendorProblems").UsedRange.ClearContents
'Copy VendorProblems to shVP --------------------------
Application.ScreenUpdating = False
shAD.AutoFilterMode = False
With shAD.UsedRange
Set adRng = FilterWS(.Columns(DATE_COL), "2017")
If Not adRng Is Nothing Then
If .Cells.CountLarge > 2 Then
Set vpRng = shVP.Cells(shVP.UsedRange.Rows.Count + 1, 1)
.Offset(1).Resize(.Rows.Count - 1, .Columns.Count).Copy vpRng
End If
End If
End With
With shAD.UsedRange
Set adRng = FilterWS(.Columns(REJECTED_COL), "Reject")
If Not adRng Is Nothing Then
If .Cells.CountLarge > 2 Then
Set vpRng = shVP.Cells(shVP.UsedRange.Rows.Count + 1, 1)
.Offset(1).Resize(.Rows.Count - 1, .Columns.Count).Copy vpRng
End If
End If
End With
With shAD.UsedRange
Set adRng = FilterWS(.Columns(REJECTED_COL), "Other")
If Not adRng Is Nothing Then
If .Cells.CountLarge > 2 Then
Set vpRng = shVP.Cells(shVP.UsedRange.Rows.Count + 1, 1)
.Offset(1).Resize(.Rows.Count - 1, .Columns.Count).Copy vpRng
End If
End If
End With
shAD.AutoFilterMode = False
'shVP.UsedRange.RemoveDuplicates Columns:=1, Header:=xlNo
'Sort shVP ----------------------------------------------------
Set vpRng = shVP.UsedRange.Columns(11)
With shVP.Sort
.SortFields.Clear
.SetRange shVP.UsedRange
.SortFields.Add Key:=vpRng, SortOn:=xlSortOnValues, Order:=xlAscending
.Header = xlNo
.MatchCase = False
.Orientation = xlTopToBottom
.Apply
End With
'Remove blanks from shVP --------------------------------------
With shVP.UsedRange
shVP.AutoFilterMode = False
If Len(shVP.Cells(1)) = 0 Then shVP.Cells(1) = "Header": flg = 1
Set vpRng = FilterWS(shVP.UsedRange.Columns(11), "=")
If Not vpRng Is Nothing Then
Set vpRng = shVP.UsedRange.Columns(2).SpecialCells(xlCellTypeVisible)
If .Cells.Count > 1 Then .SpecialCells(xlCellTypeVisible).EntireRow.Delete
End If
If flg = 1 Then shVP.Cells(1).EntireRow.Delete
shVP.AutoFilterMode = False
End With
Application.ScreenUpdating = True
'Copys qty recieved to amnt rejected if amt rejected is blank
With shVP
lr = .Cells(.Rows.Count, "A").End(xlUp).Row
For Each cel In .Range("G2:G" & lr) 'loop through each cell in Column
If (cel.Value) = "" Then 'check Command Name
Set fCell = cel.Offset(0, -3) 'set first cell to be copied in fCell
Set lCell = cel.Offset(0, 0)
lCell = fCell
End If
Next cel
End With
'Sorts data alphabetically by vendor
Application.ScreenUpdating = True
shVP.Activate
Cells.Select
Range("A:P").Activate 'old line a118
With Selection
.HorizontalAlignment = xlGeneral
.WrapText = False
.AddIndent = False
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
shVP.Range("A1").Select
' Array of header labels
headers() = Array("Warehouse", "Inspection Type", "ItemID", "QtyReceived", "UOM", "Sample::Sample", "DefectFound", _
"Disposition", "PurchOrder", "DISTRIBUTOR", "Manufacturer", "Remarks", "Date", "Cost", "RejectCat", "Date")
' Row to insert
shVP.Activate
Range("A1").EntireRow.Insert
With shVP
For i = LBound(headers()) To UBound(headers())
.Cells(1, 1 + i).Value = headers(i)
Next i
.Rows(1).Font.Bold = True
End With
End Sub
My script moves data to excel template. Codewords is changed for relevant info.
All works well if TPLNR and AUFNR is filled. The cell is two rows in height. But if i leave AUFNR or TPLNR blank - cell height not ajusted. This is macro used to fill and adjust every row in table.
Sub Mac1()
'
' Mac1
'
Dim i As Integer
i = 12
'
Do While Range("L" & i).Value <> "THE END"
If Range("L" & i).Value = "M" Then
...
ElseIf Range("L" & i).Value = "T" Then
Range("A" & i & ":D" & i).Select
With Selection
.HorizontalAlignment = xlCenter
.Orientation = 0
.WrapText = True
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = True
End With
Selection.Merge
With Selection
.HorizontalAlignment = xlLeft
.VerticalAlignment = xlBottom
.WrapText = True
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = True
End With
Selection.Font.Italic = True
End If
i = i + 1
Loop
Call AutoFitMergedCellRowHeight
Columns("L:L").Select
Selection.Delete Shift:=xlToLeft
End Sub
Sub AutoFitMergedCellRowHeight()
Dim CurrentRowHeight As Single, MergedCellRgWidth As Single
Dim CurrCell As Range
Dim ActiveCellWidth As Single, PossNewRowHeight As Single
Dim StartCell As Range, c As Range, MergeRng As Range, Cell As Range
Dim a() As String, isect As Range, i
'Take a note of current active cell
Set StartCell = ActiveCell
'Create an array of merged cell addresses that have wrapped text
For Each c In ActiveSheet.UsedRange
If c.MergeCells Then
With c.MergeArea
If .Rows.Count = 1 And .WrapText = True Then
If MergeRng Is Nothing Then
Set MergeRng = c.MergeArea
ReDim a(0)
a(0) = c.MergeArea.Address
Else
Set isect = Intersect(c, MergeRng)
If isect Is Nothing Then
Set MergeRng = Union(MergeRng, c.MergeArea)
ReDim Preserve a(UBound(a) + 1)
a(UBound(a)) = c.MergeArea.Address
End If
End If
End If
End With
End If
Next c
Application.ScreenUpdating = False
'Loop thru merged cells
For i = 0 To UBound(a)
Range(a(i)).Select
With ActiveCell.MergeArea
If .Rows.Count = 1 And .WrapText = True Then
'Application.ScreenUpdating = False
CurrentRowHeight = .RowHeight
ActiveCellWidth = ActiveCell.ColumnWidth
For Each CurrCell In Selection
MergedCellRgWidth = CurrCell.ColumnWidth + MergedCellRgWidth
Next
.MergeCells = False
.Cells(1).ColumnWidth = MergedCellRgWidth
.EntireRow.AutoFit
PossNewRowHeight = .RowHeight
.Cells(1).ColumnWidth = ActiveCellWidth
.MergeCells = True
.RowHeight = IIf(CurrentRowHeight > PossNewRowHeight, _
CurrentRowHeight, PossNewRowHeight)
End If
End With
MergedCellRgWidth = 0
Next i
StartCell.Select
Application.ScreenUpdating = True
'Clean up
Set CurrCell = Nothing
Set StartCell = Nothing
Set c = Nothing
Set MergeRng = Nothing
Set Cell = Nothing
End Sub
What could i do to get rows after 12 to look like it intended to? With 1x height.
Making the rows equal size is quite a standard VBA task.
Just try to put this logic away from your code. The only 3 things you should know is the starting row, the ending row and the size. Thus, you may be able to do it quite well. In the code below change the parameters of Call AllRowsAreEqual(4, 10, 35) in order to make it work for you.
Option Explicit
Sub AllRowsAreEqual(lngStartRow As Long, lngEndRow As Long, lngSize)
Dim lngCounter As Long
For lngCounter = lngStartRow To lngEndRow
Cells(lngCounter, 1).RowHeight = lngSize
'Debug.Print lngCounter
Next lngCounter
End Sub
Public Sub Main()
Call AllRowsAreEqual(4, 10, 35)
End Sub
I am very new to VBA. Basically I have the following table on sheet 1
table 1
This gets updated daily with # emails we receive depending country / reason for contact.
At the end of the day I would like to assign a macro button that will copy and paste the data to sheet 2 by current date.
sheet 2
I wrote a dynamic solution to this:
Option Explicit
Option Base 1
Type EmailData
us As Object
ca As Object
End Type
Public Sub RunDataMove()
Dim wsDataFrom As Worksheet
Dim wsDataTo As Worksheet
Dim eData As EmailData
Dim i As Long
With Application
.ScreenUpdating = False
.DisplayAlerts = False
.EnableEvents = False
.Calculation = xlCalculationManual
End With
Set wsDataFrom = ThisWorkbook.Worksheets("DataFrom") 'Change Worksheet names
Set wsDataTo = ThisWorkbook.Worksheets("DataTo") 'Change Worksheet names
Set eData.us = CreateObject("Scripting.Dictionary")
Set eData.ca = CreateObject("Scripting.Dictionary")
With wsDataFrom
For i = 2 To .Cells.SpecialCells(xlCellTypeLastCell).Row
eData.us.Add .Cells(i, 3).Value, .Cells(i, 1).Value
eData.ca.Add .Cells(i, 3).Value, .Cells(i, 2).Value
Next i
End With
Call MoveDataByDate(wsDataTo, eData, DateAdd("d", 0, Date)) 'Change add days +/- if needed
With Application
.ScreenUpdating = True
.DisplayAlerts = True
.EnableEvents = True
.Calculation = xlCalculationAutomatic
End With
MsgBox "Data for " & Date & " has been moved or updated"
End Sub
Public Sub MoveDataByDate(ByRef wsTo As Worksheet, ByRef eData As EmailData, ByVal eDate As Date)
Dim obj As Variant, i As Long, usCol As Long, caCol As Long, dCol As Long, keyName As String
With wsTo
For i = 1 To .Cells.SpecialCells(xlCellTypeLastCell).Column
If .Cells(1, i).Value = eDate Then
dCol = i
usCol = i
caCol = i + 1
Exit For
End If
Next i
If dCol = 0 And i <> 1 Then
usCol = i
caCol = i + 1
Else
usCol = 2
caCol = 3
End If
If .Cells(3, 1).Value = "" Then
i = 3
For Each obj In eData.us
.Cells(i, 1).Value = obj
i = i + 1
Next obj
.Cells.EntireColumn.AutoFit
End If
For i = 3 To .Cells.SpecialCells(xlCellTypeLastCell).Row
keyName = .Cells(i, 1).Value
If eData.us.exists(keyName) Then
.Cells(i, usCol).Value = eData.us(keyName)
End If
If eData.ca.exists(keyName) Then
.Cells(i, caCol).Value = eData.ca(keyName)
End If
Next i
.Cells(1, usCol).Value = eDate
.Range(.Cells(1, usCol), .Cells(1, caCol)).Merge
.Cells(2, usCol).Value = "US"
.Cells(2, caCol).Value = "CA"
With .Range(.Cells(1, usCol), .Cells(.Cells.SpecialCells(xlCellTypeLastCell).Row, caCol))
.ColumnWidth = 8
.HorizontalAlignment = xlCenter
End With
End With
End Sub
I've been trying to add the entire row that meets the highlight criteria to an array but I've been struggling getting it to work.
The code loops through multiple identifiers and highlight them in red based off of the preconditions. I would like to add the entire row to an array for all rows meeting the precondition criteria.
Sub SWAPS101()
'red color
' If "Security Type" = SW
' If "New Position Ind" = N
' If "Prior Price" = 100
' If "Current Price" does not equal 100
Dim rng As Range, lCount As Long, LastRow As Long
Dim cell As Object
'Sheets("Output").Activate
With ActiveSheet
LastRow = .Cells(Rows.Count, 1).End(xlUp).Row
For Each cell In .Range("E2:E" & LastRow) 'new position
If cell = "N" And cell.Offset(, 16) = "SW" And cell.Offset(, 5) = 100 _
And cell.Offset(, 4) <> 100 Then
With cell.EntireRow.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 6382079
.TintAndShade = 0
.PatternTintAndShade = 0
End With
' LastRow = Range("b65000").End(xlUp).Row
' For r = 2 To LastRow
Row = Row + 1
TempArray(Row, 1) = Cells(r, cell))
Next r
End If
Next cell
End With
End Sub
Using the Range.CurrentRegion property to isolate the 'island' of data radiating out from A1 is an easy method to restrict the 'scope' of the operation. You do not want to be copying thousands of blank cells into an array.
Sub SWAPS101()
'red color
' If "Security Type" = SW
' If "New Position Ind" = N
' If "Prior Price" = 100
' If "Current Price" does not equal 100
Dim a As Long, r As Long, c As Long, vVALs As Variant
With Sheets("Output")
'reset the environment
If .AutoFilterMode Then .AutoFilterMode = False
.Columns(5).Interior.Pattern = xlNone
With .Cells(1, 1).CurrentRegion
ReDim vVALs(1 To .Columns.Count, 1 To 1)
.AutoFilter field:=Application.Match("security type", .Rows(1), 0), Criteria1:="SW"
.AutoFilter field:=Application.Match("new position ind", .Rows(1), 0), Criteria1:="N"
.AutoFilter field:=Application.Match("prior price", .Rows(1), 0), Criteria1:=100
.AutoFilter field:=Application.Match("current price", .Rows(1), 0), Criteria1:="<>" & 100
With .Resize(.Rows.Count - 1, .Columns.Count).Offset(1, 0)
'check to ensure that there is something to work with
If CBool(Application.Subtotal(103, .Cells)) Then
With Intersect(.Columns(5), .SpecialCells(xlCellTypeVisible))
.Cells.Interior.Color = vbRed
End With
Debug.Print .SpecialCells(xlCellTypeVisible).Areas.Count
With .SpecialCells(xlCellTypeVisible)
For a = 1 To .Areas.Count
Debug.Print .Areas(a).Rows.Count
For r = 1 To .Areas(a).Rows.Count
Debug.Print .Areas(a).Rows(r).Address(0, 0)
ReDim Preserve vVALs(1 To UBound(vVALs, 1), 1 To UBound(vVALs, 2) + 1)
For c = 1 To .Columns.Count
vVALs(c, UBound(vVALs, 2)) = _
.Areas(a).Rows(r).Cells(1, c).Value
Next c
Next r
Next a
vVALs = Application.Transpose(vVALs)
End With
'array is populated - do something with it
Debug.Print LBound(vVALs, 1) & ":" & UBound(vVALs, 1)
Debug.Print LBound(vVALs, 2) & ":" & UBound(vVALs, 2)
'this dumps the values starting a couple of rows down
With .Cells(.Rows.Count, 1).Offset(3, 0)
.Resize(UBound(vVALs, 1), UBound(vVALs, 2)) = vVALs
End With
End If
End With
End With
If .AutoFilterMode Then .AutoFilterMode = False
End With
End Sub
I've left a lot of the debug.print statements in so you can watch how the process loops through the rows of each Range.Areas property within the Range.SpecialCells method's xlCellTypeVisible set. Use F8 to step through the code while keeping an eye on the VBE's Immediate window ([Ctrl]+G).
Post-processing results
You can add ranges to an array, such as:
Dim myArray() As Variant 'declare an unallocated array.
myArray = Range("E2:E" & LastRow) 'myArray is now an allocated array, range being your row
My idea is to create union range uRng but I couldn't fill it in array so create temp sheet and past this range in it then fill the selection (the copied range) in array then delete this temp sheet.
this will work but I don't know if it is good way so this is just an idea because Jeeped answer seems the full answer for this question
Sub SWAPS101()
'red color
' If "Security Type" = SW
' If "New Position Ind" = N
' If "Prior Price" = 100
' If "Current Price" does not equal 100
Dim rng As Range, lCount As Long, LastRow As Long
Dim cell As Range
Dim TempArray As Variant, uRng As Range, tempSH As Worksheet
'Sheets("Output").Activate
With ActiveSheet
LastRow = .Cells(Rows.Count, 1).End(xlUp).Row
For Each cell In .Range("E2:E" & LastRow) 'new position
If cell = "N" And cell.Offset(, 16) = "SW" And cell.Offset(, 5) = 100 _
And cell.Offset(, 4) <> 100 Then
With cell.EntireRow.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 6382079
.TintAndShade = 0
.PatternTintAndShade = 0
End With
If uRng Is Nothing Then
Set uRng = cell.EntireRow
Else
Set uRng = Union(uRng, cell.EntireRow)
End If
End If
Next cell
End With
If Not uRng Is Nothing Then
Application.ScreenUpdating = False
Set tempSH = Sheets.Add
uRng.Copy
tempSH.Paste
TempArray = Selection.Value
Application.DisplayAlerts = False
tempSH.Delete
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End If
End Sub