Reputation: 23
I'm trying to make a VBA macro that will look in Column D for a specific value and input text into 3 others. I believe that I am close to having the answer I need, but I'm not sure what I'm missing to get this to work.
Here's what I have so far:
Dim rng As range
Dim i As Long
'Set the range in column D you want to loop through
**Set rng = range("D3:D")**
For Each cell In rng
'Test cell for CR
If cell.Value = "CR" Then
'write to adjacent cell
cell.Offset(0, 3).Value = "CREDIT"
cell.Offset(0, 5).Value = "CREDIT"
cell.Offset(0, 6).Value = "CREDIT"
End If
Next
**Set rng = range("G3:G")**
For Each cell In rng
'test for empty cell
If cell.Value = "" Then
'write to adjacent cell
cell.Offset(0, 0).Value = "FREIGHT"
cell.Offset(0, 2).Value = "FREIGHT"
cell.Offset(0, 3).Value = "FREIGHT"
End If
Next
End Sub
The lines with ** are where I am running into errors.
Any help is greatly appreciated!
Upvotes: 1
Views: 74
Reputation: 43595
This is a way to declare a range, based on a given cell and its End(xlDown)
:
Option Explicit
Sub TestMe()
Dim myRange As Range
Dim firstCell As Range
Dim lastCell As Range
Set firstCell = Worksheets(1).Range("A12")
Set lastCell = firstCell.End(xlDown)
Set myRange = Range(firstCell, lastCell)
End Sub
The idea is that ever two cells on a given worksheet can define a range. Thus, by defining them, the range gets defined as well.
The two cells are firstCell
and lastCell
. The interesting part is that you need to declare the parent object (worksheet
) of firstCell
only, then the lastCell
and myRange
use the same one.
Upvotes: 0