简体   繁体   中英

Copy last 3 char of text in one column to another column if cell is blank in excel spreadsheet with vba

If cell in Range("H1:H104000") is "" Then
    Range("H1:H104000) = LEFT(Range("D1:D104000), 3
End If

This is the code I am trying with no success.

You're missing the Loop. You need to write the loop to iterate through the collection of cells, the code can't do it implicitly even if you compare a single range to a collection of ranges.

Also, to compare values use = . The Is operator is only used for Objects.

Dim Cell As Range
For Each Cell In Range("H1:H104000").Cells
    If Cell.Value = "" Then
        Cell.Value = Right(Cell.Offset(0, -4).Value, 3)
    End If
Next

Once you're iterating through the column H. An easy way to refer to "column D in the current row" is by using Offset , which will return a cell, relative to your given starting position. In this case, we just need to move 4 columns to the left so I do .Offset(0,-4)

You might consider

  • assigning a worksheet related formula evaluation to a variant datafield array data and
  • writing data back to the referenced column H instead of looping through the given range; this approach lasts only a fraction of a second while the loop through each cell by means of VBA needs several seconds:
Option Explicit                         ' head of code module

Sub ExampleCall()
    Dim t As Double: t = Timer          ' start timer
    Dim ws As Worksheet
    Set ws = Sheet1                     ' << change to your project's sheet Code(Name) 
    Dim data As Variant                 ' provide for a 1-based 2-dim datafield array
    'assign worksheet related evaluation to data
    data = ws.Evaluate("=If(IsBlank(H2:H104000),Right(D2:D104000,3),H2:H104000)")
    'write to target   
    ws.Range("H2").Resize(UBound(data), 1).Value = data

    Debug.Print Format(Timer - t, "0.00 secs")    ' 0.20 secs   
End Sub

Further note A worksheet related evaluation via ws.Evaluate(...) guarantees a fully qualified range reference , whereas Evaluate(...) would need more detailed range indications like Sheet1!H2:H104000 or a further textual insertion of ws.Range("H2:H104000").Address(External:=True) to the formula string.

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