简体   繁体   中英

Inserting formula using For Next Loop

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM