VBA relative references - excel

New to VBA and just learning how to use relative references. I have an excel worksheet that will contain roughly 27 tables and I'll need to create 5 versions of this worksheet. The output from the tool I'm using is not in the format that's needed. Below is a screenshot of the output:
This is an example of what I'm trying to achieve:
Each of the tables in the worksheet will have a different number of rows. I've managed to get the code that bolds the question, centers the columns (from 'Total' to 'None') and highlights the different sections... but I can't get the code that bolds the row labels and percentages, or the row labeled 'column name.'
Here is my code for the first part:
Format Macro
'
' Keyboard Shortcut: Ctrl+Shift+F
'
ActiveCell.Select
Selection.Font.Bold = True
ActiveCell.Offset(2, 1).Range("A1:B1").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
With Selection
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlBottom
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
End With
ActiveCell.Offset(-1, 3).Range("A1:E1").Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorAccent2
.TintAndShade = 0.799981688894314
.PatternTintAndShade = 0
End With
ActiveCell.Offset(2, 0).Range("A1:E1").Select
Range(Selection, Selection.End(xlDown)).Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorAccent2
.TintAndShade = 0.799981688894314
.PatternTintAndShade = 0
End With
ActiveCell.Offset(-2, 8).Range("A1:B1").Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorAccent2
.TintAndShade = 0.799981688894314
.PatternTintAndShade = 0
End With
ActiveCell.Offset(2, 0).Range("A1").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorAccent2
.TintAndShade = 0.799981688894314
.PatternTintAndShade = 0
End With
ActiveCell.Offset(0, -11).Range("A1").Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlToLeft)).Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorAccent2
.TintAndShade = 0.799981688894314
.PatternTintAndShade = 0
End With
End Sub
Here's was my attempt to write the code for the bolding:
' Bold Macro
'
' Keyboard Shortcut: Ctrl+b
'
ActiveCell.Offset(3, 0).Range("A1").Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.Font.Bold = False
Selection.Font.Bold = True
ActiveCell.Offset(3, 0).Range("A1").Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.Font.Bold = False
Selection.Font.Bold = True
ActiveCell.Offset(3, 0).Range("A1").Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.Font.Bold = True
ActiveCell.Offset(3, 0).Range("A1").Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.Font.Bold = True
ActiveCell.Offset(3, 0).Range("A1").Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.Font.Bold = True
ActiveCell.Offset(3, 0).Range("A1").Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.Font.Bold = True
ActiveCell.Offset(3, 0).Range("A1").Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.Font.Bold = True
ActiveCell.Offset(3, 0).Range("A1").Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.Font.Bold = True
ActiveCell.Offset(3, 0).Range("A1").Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.Font.Bold = True
ActiveCell.Offset(3, 0).Range("A1").Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.Font.Bold = True
ActiveCell.Offset(3, 0).Range("A1").Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.Font.Bold = True
ActiveCell.Offset(3, 0).Range("A1").Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.Font.Bold = True
ActiveCell.Offset(3, 0).Range("A1").Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.Font.Bold = True
ActiveCell.Offset(3, 0).Range("A1").Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.Font.Bold = True
End Sub
I've included a link to a sample file for reference.

It isn't in "relative referencing" where your problems lie but in referencing. Take this code.
Dim Ws As WorkSheet
Dim Rng As Range
Set Ws = Worksheets("Sheet1")
Set Rng = Ws.Cells(1, "A").Resize(2, 10)
The code first declares two objects, meaning, names are given. This simple setup allows you to avoid all "Select" or "Activate" statements and does away with all references to the ActiveSheet or the Selection object. That's about half your code.
Having defined the worksheet and given it a name you can refer to any cell on it, like Ws.Cells(13, "C").Font.Bold = True. Note that Cells(13, "C") could also (better) be addressed as Cells(13, 3). You can change the name of that sheet, like Ws.Name = "My New Name" and still refer to it in your code as Ws. You can specify ranges in it as shown above, either by specifying an offset (as the Resize method does) or by simply specifying first and last cell.
Set Rng = Ws.Range("A1:C37")
or
Set Rng = Ws.Range(Ws.Cells(1, 1), Ws.Cells(37, "A"))
which would usually be written like this:-
With Ws
Set Rng = .Range(.Cells(1, 1), .Cells(37, 1))
End With
You can also use the worksheet object to identify tables in the worksheet.
Dim Tbl As ListObject
Set Tbl = Ws.ListObjects(1)
or
Set Tbl = Ws.ListObjects("Table1")
That new object gives you access to all sorts of cells.
Set Rng = Tbl.DataBodyRange ' all the data below the header row
Set Rng = Tbl.HeaderRowRange ' the row with captions
Set Rng = Tbl.Range ' all of the table
Within each range cells are accessible by their row and column or by their index number. Tbl.Range.Cells(1) is the same as Tbl.Range.Cells(1, 1) or Tbl.HeaderRowRange.Cells(1). Each of these cells has a Font object which has a Bold property which you can set without ever selecting anything. And you might still refer to any of them by their worksheet coordinates.
Enough. Please take it from here.

Related

Cut/paste based off of RBG color

The first macro creates four worksheets, names them, then searches the original worksheet for string words and colors them based off of RBG and sort them. I never have an issue running this macro.
My second macro should cut/paste things into their specified worksheet. It never works.
Macro 1 that creates worksheets, color codes, and sorts.
Sub MacroTest3()
' MacroTest3 Macro
'
'
Sheets.Add After:=ActiveSheet
Sheets("Sheet1").Select
Sheets("Sheet1").Name = "DNIF"
Sheets.Add After:=ActiveSheet
Sheets("Sheet2").Select
Sheets("Sheet2").Name = "Wx"
Sheets.Add After:=ActiveSheet
Sheets("Sheet3").Select
Sheets("Sheet3").Name = "Preg"
Sheets.Add After:=ActiveSheet
Sheets("Sheet4").Select
Sheets("Sheet4").Name = "<30"
Range("G34").Select
Sheets("Down Weekly").Select
Range("A1:A2").Select
Selection.Copy
Cells.Select
Application.CutCopyMode = False
Selection.Copy
Sheets("DNIF").Select
ActiveSheet.Paste
Columns("C:C").Select
Application.CutCopyMode = False
Selection.Delete Shift:=xlToLeft
Columns("D:F").Select
Selection.Delete Shift:=xlToLeft
Columns("E:I").Select
Selection.Delete Shift:=xlToLeft
Columns("G:G").Select
Selection.Delete Shift:=xlToLeft
Rows("1:3").Select
Selection.Delete Shift:=xlUp
Cells.Select '------ selects all cell command!
'------------------------------------------------------------------------------'
' Looks for string "Waiver Log" then colors it Yellow
Selection.FormatConditions.Add Type:=xlTextString, String:="Waiver Log", _
TextOperator:=xlContains
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.Color = RGB(255, 255, 0)
.TintAndShade = 0
End With
'------------------------------------------------------------------------------'
' Looks for string "Waiver Hold" then colors it Yellow
Selection.FormatConditions.Add Type:=xlTextString, String:="Waiver Hold", _
TextOperator:=xlContains
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.Color = RGB(255, 255, 0)
.TintAndShade = 0
End With
'------------------------------------------------------------------------------'
' Looks for string "Pregn" then colors it Red
Selection.FormatConditions(1).StopIfTrue = False
Selection.FormatConditions.Add Type:=xlTextString, String:="Pregn", _
TextOperator:=xlContains
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.Color = RGB(255, 0, 0)
.TintAndShade = 0
End With
'---------------------------------------------------------------------------------'
' Sorts less than 30 days then colors cels orange
Columns("D:D").Select
Selection.FormatConditions.Add Type:=xlExpression, Formula1:= _
"=D2>TODAY()-31"
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.Color = RGB(255, 192, 0)
End With
Selection.FormatConditions(1).StopIfTrue = False
'---------------------------------------------------------------------------------'
' Sorts Red cells to the top, yellow cells bellow it:
Sheets("DNIF").Select
Range("A1:G1").Select
Selection.AutoFilter
ActiveWorkbook.Worksheets("DNIF").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("DNIF").Sort.SortFields.Add(Range("G2:G1000"), _
xlSortOnCellColor, xlAscending, , xlSortNormal).SortOnValue.Color = RGB(255, 0 _
, 0)
ActiveWorkbook.Worksheets("DNIF").Sort.SortFields.Add(Range("G2:G1000"), _
xlSortOnCellColor, xlAscending, , xlSortNormal).SortOnValue.Color = RGB(255, _
255, 0)
ActiveWorkbook.Worksheets("DNIF").Sort.SortFields.Add(Range("D2:D1000"), _
xlSortOnCellColor, xlAscending, , xlSortNormal).SortOnValue.Color = RGB(255, _
192, 0)
With ActiveWorkbook.Worksheets("DNIF").Sort
.SetRange Range("A1:G1000")
.Header = xlYes
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
'-----------------------------------------------------------------------'
' Copies the headers onto the different worksheets
Range("A1:G1").Select
Selection.Copy
Sheets("Wx").Select
ActiveSheet.Paste
Sheets("Preg").Select
Range("A1").Select
ActiveSheet.Paste
Sheets("<30").Select
Range("A1").Select
ActiveSheet.Paste
End Sub
Second Macro to cut/paste rows based off of RBG color
Sub Copier()
Dim TransIDField As Range
Dim TransIDCell As Range
Dim OriginSheet As Worksheet
Dim TargetSheet As Worksheet
Dim TargetSheet2 As Worksheet
Set OriginSheet = Worksheets("Down Weekly")
Set TransIDField = OriginSheet.Range("G2", OriginSheet.Range("G2").End(xlDown))
Set TargetSheet = Worksheets("Preg")
Set TargetSheet2 = Worksheets("Wx")
For Each TransIDCell In TransIDField
If TransIDCell.Interior.Color = RGB(255, 0, 0) Then
TransIDCell.Resize(1, 7).Cut Destination:= _
TargetSheet.Range("A1").Offset(TargetSheet.Rows.Count - 1,
0).End(xlUp).Offset(1, 0)
End If
Next TransIDCell
For Each TransIDCell In TransIDField
If TransIDCell.Interior.Color = RGB(255, 255, 0) Then
TransIDCell.Resize(1, 7).Cut Destination:= _
TargetSheet2.Range("A1").Offset(TargetSheet2.Rows.Count - 1,
0).End(xlUp).Offset(1, 0)
End If
Next TransIDCell
End Sub

Dynamic row selection

I want to execute a series of code based on row number but want to keep the selection of row number flexible, so that i can execute code for row 15:15, 20:20 etc
here is the code i tried...
Dim i As Integer
i = 15
Rows("i:i").Select
Selection.Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Rows("i-1:i-1").Select
Selection.Copy
Rows("i:i").Select
ActiveSheet.Paste
Rows("i:i").Select
Application.CutCopyMode = False
With Selection.Interior
.PatternColorIndex = xlAutomatic
.Color = 65535
.TintAndShade = 0
.PatternTintAndShade = 0
End With
Range("Ei-1").Select
Selection.ClearContents
Range("Ei-1").Select
ActiveCell.FormulaR1C1 = "=RC[-1]+(R[1]C-RC[-1])/2"
Range("Ei").Select
Something like this:
Dim i As Long
i = 15
Rows(i).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
Rows(i - 1).Copy Rows(i)
With Rows(i).Interior
.PatternColorIndex = xlAutomatic
.Color = 65535
.TintAndShade = 0
.PatternTintAndShade = 0
End With
Range("E" & i - 1).FormulaR1C1 = "=RC[-1]+(R[1]C-RC[-1])/2"

