I'm new to vba and I'm trying to write a script where I want to select a Range of columns based on the existence of a value in another column. So for example in the matrix below, I want to be able to select the BC range where A column is not blank, which is B1:C3
A B C
1 12345
2 54321
3 39284
4 <blank>
5 <blank>
Option Explicit
Sub ReferenceRangeQuick()
Dim rg As Range
Set rg = Range("A1:A" & Range("A" & Rows.Count) _
.End(xlUp).Row).EntireRow.Columns("B:C")
Debug.Print rg.Address
End Sub
Sub ReferenceRangeStudy()
Const lrCol As String = "A"
Const sCols As String = "B:C"
Const fRow As Long = 1
Dim ws As Worksheet: Set ws = ActiveSheet ' improve
' Last Row
' Note that this will return 1 even if there is no data in the column.
Dim lRow As Long: lRow = ws.Cells(ws.Rows.Count, lrCol).End(xlUp).Row
If lRow < fRow Then Exit Sub
Debug.Print "Last Row Number: " & lRow
' Last Row Column Range
Dim lrcrg As Range
Set lrcrg = ws.Range(ws.Cells(fRow, lrCol), ws.Cells(lRow, lrCol))
Debug.Print "Last Row Column Range Address: " & lrcrg.Address(0, 0)
' Source Range
Dim srg As Range: Set srg = lrcrg.EntireRow.Columns(sCols)
Debug.Print "Source Range Address: " & srg.Address(0, 0)
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.