Inserting formula using For Next Loop - excel

I am attempting to concatenate a column's worth of fields (~900 at the moment) from two other fields in the same sheet.
I am trying to create a macro to enter the formula into Column C. I can't keep the quotation marks straight.
Sub Concatenate()
Dim i As Long
Dim LastRow As Long
Dim Con As String
Dim WS As Worksheet
Set WS = Sheets("Vlookups")
'Set upper range of Loop
LastRow = Range("C" & Rows.Count).End(xlUp).Row
Application.ScreenUpdating = False
'Set to Active Worksheet
Worksheets("Vlookups").Activate
'Explicitly reference the Sheet when calling for any Range or Cell
With WS
For i = 2 To LastRow
Con = "=CONCATENATE(" & .Cells(i, 15).Select & "," & "-" & "," & .Cells(i, 16).Select & ")"
.Cells(i, 3).Select
ActiveCell.Formula = Con
Next i
End With
Application.ScreenUpdating = False
End Sub

There is no need to Select or Activate.
There is no need to loop.
It looks like you are finding the last row based on column C, but then writing the formula into column C, which seems suspect. Perhaps find the last row based on column O, or column P?
There's no need to use the CONCATENATE formula.
With WS
' find last row based on column O, or maybe P
LastRow = .Range("O" & .Rows.Count).End(xlUp).Row
.Range("C2:C" & LastRow).Formula = "=O2&""-""&P2"
End With
If you actually want hard-coded strings instead of cell references in your formula, then:
With WS
' find last row based on column O, or maybe P
LastRow = .Range("O" & .Rows.Count).End(xlUp).Row
For i = 2 to LastRow
Range("C" & i).Formula = "=""" & Range("O" & i).Value & "-" & Range("P" & i).Value & """"
Next
End With

Related

Why is my macro starting in row 1 instead of row 2?

I'm not sure why my macro is starting this =TRIM(F2) formula in cell E1 instead of E2.
'Insert TRIM Contract Column & formula
Set rngHeaders = Range("1:1") 'Looks in entire first row
Set rngUsernameHeader = rngHeaders.Find(what:="Contract", After:=Cells(1, 1))
rngUsernameHeader.EntireColumn.Insert
Range("E1").Value = "TRIM CONTRACT"
Range("E1").Font.Bold = True
Range("E2").Select
Dim lastRow As Long
lastRow = Range("E2:E" & Rows.Count).End(xlUp).Row
Range("E2:E" & lastRow) = _
"=TRIM(F2)"
Range("E2:E" & lastRow).Select
Range("E2:E" & Range("F" & Rows.Count).End(xlUp).Row).FillDown
I'm just trying to insert a column (column E) that contains the TRIM values in the column next to it (column F, aka 'Contract')
This should work, I also removed all unnecessary lines:
Option Explicit
Sub Macro3()
'Insert TRIM Contract Column & formula
Set rngHeaders = Range("1:1") 'Looks in entire first row
Set rngUsernameHeader = rngHeaders.Find(what:="Contract", After:=Cells(1, 1))
rngUsernameHeader.EntireColumn.Insert
Range("E1").Value = "TRIM CONTRACT"
Range("E1").Font.Bold = True
Dim lastRow As Long
lastRow = Range("F" & Rows.Count).End(xlUp).Row
Range("E2:E" & lastRow) = "=TRIM(F2)"
End Sub
Cheers .
Followup:
If you don't know what column is going to contain "Contract" you need to make all further cell references related to your found cell:
Option Explicit
Sub Insert_Formula_Found_Column()
'Insert TRIM Contract Column & formula
Dim RngHeaders As Range
Dim RngUserNameHeader As Range
Dim BuiltFormula As String
Set RngHeaders = Range("1:1") 'Looks in entire first row
Set RngUserNameHeader = RngHeaders.Find(what:="Contract", After:=Cells(1, 1))
RngUserNameHeader.EntireColumn.Insert
RngUserNameHeader.Offset(0, -1).Value = "TRIM CONTRACT"
RngUserNameHeader.Offset(0, -1).Font.Bold = True
Dim lastRow As Long
lastRow = RngUserNameHeader.Offset(Rows.Count - 1, 0).End(xlUp).Row
BuiltFormula = "=TRIM(" & Replace(RngUserNameHeader.Offset(1, 0).Address, "$", "") & ")"
RngUserNameHeader.Offset(1, -1).Resize(lastRow).Formula = BuiltFormula
End Sub

VBA to copy formula across variable rows and columns

I'm entering a value in the last blank cell (as I can't do the last row in a column) due to other data being there. I was to add the sum of all the above cells to each column.
The number of columns is variable as is the number of names
I've been able to add the relevant formula but I can't get it to copy across in the same way my other code did.
This is the line with the error, to copy to the last used column, everything else works except this bit.
Range("O" & nextfree).AutoFill Range("O" & nextfree, Cells("O" & nextfree, lastcolumn))
I get a run type error 13, Type mis-match.
The full code is here
Sub addrow()
'Checks the number of users then adds them to the active sheet section
Dim rowsToAdd As Integer
Dim lastcolumn As Long
Dim lastRow As Long
Dim ws As Worksheet, ws1 As Worksheet
Set ws = ThisWorkbook.Worksheets("Refs")
Set w1 = ThisWorkbook.Worksheets("Active events")
With ws
lastRow = Sheets("Refs").Cells(.Rows.Count, "A").End(xlUp).Row
lastcolumn = Sheets("Active events").Cells.Find("*", searchorder:=xlByColumns, SearchDirection:=xlPrevious).Column
MsgBox lastRow - 1
MsgBox lastcolumn
End With
With ws1
Rows("5:5").Resize(lastRow - 1).Insert Shift:=xlDown ' minus 2 to account for header row and also existing text in row 4
End With
Worksheets("Refs").Range("A2:A" & lastRow).Copy Worksheets("Active events").Range("M4")
Range("O4:O" & lastRow + 2).Formula = "=SUMIF($C$14:$C$5032,$M4,O$14:O$5032)"
Range("O4:O" & lastRow + 2).AutoFill Range("O4", Cells(lastRow + 2, lastcolumn))
'Find the next blank cell in the names range and adds totals and the sum value to all columns
nextfree = Range("M4:M" & Rows.Count).Cells.SpecialCells(xlCellTypeBlanks).Row
Range("M" & nextfree).Value = "Total"
Range("O" & nextfree).Value = "=SUM(O4:O" & nextfree - 1 & ")"
'Problem code here
Range("O" & nextfree).AutoFill Range("O" & nextfree, Cells("O" & nextfree, lastcolumn))
End Sub

VBA to check if multiple values fall within multiple ranges

I have a list of about 2000 values in column A in Excel, and then a list of the start and end of value ranges in the next two columns. The range values don't correspond to the values in the first column. I want to check, for every value in column A, whether the value falls within ANY of the ranges listed in columns B and C.
So for example, in the image below, see whether A2 falls within B2-C2, B3-C3, OR B4-C4. Then the same again for A3 and A4. For each of these I want true/false to be entered in column D. The true/false value would correspond to the values in column A.
I've been trying to do this in VBA but I'm not totally confident with getting it to search the ranges. Current code is below.
Sub CheckRg()
Dim wk As Worksheet, frow As Long, i As Long
Set wk = Sheet1
frow = wk.Range("A" & Rows.Count).End(xlUp).Row
For i = 2 To frow
If wk.Range("A" & i).Value >= wk.Range("B:B").Value And wk.Range("A" & i).Value <= wk.Range("C:C").Value Then
wk.Range("D" & i).Value = "TRUE"
Else
wk.Range("D" & i).Value = "FALSE"
End If
Next i
End Sub
This formula should do the trick without VBA:
=COUNTIFS($B:$B,"<="&A2,$C:$C,">="&A2)<>0
You can use it in your code like this:
Sub CheckRg()
Dim wk As Worksheet, frow As Long, i As Long
Set wk = Sheet1
frow = wk.Range("A" & Rows.Count).End(xlUp).Row
For i = 2 To frow
With Excel.WorksheetFunction
wk.Range("D" & i).Value = .CountIfs(wk.Range("B:B"), Evaluate("""<=""" & "&A" & i), wk.Range("C:C"), Evaluate(""">=""" & "&A" & i)) <> 0
End With
Next i
End Sub
An Inefficient Double Loop
A better way to go is presented in the solution by Evil Blue Monkey.
You need to check each cell in column A against each cell pair of columns B and C which requires a second loop that slows down the operation when thousands of rows are expected.
Here's an example of how you could go about that.
Sub CheckRg()
Dim ws As Worksheet: Set ws = Sheet1
Dim lRow As Long: lRow = ws.Range("A" & ws.Rows.Count).End(xlUp).Row
Application.ScreenUpdating = False
Dim i As Long
Dim j As Long
Dim MatchFound As Boolean
For i = 2 To lRow
For j = 2 To lRow
If ws.Range("A" & i).Value >= ws.Range("B" & j).Value _
And ws.Range("A" & i).Value <= ws.Range("C" & j).Value Then
MatchFound = True
Exit For
End If
Next j
If MatchFound Then
ws.Range("D" & i).Value = True
MatchFound = False
Else
ws.Range("D" & i).Value = False
End If
Next i
Application.ScreenUpdating = True
MsgBox "Range checked.", vbInformation
End Sub

Excel VBA - Add hyphens to column A if column B contains specific letter

Please help a newbie.
Using Excel VBA, I am trying to format the text in column A with hyphens but only if column B contains the letter B.
I have found the code below, one which formats the cells in column A with hyphens, and another code which checks column B for the correct value, but cannot seem to combine them to work. Help please.
Thank you.
Sub AddDashes()
Dim Cell As Range
On Error GoTo NoFilledCells
For Each Cell In Range("A1:A" & Cells(Rows.Count, "A").End(xlUp).Row).SpecialCells(xlCellTypeConstants)
Cell.Value = Format(Replace(Cell.Value, "-", ""), "#####-###-####")
Next
NoFilledCells:
End Sub
and
Sub ChangeColumn()
Dim LastRow As Long
Dim i As Long
LastRow = Range("A" & Rows.Count).End(xlUp).Row
For i = 2 To LastRow
If Range("B" & i).Value = "B" Then
Range("A" & i).Value = "Formatted text with hyphens as above"
End If
Next i
End Sub
Option Explicit
Sub AddDashes()
Dim ws As Worksheet, cell As Range
Dim LastRow As Long
Set ws = ActiveSheet
LastRow = ws.Range("A" & Rows.Count).End(xlUp).Row
For Each cell In ws.Range("A2:A" & LastRow)
If cell.Offset(0, 1) = "B" Then ' col B
cell.Value = Format(Replace(cell.Value, "-", ""), "#####-###-####")
End If
Next
End Sub

Autofill Dynamic Range Last Row and Last Column

I have a workbook containing multiple sheets of varying sizes. I want to add a total column after the last row and copy the formula across all columns. I have defined the last row and column and the formula appears as expected in the correct place but I receive an error when trying to fill across. How do I correctly reference both dynamic cells for the fill? I'm just using a single sheet for now for testing but will eventually be looping through all the sheets in the book.
Sub Addtotals()
Dim Bord As Worksheet
Dim LRow As Long
Dim LCol As Long
Dim frmcell As Range
Set Bord = Sheets("Borders")
With Bord
'--> Define last rows and columns
LRow = .Range("A" & Rows.Count).End(xlUp).Row
LCol = .Range("A" & Columns.Count).End(xlToLeft).Column
'--> Add Total text to first column
.Range("A" & LRow).Offset(1, 0).Select
ActiveCell = "Total"
'--> Add formula to next column
Set frmcell = Range("B" & LRow + 1)
frmcell.Formula = "=sum(B2:B" & LRow & ")"
'--> Fill formula across range
frmcell.Select
Selection.AutoFill Destination:=Range(frmcell & LCol), Type:=xlFillDefault
End With
End Sub
Thanks :)
Like this?
Option Explicit
Sub Addtotals()
Dim Bord As Worksheet
Dim LRow As Long, LCol As Long
Set Bord = Sheets("Borders")
With Bord
'--> Define last rows and columns
LRow = .Range("A" & Rows.Count).End(xlUp).Row + 1
LCol = .Cells(1, Columns.Count).End(xlToLeft).Column
'--> Add Total text to first column
.Range("A" & LRow).Value = "Total"
'--> Fill formula across range
.Range("B" & LRow & ":" & _
Split(Cells(, LCol).Address, "$")(1) & LRow).Formula = _
"=Sum(B2:B" & LRow - 1 & ")"
End With
End Sub

Resources