简体   繁体   中英

String functions in VBA ranges

Trying to write a string formula Left(a1,2) in VBA within a range.
Must use variables for "a1" to "a30" and "k1" to "k30"

Text in "a1" result in "k1"
03_15 03
.. ..
.. ..
12_21 12

Down to 30+ lines down.
I've tried this:

Cells(i, 8).Formula = "=left(A" & i &, 2")
Range("K1:K30").formula = "=Left(A1,2)"  

Written from my phone, untested, but should work.

Looks like you're just missing a double quote after the last ampersand:

Cells(i, 8).Formula = "=left(A" & i & ", 2")

When concatenating you should end up with an even number of quotation marks.

Write Formulas to Dynamic Range

Option Explicit

Sub writeFormulaToRange()
    ' Source First Cell Address
    Const srcFirstCell As String = "A1"
    ' Destination Column ID (Number or String)
    Const dstColID As Variant = "K" ' or 11
    ' Declare Variables.
    Dim srcRng As Range ' Source Range
    Dim srcLastRow As Long ' Source Last Row
    Dim ColOffset As Long ' Column Offset
    ' Define First Cell Range.
    With Range(srcFirstCell)
        ' Source Column is the column of the First Cell Range.
        ' Source Last Row is the row of the Last Non-Empty Cell Range
        ' in Source Column.
        ' Calculate Source Last Row.
        srcLastRow = .Worksheet.Cells(.Worksheet.Rows.Count, .Column) _
            .End(xlUp).Row
        ' Source Range is the range from the First Cell Range
        ' to the Last Non-Empty Cell Range.
        ' Define Source Range.
        Set srcRng = .Resize(srcLastRow - .Row + 1)
        ' Column Offset is the difference between the Destination
        ' and the Source Column Numbers.
        ' Calculate Column Offset.
        ColOffset = .Worksheet.Columns(dstColID).Column - .Column
    End With
    ' Destination Range is of the same size as the Source Range.
    ' Write the formulas to the Destination Range.
    srcRng.Offset(, ColOffset).Value = "=Left(" & srcFirstCell & ",2)"
    ' or:
    'rng.Offset(, ColOffset).Formula = "=Left(" & srcFirstCell & ",2)"
End Sub

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