I need someone's help to consolidate my vba code for a spreadsheet at work

so I've been writing a code at my work to take a .csv file and pull data from it into datasheets that already have specified columns. I've never taken any kind of vba courses or anything, it's all just what I've found from forums modpodged together. Currently, it works but occasionally it breaks and crashes excel. From what I've found it looks like I need to consolidate it so I'm posting it here to see if there's someone with more knowledge who could help me do that. It was very complicated. Some of the issues I had was copying from an unmerged cell to merged cell, using a single cell to change the file path that is opening the file as a new datasheet, and using InStr to search for the correct column of cells to pull the data from. Also, sometimes there is only one dataset, in those cases I needed to be able to pull that data but using xldown was selecting all cells, so I created an if statement. See the code below.
''Finds data from results and brings it into datasheet
Sub Update_Data_Click()
''Sets up Variables
Dim Job As String
Dim Year As String
Dim Folder As String
Dim TestResults As String
Dim Sh As Worksheet
Dim DestSh As Worksheet
Dim Last As Long
Dim SampleID As Range
Dim UTS As Range
Dim YS As Range
Dim ELG As Range
Dim UTF As Range
Dim YF As Range
Worksheets("Tensile Ext").Rows(37 & ":" & Worksheets("Tensile Ext").Rows.Count).Delete
Worksheets("Tensile Ext").Rows("21:36").ClearContents
''Change year here each year
Job = Range("S2")
Year = 2020
Folder = "D-MaterialsTesting"
TestResults = "TestResults"
''Finds Job folder with from support data
Application.ScreenUpdating = False
Workbooks.OpenText Filename:="S:" & "\" & Folder & "\" & Year & "\" & Job & "\" & "TestResults" & ".csv", DataType:=xlDelimited, comma:=True
With ActiveWorkbook
.ActiveSheet.Copy After:=ThisWorkbook.Sheets(Sheets.Count)
.Close
End With
Cells.Select
Cells.EntireColumn.AutoFit
Sheets("TestResults").Select
Range("A2").Select
If ActiveSheet.UsedRange.Rows.Count = 2 Then
''Copies Sample ID Data from TestResults Datasheet
Sheets("Tensile Ext").Select
Range("A21").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.UnMerge
Sheets("TestResults").Select
For Each SampleID In Range("A1:I1")
DoEvents
If InStr(SampleID.Value, "Sample ID") > 0 Then
SampleID.Offset(1, 0).Select
Selection.Copy
Sheets("Tensile Ext").Select
Range("A21").Select
ActiveSheet.Paste
End If
Next SampleID
Range("A21:D21").Select
With Selection
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlBottom
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
.Borders.LineStyle = xlContinuous
End With
Selection.Merge
Selection.AutoFill Destination:=Range(Selection, Selection.End(xlDown)), Type:=xlFillDefault
''Copies Ultimate Force from TestResults Datasheet
Sheets("Tensile Ext").Select
Range("N21").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.UnMerge
Sheets("TestResults").Select
For Each UTF In Range("A1:I1")
If InStr(UTF.Value, "Ultimate Force") > 0 Then
UTF.Offset(1, 0).Select
Selection.Copy
Sheets("Tensile Ext").Select
Range("N21").Select
ActiveSheet.Paste
End If
Next UTF
Range("N21:Q21").Select
With Selection
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlBottom
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
.Borders.LineStyle = xlContinuous
End With
Selection.Merge
Selection.AutoFill Destination:=Range(Selection, Selection.End(xlDown)), Type:=xlFillDefault
''Copies Yield Force Data from TestResults Datasheet
Sheets("Tensile Ext").Select
Range("R21").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.UnMerge
Sheets("TestResults").Select
For Each YF In Range("A1:I1")
If InStr(YF.Value, "Offset Force") > 0 Then
YF.Offset(1, 0).Select
Selection.Copy
Sheets("Tensile Ext").Select
Range("R21").Select
ActiveSheet.Paste
End If
Next YF
Range("R21:U21").Select
With Selection
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlBottom
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
.Borders.LineStyle = xlContinuous
End With
Selection.Merge
Selection.AutoFill Destination:=Range(Selection, Selection.End(xlDown)), Type:=xlFillDefault
''Copies Ultimate Stress Data from TestResults Datasheet
Sheets("Tensile Ext").Select
Range("V21").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.UnMerge
Sheets("TestResults").Select
For Each UTS In Range("A1:I1")
If InStr(UTS.Value, "Ultimate Stress") > 0 Then
UTS.Offset(1, 0).Select
Selection.Copy
Sheets("Tensile Ext").Select
Range("V21").Select
ActiveSheet.Paste
End If
Next UTS
Range("V21:Y21").Select
With Selection
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlBottom
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
.Borders.LineStyle = xlContinuous
End With
Selection.Merge
Selection.AutoFill Destination:=Range(Selection, Selection.End(xlDown)), Type:=xlFillDefault
''Copies Yield Stress Data from TestResults Datasheet
Sheets("Tensile Ext").Select
Range("Z21").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.UnMerge
Sheets("TestResults").Select
For Each YS In Range("A1:I1")
If InStr(YS.Value, "Offset Stress") > 0 Then
YS.Offset(1, 0).Select
Selection.Copy
Sheets("Tensile Ext").Select
Range("Z21").Select
ActiveSheet.Paste
End If
Next YS
Range("Z21:AC21").Select
With Selection
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlBottom
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
.Borders.LineStyle = xlContinuous
End With
Selection.Merge
Selection.AutoFill Destination:=Range(Selection, Selection.End(xlDown)), Type:=xlFillDefault
''Copies Elongation Data from TestResults Datasheet
Sheets("Tensile Ext").Select
Range("AD21").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.UnMerge
Sheets("TestResults").Select
For Each ELG In Range("A1:I1")
If InStr(ELG.Value, "Elongation") > 0 Then
ELG.Offset(1, 0).Select
Selection.Copy
Sheets("Tensile Ext").Select
Range("AD21").Select
ActiveSheet.Paste
End If
Next ELG
Range("AD21:AE21").Select
With Selection
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlBottom
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
.Borders.LineStyle = xlContinuous
End With
Selection.Merge
Selection.AutoFill Destination:=Range(Selection, Selection.End(xlDown)), Type:=xlFillDefault
''This deletes copied Worksheet
Application.DisplayAlerts = False
Sheets("TestResults").Delete
Application.DisplayAlerts = True
Application.ScreenUpdating = True
ElseIf Range(Selection, Selection.End(xlDown)).Count < 2000 Then
''Copies Sample ID Data from TestResults Datasheet
Sheets("Tensile Ext").Select
Range("A21").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.UnMerge
Sheets("TestResults").Select
For Each SampleID In Range("A1:I1")
If InStr(SampleID.Value, "Sample ID") > 0 Then
SampleID.Offset(1, 0).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Sheets("Tensile Ext").Select
Range("A21").Select
Range(Selection, Selection.End(xlDown)).Select
ActiveSheet.Paste
End If
Next SampleID
Range("A21:D21").Select
With Selection
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlBottom
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
.Borders.LineStyle = xlContinuous
End With
Selection.Merge
Selection.AutoFill Destination:=Range(Selection, Selection.End(xlDown)), Type:=xlFillDefault
''Copies Ultimate Force Data from TestResults Datasheet
Sheets("Tensile Ext").Select
Range("N21").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.UnMerge
Sheets("TestResults").Select
For Each UTF In Range("A1:I1")
If InStr(UTF.Value, "Ultimate Force") > 0 Then
UTF.Offset(1, 0).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Sheets("Tensile Ext").Select
Range("N21").Select
Range(Selection, Selection.End(xlDown)).Select
ActiveSheet.Paste
End If
Next UTF
Range("N21:Q21").Select
With Selection
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlBottom
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
.Borders.LineStyle = xlContinuous
End With
Selection.Merge
Selection.AutoFill Destination:=Range(Selection, Selection.End(xlDown)), Type:=xlFillDefault
''Copies Yield Force Data from TestResults Datasheet
Sheets("Tensile Ext").Select
Range("R21").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.UnMerge
Sheets("TestResults").Select
For Each YF In Range("A1:I1")
If InStr(YF.Value, "Offset Force") > 0 Then
YF.Offset(1, 0).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Sheets("Tensile Ext").Select
Range("R21").Select
Range(Selection, Selection.End(xlDown)).Select
ActiveSheet.Paste
End If
Next YF
Range("R21:U21").Select
With Selection
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlBottom
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
.Borders.LineStyle = xlContinuous
End With
Selection.Merge
Selection.AutoFill Destination:=Range(Selection, Selection.End(xlDown)), Type:=xlFillDefault
''Copies Ultimate Stress Data from TestResults Datasheet
Sheets("Tensile Ext").Select
Range("V21").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.UnMerge
Sheets("TestResults").Select
For Each UTS In Range("A1:I1")
If InStr(UTS.Value, "Ultimate Stress") > 0 Then
UTS.Offset(1, 0).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Sheets("Tensile Ext").Select
Range("V21").Select
Range(Selection, Selection.End(xlDown)).Select
ActiveSheet.Paste
End If
Next UTS
Range("V21:Y21").Select
With Selection
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlBottom
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
.Borders.LineStyle = xlContinuous
End With
Selection.Merge
Selection.AutoFill Destination:=Range(Selection, Selection.End(xlDown)), Type:=xlFillDefault
''Copies Yield Stress Data from TestResults Datasheet
Sheets("Tensile Ext").Select
Range("Z21").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.UnMerge
Sheets("TestResults").Select
For Each YS In Range("A1:I1")
If InStr(YS.Value, "Offset Stress") > 0 Then
YS.Offset(1, 0).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Sheets("Tensile Ext").Select
Range("Z21").Select
Range(Selection, Selection.End(xlDown)).Select
ActiveSheet.Paste
End If
Next YS
Range("Z21:AC21").Select
With Selection
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlBottom
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
.Borders.LineStyle = xlContinuous
End With
Selection.Merge
Selection.AutoFill Destination:=Range(Selection, Selection.End(xlDown)), Type:=xlFillDefault
''Copies Elongation Data from TestResults Datasheet
Sheets("Tensile Ext").Select
Range("AD21").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.UnMerge
Sheets("TestResults").Select
For Each ELG In Range("A1:I1")
If InStr(ELG.Value, "Elongation") > 0 Then
ELG.Offset(1, 0).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Sheets("Tensile Ext").Select
Range("AD21").Select
Range(Selection, Selection.End(xlDown)).Select
ActiveSheet.Paste
End If
Next ELG
Range("AD21:AE21").Select
With Selection
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlBottom
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
.Borders.LineStyle = xlContinuous
End With
Selection.Merge
Selection.AutoFill Destination:=Range(Selection, Selection.End(xlDown)), Type:=xlFillDefault
''This deletes copied Worksheet
Application.DisplayAlerts = False
Sheets("TestResults").Delete
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End If
End Sub
Your code is far too voluminous to lend itself to q quick review. You earned kudos for being self-taught but, well, not quite enough when considering the volume of your code.
To avoid such comments in the future, please learn to split your code into a Main of perhaps 20 or 30 lines which calls subs and functions, each of them not longer than 15 to 20 lines as a rule of thumb.
So, I started reviewing your code and advised you "don't select or activate anything". If you heed this advice your code will shrink by about half. Then I found a huge block of code which is repetitive. For that I created a sub-routine which is then called six times with different parameters. This is where you learn to handle repetitions.
After that I encountered an ElseIf that I hadn't found before. I added a comment at the If to the effect that the IF block was too large. I was right in that. Then I saw what appeared to be another series of repetitions which caused me to draw a balance.
The changes I made are far too significant to have been accomplished without error. My code needs testing which I can't do due to lack of data.
Setting up another sub-routine will be exactly what you need to learn. No benefit for you in my doing it.
Nobody is better suited to resolve the ElseIf than yourself. This project needs to return to your care. Here it is - as it is. But one more note before I go: You can "recycle" variables of the same type. For example, your ranges UTF and UTS do not seem to need to keep their originally assigned values. So, one variable can probably do the job of them both, one job after the other. Once you don't need the value anymore the variable can be re-assigned to another use.
Sorry, I didn't manage to get all the code between code tags. The system wouldn't do it. Plese just copy everything below this paragraph and sort the lines in your VB Editor.
Sub Update_Data_Click()
Dim WsTe As Worksheet ' "Tensile Ext"
Dim WsTr As Worksheet ' "Test Result"
Dim Job As String
Dim Year As String
Dim Folder As String
Dim TestResults As String
Dim Sh As Worksheet
Dim DestSh As Worksheet
Dim Last As Long
Dim SampleID As Range
Dim UTS As Range, UTF As Range
Dim YS As Range, YF As Range
Dim ELG As Range
Dim Tmp As Variant ' for intermediate use
Set WsTe = Worksheets("Tensile Ext") ' it seems you will use this sheet again
Set WsTr = Worksheets("TestResult") ' list Ws declarations together for easy reference
With WsTe
' determine last used row in column A
Last = .Cells(.Rows.Count, "A").End(xlUp).Row
' deleting 1.4 million rows is both excessive and impossible
' .Rows(37 & ":" & .Rows.Count).Delete
.Range(.Rows(37), .Rows(Last)).Delete
.Rows("21:36").ClearContents
End With
Job = Range("S2").Value ' always specify the property
Year = 2020 ' Change year here each year
Folder = "D-MaterialsTesting"
TestResults = "TestResults"
' Find Job folder with from support data
Application.ScreenUpdating = False
' creating the string before you use it makes code
' more readable and easier to trouble shoot
Tmp = "S:" & "\" & Folder & "\" & Year & "\" & Job & "\" & "TestResults" & ".csv"
Workbooks.OpenText Filename:=Tmp, DataType:=xlDelimited, Comma:=True
With ActiveWorkbook
' I would prefer Worksheets(1).Copy
' effectively, there is no telling which sheet will be active
.ActiveSheet.Copy After:=ThisWorkbook.Sheets(Sheets.Count)
.Close
End With
' big mistake here!
' Worksheet isn't identified, which specifies the ActiveSheet
' I presume this to be WsTe most of the time but it's a lottery
' Cells.Select ' don't Select anything
Cells.EntireColumn.AutoFit
' don't select or activate anything!
' instead, name the worksheets and address them by your variable names
' Sheets("TestResults").Select
' Range("A2").Select
' this IF block is too large, perhaps therefore also End If misplaced
' UsedRange is unreliable!
' If ActiveSheet.UsedRange.Rows.Count = 2 Then
With WsTr
' using column A to determine last used row
If .Cells(.Rows.Count, "A").End(xlUp).Row > 2 Then GoTo Skip
End With
CopyResultData "Sample ID", WsTe.Range("A21:D21"), WsTe, WsTr
CopyResultData "Ultimate Force", WsTe.Range("N21:Q21"), WsTe, WsTr
CopyResultData "Offset Force", WsTe.Range("R21:U21"), WsTe, WsTr
CopyResultData "Ultimate Stress", WsTe.Range("V21:Y21"), WsTe, WsTr
CopyResultData "Offset Stress", WsTe.Range("Z21:AC21"), WsTe, WsTr
CopyResultData "Elongation", WsTe.Range("AD21:AE21"), WsTe, WsTr
' ============================================================
' This is where I terminated my review
' The ElseIf below isn't connected to any IF above.
' ============================================================
''This deletes copied Worksheet
Application.DisplayAlerts = False
Sheets("TestResults").Delete
Application.DisplayAlerts = True
Application.ScreenUpdating = True
ElseIf Range(Selection, Selection.End(xlDown)).Count < 2000 Then
''Copies Sample ID Data from TestResults Datasheet
Sheets("Tensile Ext").Select
Range("A21").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.UnMerge
Sheets("TestResults").Select
For Each SampleID In Range("A1:I1")
If InStr(SampleID.Value, "Sample ID") > 0 Then
SampleID.Offset(1, 0).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Sheets("Tensile Ext").Select
Range("A21").Select
Range(Selection, Selection.End(xlDown)).Select
ActiveSheet.Paste
End If
Next SampleID
Range("A21:D21").Select
With Selection
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlBottom
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
.Borders.LineStyle = xlContinuous
End With
Selection.Merge
Selection.AutoFill Destination:=Range(Selection, Selection.End(xlDown)), Type:=xlFillDefault
''Copies Ultimate Force Data from TestResults Datasheet
Sheets("Tensile Ext").Select
Range("N21").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.UnMerge
Sheets("TestResults").Select
For Each UTF In Range("A1:I1")
If InStr(UTF.Value, "Ultimate Force") > 0 Then
UTF.Offset(1, 0).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Sheets("Tensile Ext").Select
Range("N21").Select
Range(Selection, Selection.End(xlDown)).Select
ActiveSheet.Paste
End If
Next UTF
Range("N21:Q21").Select
With Selection
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlBottom
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
.Borders.LineStyle = xlContinuous
End With
Selection.Merge
Selection.AutoFill Destination:=Range(Selection, Selection.End(xlDown)), Type:=xlFillDefault
''Copies Yield Force Data from TestResults Datasheet
Sheets("Tensile Ext").Select
Range("R21").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.UnMerge
Sheets("TestResults").Select
For Each YF In Range("A1:I1")
If InStr(YF.Value, "Offset Force") > 0 Then
YF.Offset(1, 0).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Sheets("Tensile Ext").Select
Range("R21").Select
Range(Selection, Selection.End(xlDown)).Select
ActiveSheet.Paste
End If
Next YF
Range("R21:U21").Select
With Selection
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlBottom
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
.Borders.LineStyle = xlContinuous
End With
Selection.Merge
Selection.AutoFill Destination:=Range(Selection, Selection.End(xlDown)), Type:=xlFillDefault
''Copies Ultimate Stress Data from TestResults Datasheet
Sheets("Tensile Ext").Select
Range("V21").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.UnMerge
Sheets("TestResults").Select
For Each UTS In Range("A1:I1")
If InStr(UTS.Value, "Ultimate Stress") > 0 Then
UTS.Offset(1, 0).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Sheets("Tensile Ext").Select
Range("V21").Select
Range(Selection, Selection.End(xlDown)).Select
ActiveSheet.Paste
End If
Next UTS
Range("V21:Y21").Select
With Selection
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlBottom
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
.Borders.LineStyle = xlContinuous
End With
Selection.Merge
Selection.AutoFill Destination:=Range(Selection, Selection.End(xlDown)), Type:=xlFillDefault
''Copies Yield Stress Data from TestResults Datasheet
Sheets("Tensile Ext").Select
Range("Z21").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.UnMerge
Sheets("TestResults").Select
For Each YS In Range("A1:I1")
If InStr(YS.Value, "Offset Stress") > 0 Then
YS.Offset(1, 0).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Sheets("Tensile Ext").Select
Range("Z21").Select
Range(Selection, Selection.End(xlDown)).Select
ActiveSheet.Paste
End If
Next YS
Range("Z21:AC21").Select
With Selection
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlBottom
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
.Borders.LineStyle = xlContinuous
End With
Selection.Merge
Selection.AutoFill Destination:=Range(Selection, Selection.End(xlDown)), Type:=xlFillDefault
''Copies Elongation Data from TestResults Datasheet
Sheets("Tensile Ext").Select
Range("AD21").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.UnMerge
Sheets("TestResults").Select
For Each ELG In Range("A1:I1")
If InStr(ELG.Value, "Elongation") > 0 Then
ELG.Offset(1, 0).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Sheets("Tensile Ext").Select
Range("AD21").Select
Range(Selection, Selection.End(xlDown)).Select
ActiveSheet.Paste
End If
Next ELG
Range("AD21:AE21").Select
With Selection
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlBottom
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
.Borders.LineStyle = xlContinuous
End With
Selection.Merge
Selection.AutoFill Destination:=Range(Selection, Selection.End(xlDown)), Type:=xlFillDefault
''This deletes copied Worksheet
Application.DisplayAlerts = False
Sheets("TestResults").Delete
Application.DisplayAlerts = True
Skip:
Application.ScreenUpdating = True
End Sub
Private Sub CopyResultData(Itm As String, _
Rng As Range, _
WsTe As Worksheet, _
WsTr As Worksheet)
' Copies Itm Data from TestResults Datasheet
Dim Cell As Range
With WsTe
' next 9 lines are your original code which I commented
' and moved from your Main sub here.
' Just to show the development. Take note and delete:-
' Sheets("Tensile Ext").Select ' don't select anything
' Range("A21").Select
' Range(Selection, Selection.End(xlDown)).Select
' Selection.UnMerge
' ' xlDown will find the first empty cell after A21
' ' your code includes that blank cell in the unmerge
' .Range(.Cells(21, "A"), .Cells(21, "A").End(xlDown)).UnMerge
' ' xlUp will find the first non-empty cell above "A" last row
'' .Range(.Cells(21, "A"), .Cells(.Rows.Count, "A").End(xlUp)).UnMerge
' the next 3 lines perform the same work as the above
' but within the requirement of this procedure
.Range(Rng.Cells(1), Rng.Cells(1).End(xlDown)).UnMerge
' use either the above or the below
' .Range(Rng.Cells(1), Rng.Cells(1).End(xlUp)).UnMerge
End With
' Sheets("TestResults").Select ' don't select anything
For Each Cell In WsTr.Range("A1:I1")
' DoEvents ' why's that?
If InStr(Cell.Value, Itm) > 0 Then
' Cell.Offset(1, 0).Select
' Selection.Copy
Cell.Offset(1, 0).Copy _
Destination:=WsTe.Cells(WsTe.Rows.Count, Rng.Column).End(xlUp).Offset(1)
' Sheets("Tensile Ext").Select
' Range("A21").Select ' this will always paste to the same cell
' I changed that
' the next line pastes to A21 as per your original code
' Cell.Offset(1, 0).Copy Destination:=Rng.Cells(1)
' ActiveSheet.Paste
End If
' consider HLOOKUP instead of the above entire IF block
' On Error Resume Next ' in case not found
' Tmp = Application.HLookup(Itm, WsTr.Range("A1:I2"), 2, False)
' If Err.Number = 0 Then
' WsTe.Cells(WsTe.Rows.Count, "A").End(xlUp).Offset(1).Value = Tmp
' End If
Next Cell
On Error GoTo 0 ' only needed if HLOOKUP is deployed
' Range("A21:D21").Select ' don't select anything
With Rng
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlBottom
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
.MergeCells = False
.Borders.LineStyle = xlContinuous
.Merge
' not sure what this will do. Looks faulty:-
' you are applying AutoFill to a range both smaller (in width)
' and larger (potentially - in height) than the source cell
' of your AutoFill, which is probably blank!
.AutoFill Destination:=WsTe.Range(.Cells(1), .Cells(1).End(xlDown)), Type:=xlFillDefault
End With
' Selection.Merge
' Selection.AutoFill Destination:=Range(Selection, Selection.End(xlDown)), Type:=xlFillDefault
End Sub
So I've updated my code quite a bit to make subroutines for the repetitive portions. Below is my new code. I left one loop in the main code only because it had the formatting for the rowheight and I didn't want every single paste to go through that change. It shortened the runtime a bit. When I have a large amount of samples it still takes a long time, maybe you guys can see what I'm missing. Maybe there's a way to format all the cells the same way at one time? I'm not sure.
''Finds data from results and brings it into datasheet
Sub Update_Data_Click()
''Sets up Variables
Dim Job As String
Dim Year As String
Dim Folder As String
Dim TestResults As String
Dim Sh As Worksheet
Dim DestSh As Worksheet
Dim Last As Long
Dim Tst As Range
Dim Row As Long
Dim i As Long
Worksheets("Tensile Ext").Rows(37 & ":" & Worksheets("Tensile Ext").Rows.Count).Delete
Worksheets("Tensile Ext").Range("A21:D36").ClearContents
Worksheets("Tensile Ext").Range("N21:AG36").ClearContents
''Change year here each year
Job = Range("S2")
Year = 2020
Folder = "D-MaterialsTesting"
TestResults = "TestResults"
''Finds Job folder with from support data
Application.ScreenUpdating = False
Workbooks.OpenText Filename:="S:" & "\" & Folder & "\" & Year & "\" & Job & "\" & "TestResults" & ".csv", DataType:=xlDelimited, comma:=True
With ActiveWorkbook
.ActiveSheet.Copy After:=ThisWorkbook.Sheets(Sheets.Count)
.Close
End With
Sheets("TestResults").Select
Range("A2").Select
If ActiveSheet.UsedRange.Rows.Count = 2 Then
''Copies Sample ID Data from TestResults Datasheet
Call CopyResultData1("A21", "A21:D21", "Sample ID")
''Copies Ultimate Force from TestResults Datasheet
Call CopyResultData1("N21", "N21:Q21", "Ultimate Force")
''Copies Yield Force Data from TestResults Datasheet
Call CopyResultData1("R21", "R21:U21", "Offset Force")
''Copies Ultimate Stress Data from TestResults Datasheet
Call CopyResultData1("V21", "V21:Y21", "Ultimate Stress")
''Copies Yield Stress Data from TestResults Datasheet
Call CopyResultData1("Z21", "Z21:AC21", "Offset Stress")
''Copies Elongation Data from TestResults Datasheet
Call CopyResultData1("AD21", "AD21:AE21", "Elongation")
''This deletes copied Worksheet
Application.DisplayAlerts = False
Sheets("TestResults").Delete
Application.DisplayAlerts = True
Application.ScreenUpdating = True
ElseIf Range(Selection, Selection.End(xlDown)).Count < 20000 Then
Sheets("TestResults").Select
Range("A2").Select
Row = 20 + Range(Selection, Selection.End(xlDown)).Count
i = 21
''Copies Sample ID Data from TestResults Datasheet
Sheets("Tensile Ext").Select
Range("A21").Select
Range(Selection, "A" & Row).Select
Selection.UnMerge
Sheets("TestResults").Select
For Each Tst In Range("A1:L1")
If InStr(Tst.Value, "Sample ID") > 0 Then
Tst.Offset(1, 0).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Sheets("Tensile Ext").Select
Range("A21").Select
Range(Selection, "A" & Row).Select
ActiveSheet.Paste
Exit For
End If
Next Tst
Do While i <= Row
Range("A" & i & ":" & "D" & i).Select
With Selection
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlBottom
.MergeCells = True
.Borders.LineStyle = xlContinuous
.RowHeight = 24
End With
i = i + 1
Loop
i = 21
''Copies Ultimate Stress Data from TestResults Datasheet
Call CopyResultData2("N21", "N" & i & ":" & "Q" & i, "Ultimate Force", Row, i, "N", "Q")
''Copies Yield Force Data from TestResults Datasheet
Call CopyResultData2("R21", "R" & i & ":" & "U" & i, "Offset Force", Row, i, "R", "U")
''Copies Ultimate Stress Data from TestResults Datasheet
Call CopyResultData2("V21", "V" & i & ":" & "Y" & i, "Ultimate Stress", Row, i, "V", "Y")
''Copies Yield Stress Data from TestResults Datasheet
Call CopyResultData2("Z21", "Z" & i & ":" & "AC" & i, "Offset Stress", Row, i, "Z", "AC")
''Copies Elongation Data from TestResults Datasheet
Call CopyResultData2("AD21", "AD" & i & ":" & "AE" & i, "Elongation", Row, i, "AD", "AE")
''This deletes copied Worksheet
Application.DisplayAlerts = False
Sheets("TestResults").Delete
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End If
End Sub
Sub CopyResultData1(ByVal PstRng As String, ByVal FormRng As String, ByVal Rslt As String)
Worksheets("TestResults").Select
For Each Tst In Range("A1:L1")
DoEvents
If InStr(Tst.Value, Rslt) > 0 Then
Tst.Offset(1, 0).Select
Selection.Copy
Sheets("Tensile Ext").Select
Range(PstRng).Select
ActiveSheet.Paste
Exit For
End If
Next Tst
Range(FormRng).Select
With Selection
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlBottom
.MergeCells = False
.Borders.LineStyle = xlContinuous
End With
Selection.Merge
End Sub
Sub CopyResultData2(ByVal PstRng As String, ByVal FormRng As String, ByVal Rslt As String, ByVal Row As String, ByVal i As Variant, PstCol1, PstCol2)
Sheets("Tensile Ext").Select
Range(PstRng).Select
Range(Selection, PstCol1 & Row).Select
Selection.UnMerge
Sheets("TestResults").Select
For Each Tst In Range("A1:L1")
If InStr(Tst.Value, Rslt) > 0 Then
Tst.Offset(1, 0).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
Sheets("Tensile Ext").Select
Range(PstRng).Select
Range(Selection, PstCol1 & Row).Select
ActiveSheet.Paste
Exit For
End If
Next Tst
Do While i <= Row
Range(PstCol1 & i & ":" & PstCol2 & i).Select
With Selection
.HorizontalAlignment = xlCenter
.VerticalAlignment = xlBottom
.ReadingOrder = xlContext
.MergeCells = True
.Borders.LineStyle = xlContinuous
End With
i = i + 1
Loop
End Sub

