I'm re-writing my module of Standard Methods. Virtually every project I do begins with grabbing some number of Data Tables and putting them in arrays. So, this is my general "Get Worksheet Data" method(s).
As always, particularly interested in maintainability, but all feedback is welcome.
Public Function GetWsDataArray(ByRef wbTarget As Workbook, ByRef wsTarget As Worksheet, ByVal topLeftCellText As String, ByVal useCurrentRegion As Boolean _
, Optional ByVal searchStartRow As Long = 1, Optional ByVal searchStartColumn As Long = 1 _
, Optional ByVal searchEndRow As Long = 10, Optional ByVal searchEndColumn As Long = 10) As Variant
'/ 10x10 is arbitrary search range that should cover almost all typical worksheets
Dim dataArray As Variant
dataArray = Array()
dataArray = GetWsDataRange(wbTarget, wsTarget, topLeftCellText, useCurrentRegion, searchStartRow, searchStartColumn, searchEndRow, searchEndColumn)
GetWsDataArray = dataArray
End Function
Public Function GetWsDataRange(ByRef wbTarget As Workbook, ByRef wsTarget As Worksheet, ByVal topLeftCellText As String, ByVal useCurrentRegion As Boolean _
, ByVal searchStartRow As Long, ByVal searchStartColumn As Long _
, ByVal searchEndRow As Long, ByVal searchEndColumn As Long) As Range
Dim wbSource As Workbook, wsSource As Worksheet
Set wbSource = ActiveWorkbook
Set wsSource = ActiveSheet
wbTarget.Activate
wsTarget.Activate
UnhideWsCellsAndRemoveFilters wsTarget
Dim topLeftCell As Range, searchRange As Range, dataRange As Range
Set searchRange = wsTarget.Range(Cells(searchStartRow, searchStartColumn), Cells(searchEndRow, searchEndColumn))
Set topLeftCell = CellContainingStringInRange(searchRange, topLeftCellText)
Dim lastRow As Long, lastCol As Long
If useCurrentRegion Then
Set dataRange = topLeftCell.CurrentRegion
Else
lastRow = Cells(Rows.Count, topLeftCell.Column).End(xlUp).row
lastCol = Cells(topLeftCell.row, Columns.Count).End(xlToLeft).Column
Set dataRange = wsTarget.Range(topLeftCell, Cells(lastRow, lastCol))
End If
Set GetWsDataRange = dataRange
wbSource.Activate
wsSource.Activate
End Function
Public Function CellContainingStringInRange(ByRef rngSearch As Range, ByVal strSearch As String) As Range
Dim errorMessage As String
Set CellContainingStringInRange = rngSearch.Find(strSearch, LookIn:=xlValues)
If CellContainingStringInRange Is Nothing _
Then
errorMessage = "Couldn't find cell """ & strSearch & """ in " & rngSearch.Worksheet.name
PrintErrorMessage errorMessage, stopExecution:=True
End If
End Function
Public Sub UnhideWsCellsAndRemoveFilters(ByRef ws As Worksheet)
ws.Rows.Hidden = False
ws.Columns.Hidden = False
ws.AutoFilterMode = False
End Sub
ws
from the call ofUnhideWsCellsAndRemoveFilters ws
in theGetWsDataRange()
come from ? \$\endgroup\$