How can I rename each column of a table? - excel

So I have a table with X columns, and I want to rename each with its own name.
I want to rename the first column using the string on A1, the second with the string on B1, and so on.
I tried using:
ActiveWorkbook.Names.Add Name:=Name, RefersToR1C1:="=Sheet1!R2C1:R70C1"
But I want to replace the R2C1:R70C1 to something like R2CA:R70CA where A's value goes up for each column. And also replace Sheet1 with ActiveSheet.Name
Any suggestions?
Note: No, the table isn't an object, so ActiveWorkbook.Sheets("Sheet").ListObjects("Table").ListColumns("Column name").Name = "New column name" doesn't work.
Note 2: I'm using Excel 2013

Add Name For Each Column
Sub AddNames()
Const FirstCol As String = "A"
Const FirstRow As Long = 2
Const LastRow As Long = 70
With ActiveSheet
Dim wsName As String: wsName = .Name
Dim fCell As Range: Set fCell = .Cells(FirstRow, FirstCol)
Dim rg As Range
Set rg = .Range(fCell, .Cells(FirstRow, .Columns.Count).End(xlToLeft)) _
.Resize(LastRow - FirstRow + 1)
Dim crg As Range, ErrNumber As Long, nmName As String
For Each crg In rg.Columns
nmName = CStr(crg.Cells(1).Value)
On Error Resume Next
.Names.Add nmName, "'" & wsName & "'!" & crg.Address
ErrNumber = Err.Number
On Error GoTo 0
If ErrNumber <> 0 Then
MsgBox "Could not add name """ & nmName & """.", vbCritical
ErrNumber = 0
End If
Next crg
End With
MsgBox "Names added.", vbInformation
End Sub
If you want the ranges of only the data (no headers), use the following:
Sub AddNamesData()
Const FirstCol As String = "A"
Const FirstRow As Long = 2
Const LastRow As Long = 70
With ActiveSheet
Dim wsName As String: wsName = .Name
Dim fCell As Range: Set fCell = .Cells(FirstRow, FirstCol)
Dim rg As Range
Set rg = .Range(fCell, .Cells(FirstRow, .Columns.Count).End(xlToLeft)) _
.Resize(LastRow - FirstRow + 1)
Dim hrg As Range: Set hrg = rg.Rows(1)
Dim drg As Range: Set drg = rg.Resize(rg.Rows.Count - 1).Offset(1)
Dim hCell As Range, c As Long, ErrNumber As Long, nmName As String
For Each hCell In hrg.Cells
c = c + 1
nmName = CStr(hCell.Value)
On Error Resume Next
.Names.Add nmName, "'" & wsName & "'!" & drg.Columns(c).Address
ErrNumber = Err.Number
On Error GoTo 0
If ErrNumber <> 0 Then
MsgBox "Could not add name """ & nmName & """.", vbCritical
ErrNumber = 0
End If
Next hCell
End With
MsgBox "Names added.", vbInformation
End Sub

Related

"run time error 91 object variable or with block variable not set" working with ranges

I'm a VBA beginner. I get a 'run time error 91 object variable or with block variable not set' trying to run the following code. Here is what I'm trying to do:
Select all data in my worksheet
Name the selection to AllData
Go through this range and wherever 'X' is found in Column D, change
value of Column W to 'No'.
The error refers to the 9th row where I try to set No_Of_Rows to the row count of my range. Apparently I should 'Set' my object beforehand..? But I don't know what I'm doing wrong...
Thanks in advance for your help.
Sub ChngColW()
Dim AllData As Range
Dim No_Of_Rows As Integer
Dim i As Long
Range("A1").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Name = "AllData"
No_Of_Rows = AllData.Rows.Count
For i = 1 To No_Of_Rows
If AllData("D" & i).Value = "X" Then
AllData("W" & i).Value = "No"
End If
Next i End Sub
A Quick Fix
Sub ChangeColumnW()
' Reference the worksheet.
Dim ws As Worksheet: Set ws = ActiveSheet ' improve!
' Reference the range.
Dim AllData As Range
Set AllData = ws.Range("A1", ws.Range("A1").End(xlToRight).End(xlDown))
' Name the range (useless).
'AllData.Name = "AllData"
' Now you could refer to it with 'Range("AllData")' but what's the benefit?
Dim i As Long
For i = 2 To AllData.Rows.Count
If AllData(i, "D").Value = "X" Then
AllData(i, "W").Value = "No"
End If
Next i
End Sub
An Alternative
Just 'looking' in the column not caring about the range including some improvements.
Sub ChangeColumnNoConstants()
Dim ws As Worksheet: Set ws = ActiveSheet ' improve!
Dim lRow As Long: lRow = ws.Cells(ws.Rows.Count, "D").End(xlUp).Row
Dim r As Long
Dim fCount As Long
For r = 2 To lRow
If StrComp(CStr(ws.Cells(r, "D").Value), "X", vbTextCompare) = 0 Then
ws.Cells(r, "W").Value = "No"
fCount = fCount + 1
End If
Next r
MsgBox "Found 'X' in " & fCount & " cells.", vbInformation
End Sub
Sub ChangeColumnUsingConstants()
Const sCol As String = "D"
Const sCrit As String = "X"
Const dCol As String = "W"
Const dCrit As String = "No"
Const fRow As Long = 2
Dim ws As Worksheet: Set ws = ActiveSheet ' improve!
Dim lRow As Long: lRow = ws.Cells(ws.Rows.Count, sCol).End(xlUp).Row
Dim r As Long
Dim fCount As Long
For r = fRow To lRow
If StrComp(CStr(ws.Cells(r, sCol).Value), sCrit, vbTextCompare) = 0 Then
ws.Cells(r, dCol).Value = dCrit
fCount = fCount + 1
End If
Next r
MsgBox "Found '" & sCrit & "' in " & fCount & " cells.", vbInformation
End Sub

Highlight rows in a sheet which contains a series of values in a column from another sheet

I have 2 sheets in a workbook.
Sheet 1 contains a list of numbers like,
A
B
9154
AAAA
9567
BBBB
9367
CCCC
9867
DDDD
9597
DDDD
In Sheet 2, I need to highlight all rows that contain values in Column A of sheet 1.
Both sheet have more than 10,000 rows. So its not possible to input search value as a string.
i found a code like this to highlight a specific value from https://stackoverflow.com/a/27237420/478884. But how can i ask the code to search and highlight from Column A of sheet 1.
Sub foo()
Dim value As String: value = "/"
Dim rSearch As Range
Dim firstFound As Range
Dim nextFound As Range
Dim wks As Worksheet
For Each wks In Worksheets
wks.Activate
Set rSearch = Range("a1", Cells(Rows.Count, "a").End(xlUp))
Set firstFound = rSearch.Find(value)
If Not firstFound Is Nothing Then
Set nextFound = firstFound
Do
nextFound.EntireRow.Interior.Color = RGB(1, 256, 1)
Set nextFound = rSearch.FindNext(nextFound)
Loop While nextFound.Address <> firstFound.Address
End If
Next
End Sub
Highlight Data Rows
It is assumed that both ranges are 'nice' tables starting in cell A1 with one row of headers.
Adjust the worksheet names, columns, and color in the constants section.
Option Explicit
Sub HighlightData()
Const ProcName As String = "HighlightData"
On Error GoTo ClearError
' Source
Const sName As String = "Sheet1"
Const sCol As Long = 1
' Destination
Const dName As String = "Sheet2"
Const dCol As Long = 1
Const dColor As Long = vbGreen
' Workbook
Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
Dim ws As Worksheet
Dim rg As Range, drg As Range
Dim Data As Variant
Application.ScreenUpdating = True
' Source
Set ws = wb.Worksheets(sName)
If ws.FilterMode Then ws.ShowAllData
Set rg = ws.Range("A1").CurrentRegion
Set drg = rg.Columns(sCol).Resize(rg.Rows.Count - 1).Offset(1)
Data = drg.Value
Dim dict As Object: Set dict = CreateObject("Scripting.Dictionary")
dict.CompareMode = vbTextCompare
Dim Key As Variant
Dim r As Long
For r = 1 To drg.Rows.Count
Key = Data(r, 1)
If Not IsError(Key) Then
If Len(Key) > 0 Then
dict(Key) = Empty
End If
End If
Next r
' Either...
r = 0
ReDim Data(1 To dict.Count) As String
For Each Key In dict.Keys
r = r + 1
Data(r) = Key
Next Key
' ... or:
'Data = Split(Join(dict.Keys, vbLf), vbLf) ' not sure what can all go wrong
Set dict = Nothing
' Destination
Set ws = wb.Worksheets(dName)
If ws.FilterMode Then ws.ShowAllData
Set rg = ws.Range("A1").CurrentRegion
Set drg = rg.Resize(rg.Rows.Count - 1).Offset(1)
drg.Interior.Color = xlNone
rg.AutoFilter dCol, Data, xlFilterValues
Erase Data
Set rg = Nothing
On Error Resume Next
Set rg = drg.SpecialCells(xlCellTypeVisible)
On Error GoTo ClearError
ws.AutoFilterMode = False
Dim IsSuccess As Boolean
If Not rg Is Nothing Then rg.Interior.Color = dColor: IsSuccess = True
Application.ScreenUpdating = True
If IsSuccess Then MsgBox "Data highlighted.", vbInformation
ProcExit:
Exit Sub
ClearError:
Debug.Print "'" & ProcName & "' Run-time error '" _
& Err.Number & "':" & vbLf & " " & Err.Description
Resume ProcExit
End Sub

Last column sorting for multiple fixed rows through VBA

trying to fix the macro for sorting on the last column of every sheet but the rows are fixed A3:A20 & A23:A32. Found the below code but I am unable to lock rows in it.
unable to crack how to define the rows in the below code.
sample data
Sub jusho()
Dim lColumn As Long
lColumn = Cells(1, Columns.Count).End(xlToLeft).Column
LastRow = Range("A" & Rows.Count).End(xlUp).Row
Range(Cells(2, 1), Cells(LastRow, lColumn)).Sort key1:=Range(Cells(2, lColumn), Cells(LastRow, lColumn)), _
order1:=xlAscending, Header:=xlNo
End Sub
Sort Multiple Ranges
Option Explicit
Sub SortByLastColumnASC()
SortMultipleRanges ThisWorkbook, "Sheet1", "2:20,22:32"
End Sub
Sub SortByLastColumnDSC()
SortMultipleRanges ThisWorkbook, "Sheet1", "2:20,22:32", , xlDescending
End Sub
Sub SortBySalesKeyASC()
SortMultipleRanges ThisWorkbook, "Sheet1", "2:20,22:32", 1
End Sub
Sub SortByDateKeyASC()
SortMultipleRanges ThisWorkbook, "Sheet1", "2:20,22:32", 2
End Sub
Sub SortMultipleRanges( _
ByVal wb As Workbook, _
ByVal wsName As String, _
ByVal wsRowsList As String, _
Optional ByVal SortColumn As Long = 0, _
Optional ByVal SortOrder As XlSortOrder = xlAscending, _
Optional ByVal SortHeader As XlYesNoGuess = xlYes)
Const ProcName As String = "SortMultipleRanges"
On Error GoTo ClearError
Dim ws As Worksheet: Set ws = wb.Worksheets(wsName)
Dim srg As Range: Set srg = ws.Range("A1").CurrentRegion
If SortColumn = 0 Then
SortColumn = srg.Columns.Count
End If
Dim wsRows() As String: wsRows = Split(wsRowsList, ",")
Dim nUpper As Long: nUpper = UBound(wsRows)
Dim drg As Range
Dim n As Long
For n = 0 To nUpper
Set drg = srg.Rows(wsRows(n))
drg.Sort Key1:=drg.Columns(SortColumn), Order1:=SortOrder, _
Header:=SortHeader
Next n
ProcExit:
Exit Sub
ClearError:
Debug.Print "'" & ProcName & "': Unexpected Error!" & vbLf _
& " " & "Run-time error '" & Err.Number & "':" & vbLf _
& " " & Err.Description
Resume ProcExit
End Sub
Consider using the macro to find the start row and end row of the sort ranges rather than hard coding them in.
Option Explicit
Sub SortRows()
Dim wb As Workbook, ws As Worksheet
Dim LastCol As Long, LastRow As Long, r As Long, n As Long
Dim rowStart As Long, rng As Range, s As String
Set wb = ThisWorkbook
Set ws = wb.Sheets("Sheet1")
With ws
LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row
LastCol = .Cells(1, Columns.Count).End(xlToLeft).Column
For r = 2 To LastRow
' start sort range
If .Cells(r, "A") = "SalesKey" Then
If rowStart > 0 Then
MsgBox "Duplicate SalesKey on row " & r, vbExclamation
End If
rowStart = r + 1
' end sort range
ElseIf .Cells(r, "A") = "Total" Then
If rowStart = 0 Then
MsgBox "Total without records on row " & r, vbExclamation
ElseIf r > rowStart + 1 Then
Set rng = .Cells(rowStart, 1).Resize(r - rowStart, LastCol)
rng.Sort key1:=.Cells(r, LastCol), _
order1:=xlAscending, Header:=xlNo
s = s & vbCrLf & rng.Address
End If
rowStart = 0
End If
Next
End With
MsgBox "Sorted ranges : " & s, vbInformation
End Sub

Finding Cells With Only Spaces

I am trying to find any cells with just spaces in. When I run this though it finds cells that are blanks too. Is there anyway to just find cells with spaces?
For i = 1 to lastRow
If len(trim(this workbook.sheets("data").range("a" & i)) = 0 then
Msgbox("a" & i " contains only space")
End if
Next i
Plase, try:
Sub testFindSpaces()
Dim wsD as Worksheet, i As Long, x As String, lastRow As Long
Set wsD = ThisWorkbook.Sheets("data")
lastRow = wsD.Range("A" & wsD.rows.count).End(xlUp).row
For i = 1 To lastRow
x = wsD.Range("a" & i).Value
If UBound(Split(x, " ")) = Len(x) Then
MsgBox "a" & i & " contains only space"
End If
Next i
End Sub
Just exclude blanks by testing for Len(ThisWorkbook.Worksheets("data").Range("A" & i)) <> 0 too.
For i = 1 to lastRow
Dim Untrimmed As String
Untrimmed = ThisWorkbook.Worksheets("data").Range("A" & i).Value
If Len(Trim(Untrimmed) = 0 AND Len(Untrimmed) <> 0 then
Msgbox "a" & i & " contains only space"
End if
Next i
Alternativeley use ThisWorkbook.Worksheets("data").Range("A" & i).Value <> vbNullString to exclude blanks
For i = 1 to lastRow
Dim Untrimmed As String
Untrimmed = ThisWorkbook.Worksheets("data").Range("A" & i).Value
If Len(Trim(Untrimmed) = 0 AND Untrimmed <> vbNullString then
Msgbox "a" & i & " contains only space"
End if
Next i
Just to add alternatives:
With ThisWorkbook.Sheets("data").Range("A" & i)
If .Value Like "?*" And Not .Value Like "*[! ]*" Then
MsgBox ("A" & i & " contains only space")
End If
End With
You may also just create a new regex-object and use pattern ^ +$ to validate the input.
If you don't want to loop the entire range but beforehand would like to exclude the empty cells you could (depending on your data) use xlCellTypeConstants or the numeric equivalent 2 when you decide to use SpecialCells() method and loop the returned cells instead:
Dim rng As Range, cl As Range
Set rng = ThisWorkbook.Worksheets("Data").Range("A:A").SpecialCells(2)
For Each cl In rng
If Not cl.Value Like "*[! ]*" Then
MsgBox ("A" & cl.Row & " contains only spaces")
End If
Next cl
You may also no longer need to find your last used row, but note that this may error out if no data at all is found in column A.
A last option I just thought about is just some concatenation before validation:
For i = 1 To lastRow
If "|" & Trim(ThisWorkbook.Sheets("data").Range("A" & i).value & "|" = "| |" Then
MsgBox ("A" & i & " contains only space")
End If
Next
Macro to get a string of address of cells containing only space using Evaluate VBA function
Edited code below - As suggested by #VBasic2008 and #T.M. in the comments below.
Option Explicit
Sub Cells_with_Space_Only()
Dim ws As Worksheet
Set ws = Sheets("Sheet2")
'Macro to get a string of address of cells containing only space
'https://stackoverflow.com/questions/68891170/finding-cells-with-only-spaces
Dim rngArr, rngStr As String, i As Long, rng As Range
rngArr = Evaluate("IFERROR(ADDRESS((ISBLANK(" & ws.UsedRange.Address(External:=True) & _
")=FALSE)*(" & ws.UsedRange.Address(External:=True) & _
"=REPT("" "",LEN(" & ws.UsedRange.Address(External:=True) & _
")))*ROW(" & ws.UsedRange.Address(External:=True) & _
"),COLUMN(" & ws.UsedRange.Address(External:=True) & ")),""**"")")
rngStr = ""
'If number of columns in usedrange are less then loop with
'For i = 1 To ActiveSheet.UsedRange.Columns.Count
For i = 1 To ws.UsedRange.Rows.Count
'if looped with For i = 1 To ActiveSheet.UsedRange.Columns.Count
'rngStr = Join(Filter(Application.Transpose(Application.Index(rngArr, 0, i)) _
, "**", False, vbBinaryCompare), ",")
rngStr = Join(Filter(Application.Index(rngArr, i, 0) _
, "**", False, vbBinaryCompare), ",")
If rngStr <> "" Then
If rng Is Nothing Then
Set rng = Range(rngStr)
Else
Set rng = Union(rng, Range(rngStr))
End If
End If
Next i
Debug.Print rng.Address
End Sub
The macro returns a string for the sample data in the image below --
$D$1,$A$2,$F$2,$B$3,$E$4,$A$6,$F$6,$E$7,$B$8,$D$9,$C$10,$F$10,$A$11,$D$13,$F$13,$E$14,$A$16,$E$16,$D$17,$F$17:$F$18
Array formula in the worksheet -
=IFERROR(ADDRESS((ISBLANK($A$1:$F$18)=FALSE)*($A$1:$F$18=REPT(" ",LEN($A$1:$F$18)))*ROW($A$1:$F$18),COLUMN($A$1:$F$18)),"**")
Clear Solo Spaces
Couldn't think of any reason for doing this other than for clearing the cells containing only spaces.
Option Explicit
Sub ClearSoloSpaces()
Dim wb As Workbook: Set wb = ThisWorkbook
Dim ws As Worksheet: Set ws = wb.Worksheets("Data")
Dim srg As Range ' Source Range
Set srg = ws.Range("A1", ws.Cells(ws.Rows.Count, "A").End(xlUp))
Dim crg As Range ' Clear Range
Dim cCell As Range ' Current Cell in Source Range
Dim cString As String ' Current Cell's Value Converted to a String
For Each cCell In srg.Cells
cString = CStr(cCell.Value)
If Len(cString) > 0 Then
If Len(Trim(cString)) = 0 Then
If crg Is Nothing Then
Set crg = cCell
Else
Set crg = Union(crg, cCell)
End If
End If
End If
Next cCell
If crg Is Nothing Then
MsgBox "No cells containing only spaces found.", _
vbInformation, "Clear Solo Spaces"
Else
Dim Msg As Long
Msg = MsgBox("The cells in the rows '" _
& Replace(crg.Address, "$A$", "") _
& "' of column 'A' contain only spaces." & vbLf _
& "Do you want to clear them?", _
vbInformation + vbYesNo, "Clear Solo Spaces")
If Msg = vbYes Then
crg.Clear ' or crg.ClearContents ' to preserve formatting
End If
End If
End Sub
Just for the sake of showing alternatives (#T.M.), please test the next one, too:
Private Sub testFindSpacesBis()
Dim wsD As Worksheet, i As Long, x As String, lastRow As Long
Set wsD = ActiveSheet ' ThisWorkbook.Sheets("data")
lastRow = wsD.Range("A" & wsD.rows.count).End(xlUp).row
For i = 1 To lastRow
x = wsD.Range("a" & i).Value
If StrComp(x, space(Len(x)), vbBinaryCompare) = 0 Then
MsgBox "a" & i & " contains only spaces"
End If
Next i
End Sub

Matching the Three Criteria and Copy Paste the Data

Below code match the string in the specific range (this range contains Headers) if finds then copy the whole column and paste into Sheet2.
I want to add two more condition in below code that are:
Dim FindValue2 As String
Dim FindValue3 As String
FindValue2 = shSummary.Range("A2").Value
FindValue3 = shSummary.Range("B2").Value
and match in Sheet1 Column A for FindValue3 and Column F for FindValue2 after matching these 3 criteria then copy and paste the data.
Your help will be much appreciated.
Sub find()
Dim foundRng As Range
Dim FindValue As String
Dim lastRow As Long
Set shData = Worksheets("Sheet1")
Set shSummary = Worksheets("Sheet2")
FindValue = shSummary.Range("C2")
Set foundRng = shData.Range("G1:Z1").find(FindValue)
With shData
lastRow = .Cells(.Rows.Count, foundRng.Column).End(xlUp).Row
End With
shData.Rows("2:" & lastRow).Columns(foundRng.Column).Copy shSummary.Range("I3")
End Sub
Apply a filter to columns A and F then copy the visible cells.
Option Explicit
Sub Find3()
Dim wb As Workbook, wsData As Worksheet, wsSummary As Worksheet
Dim rngFound As Range, rngData As Range, rngCopy As Range
Dim FindValue As String, FilterA As String, FilterF As String
Dim lastRow As Long, c As Long
Set wb = ThisWorkbook
Set wsData = wb.Worksheets("Sheet1")
wsData.AutoFilterMode = False
Set wsSummary = wb.Worksheets("Sheet2")
With wsSummary
FindValue = .Range("B2")
FilterA = .Range("C2")
FilterF = .Range("A2")
End With
Set rngFound = wsData.Range("G1:Z1").find(FindValue)
If rngFound Is Nothing Then
MsgBox "'" & FindValue & "' not found", vbCritical
Exit Sub
End If
' column matching FindValue
c = rngFound.Column
lastRow = wsData.Cells(Rows.Count, c).End(xlUp).Row
If lastRow = 1 Then
MsgBox "No data in column " & c, vbCritical
Exit Sub
End If
' filter data on colA and F
With wsData
Set rngData = .Cells(2, c).Resize(lastRow - 1)
.UsedRange.AutoFilter
.UsedRange.AutoFilter Field:=1, Criteria1:=FilterA
.UsedRange.AutoFilter Field:=6, Criteria1:=FilterF
' data to copy
On Error Resume Next
Set rngCopy = rngData.SpecialCells(xlCellTypeVisible)
On Error GoTo 0
' copy data
If rngCopy Is Nothing Then
MsgBox "No data to copy from column " & c, vbCritical
.AutoFilterMode = False
Exit Sub
Else
rngCopy.Copy wsSummary.Range("I3")
End If
.AutoFilterMode = False
End With
MsgBox "Done"
End Sub
Copy Data Columns to Another Worksheet
Adjust the values in the constants section.
Delete (out-comment) the Debug.Print lines when done testing.
Option Explicit
Sub ExportDataColumns()
Const sName As String = "Sheet1"
Const sHeadersAddress As String = "G1:Z1"
Const dName As String = "Sheet2"
Const dReadList As String = "A2,B2,C2"
Const dWriteList As String = "F3,A3,I3"
Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
Dim sws As Worksheet: Set sws = wb.Worksheets(sName)
Dim wsrCount As Long: wsrCount = sws.Rows.Count
Dim shrg As Range: Set shrg = sws.Range(sHeadersAddress)
Debug.Print "Source Header Range: " & shrg.Address(0, 0)
Dim sfRow As Long: sfRow = shrg.Row + 1 ' first row below the headers
Debug.Print "Source First Row: " & sfRow
If sfRow >= wsrCount Then Exit Sub
Dim slRow As Long: slRow = GetLastRow(shrg)
Debug.Print "Source Last Row: " & slRow
If slRow < sfRow Then Exit Sub
Dim sdrg As Range
Set sdrg = shrg.Resize(slRow - sfRow + 1).Offset(1)
Debug.Print "Source Data Range: " & sdrg.Address(0, 0)
Dim dRead() As String: dRead = Split(dReadList, ",")
Dim dWrite() As String: dWrite = Split(dWriteList, ",")
Dim dUpper As Long: dUpper = UBound(dRead)
Dim dws As Worksheet: Set dws = wb.Worksheets(dName)
Dim srg As Range
Dim drg As Range
Dim dcrg As Range
Dim srCount As Long
Dim n As Long
For n = 0 To dUpper
Debug.Print "Item " & n + 1
Dim scIndex As Variant
scIndex = Application.Match(dws.Range(dRead(n)).Value, shrg, 0)
If IsNumeric(scIndex) Then
Set srg = sdrg.Columns(scIndex)
Debug.Print "Source Range: " & srg.Address(0, 0)
srCount = srg.Rows.Count
Set drg = dws.Range(dWrite(n)).Resize(srCount)
Debug.Print "Destination Range: " & drg.Address(0, 0)
drg.Value = srg.Value
Set dcrg = drg.Resize(wsrCount - drg.Row - srCount + 1) _
.Offset(srCount)
Debug.Print "Destination Clear Range: " & dcrg.Address(0, 0)
dcrg.ClearContents
End If
Next n
End Sub
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
' Purpose: Returns the worksheet row number of the last non-empty row
' in the range from the first row of a range ('rg')
' through the same sized bottom-most row of the worksheet.
''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
Function GetLastRow( _
ByVal rg As Range) _
As Long
If rg Is Nothing Then Exit Function
Dim lCell As Range
With rg.Rows(1)
Set lCell = .Resize(.Worksheet.Rows.Count - .Row + 1) _
.Find("*", , xlFormulas, , xlByRows, xlPrevious)
End With
If lCell Is Nothing Then Exit Function
GetLastRow = lCell.Row
End Function

Resources