Excel VBA Error'438' Object doesn't support this property or method

I would like to use this complicated formula in VBA, however, I keep getting the error, "Description" is one of the headers' names from my table, would you please help me out? Thanks.
Now it shows two errors,extended the table all the way to the bottom and error 1004
Sub StartChecking()
'Spacing Check and Auto Correct
ActiveSheet.Range("O6").Formula = "=SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(TRIM(SUBSTITUTE(DVDQC_Log[#Description], ""/"", "" / "")), ""C / O"", ""C/O""), "" -"", ""-""), ""- "", ""-"")"
Columns("O:O").EntireColumn.AutoFit
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
ActiveWindow.ScrollColumn = 6
ActiveWindow.ScrollColumn = 5
ActiveWindow.ScrollColumn = 3
ActiveWindow.ScrollColumn = 2
ActiveWindow.ScrollColumn = 1
Range("F6").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
ActiveWindow.ScrollColumn = 2
ActiveWindow.ScrollColumn = 3
Application.CutCopyMode = False
'Pass or Fail Check
ActiveSheet.Range("P6").Formula = "=IF([DVDQC_Log[#Needed Revisions]]="", ""PASSED"", ""FAILED"")"
Columns("I:I").Select
Selection.FormatConditions.Add Type:=xlExpression, Formula1:="=$I1<>$P1"
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorAccent2
.TintAndShade = 0.399945066682943
End With
Selection.FormatConditions(1).StopIfTrue = False
Range("DVDQC_Log[[#Headers],[Notes]]").Select
Selection.Copy
Range("DVDQC_Log[[#Headers],[Pass/Fail]]").Select
Selection.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, _
SkipBlanks:=False, Transpose:=False
Application.CutCopyMode = False
Application.CutCopyMode = False
ActiveWorkbook.Names.Add Name:="Address_ID", RefersToR1C1:= _
"=DVDQC_Log[Address_ID]"
ActiveWorkbook.Names("Address_ID").Comment = ""
Columns("N:N").Select
Selection.FormatConditions.Add Type:=xlExpression, Formula1:= _
"=LEN(TRIM(N1))=0"
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.ThemeColor = xlThemeColorAccent2
.TintAndShade = 0.399945066682943
End With
Selection.FormatConditions(1).StopIfTrue = False
ActiveWindow.ScrollColumn = 2
ActiveWindow.ScrollColumn = 1
Range("A6").Select
End Sub
Essentially, you put a formula into a cell or range of cells; not into a worksheet. It looks like your code was adapted from a Copy & Paste operation where you can paste into the ActiveSheet's default ActiveCell.
If O6 is one of the cells in the table with Description as one of the column names then,
Sub StartChecking()
ActiveSheet.Range("O6").Formula = _
"=SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(TRIM(SUBSTITUTE([#Description], ""/"", "" / "")), ""C / O"", ""C/O""), "" -"", ""-""), ""- "", ""-"")"
...
Range(Range("O6"), Range("O6").End(xlDown)).Select
...
ActiveSheet.Range("P6").Formula = _
"=IF([DVDQC_Log[#Needed Revisions]]=text(,), ""PASSED"", ""FAILED"")"
End Sub
If O6 is not one of the cells in the table then you also need to include the table name in the [#Description] reference like Table1[#Description].

Coloring multiple columns in excel

I am trying to color every other column in my excel file, the excel file has 500 columns. I came up with a macro which colors 5 columns at a time. Is there a way I can color all the columns at once.Here is my code. I am looking for a code that colors all the columns and I do not have to do it manually.
Sub Macro2()
'
' Macro2 Macro
'
'
ActiveCell.Range("A1:A2").Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlUp)).Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 65535
.TintAndShade = 0
.PatternTintAndShade = 0
End With
ActiveCell.Offset(0, 2).Range("A1").Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlDown)).Select
ActiveCell.Range("A1:A19").Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 65535
.TintAndShade = 0
.PatternTintAndShade = 0
End With
ActiveCell.Offset(0, 2).Range("A1:A19").Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 65535
.TintAndShade = 0
.PatternTintAndShade = 0
End With
ActiveCell.Offset(0, 2).Range("A1:A19").Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 65535
.TintAndShade = 0
.PatternTintAndShade = 0
End With
ActiveCell.Offset(0, 2).Range("A1:A19").Select
With Selection.Interior
.Pattern = xlSolid
.PatternColorIndex = xlAutomatic
.Color = 65535
.TintAndShade = 0
.PatternTintAndShade = 0
End With
End Sub
You can enumerate the Columns collection of the worksheet, and then for each Column, the 'column' property is the Column Index. Check that to see if it is even or odd, and set the colour.
Public Sub Colour()
Dim Column As Range
For Each Column In ActiveSheet.Columns
If Column.Column Mod 2 = 0 Then
Column.Interior.Color = vbRed
End If
Next Column
End Sub
To limit the columns, or change the how many are ordered, you can use a "for" loop instead of a For Each loop. Eg:
Public Sub Colour()
Dim colIndex As Long
For colIndex = 1 To ActiveSheet.Columns.Count Step 3 '//Step 3 means every third column.
ActiveSheet.Columns(colIndex).Interior.Color = vbRed
Next colIndex
End Sub
if you wanted to limit it to 500 columns:
Public Sub Colour()
Dim colIndex As Long
For colIndex = 1 To 500 Step 3 '//Step 3 means every third column.
ActiveSheet.Columns(colIndex).Interior.Color = vbRed
Next colIndex
End Sub

Resources