I want to know how to loop declaring a variant.
instead of
Dim Foreign_Field_1 As Variant
ReDim Foreign_Field_1(LBound(Foreign_Key, 1) To UBound(Foreign_Key, 1), _
LBound(Foreign_Key, 2) To UBound(Foreign_Key, 2))
Dim Foreign_Field_2 As Variant
ReDim Foreign_Field_2(LBound(Foreign_Key, 1) To UBound(Foreign_Key, 1), _
LBound(Foreign_Key, 2) To UBound(Foreign_Key, 2))
with (just an idea)
dim i as integer
for i = 1 to 2
Dim x As Variant
x = "Foreign_Field_" & i
ReDim x(LBound(Foreign_Key, 1) To UBound(Foreign_Key, 1), _
LBound(Foreign_Key, 2) To UBound(Foreign_Key, 2))
next i
meaning that i want to loop through the variable itself, so that instead of writing the same procedure more than one time just loop through the same procedure.
Foreign_Field_1, Foreign_Field_2, etc...
Hope you got the question?
This is part of a bigger code, I just need help regarding this matter solely.
any ideas?
FullCode
Sub Get_Data_BYN()
' // Set Data Workplaces
' / Set Data WorkBooks
Dim SourceBook As Workbook
Set SourceBook = GetWorkbook(Source)
Dim TargetBook As Workbook
Set TargetBook = ThisWorkbook
' / Set Data WorkSheets
Dim SourceSheet As Worksheet
Set SourceSheet = SourceBook.Worksheets("Data")
Dim TargetSheet As Worksheet
Set TargetSheet = TargetBook.Worksheets("Sheet2")
' / Set Data Ranges
Dim SourceLastRow As Long
SourceLastRow = SourceSheet.Cells(Rows.Count, 1).End(xlUp).Row
Dim TargetLastRow As Long
TargetLastRow = TargetSheet.Cells(Rows.Count, 1).End(xlUp).Row
' / Set Data Keys
Dim Primary_Key As Variant '[SourceSheet Array Store]: LAVA ID
Primary_Key = WorksheetFunction.Transpose(SourceSheet.Range("A2:A" & SourceLastRow).Value)
Dim Foreign_Key As Variant '[TargetSheet Range Store]: LAVA ID
Foreign_Key = TargetSheet.Range("G2:G" & TargetLastRow).Value
' / Set Data Fields
Dim Primary_Field_1 As Variant '[SourceSheet Array Store]: Bayan ID
Primary_Field_1 = WorksheetFunction.Transpose(SourceSheet.Range("B2:B" & SourceLastRow).Value)
Dim Primary_Field_2 As Variant '[SourceSheet Array Store]: Bayan ID
Primary_Field_2 = WorksheetFunction.Transpose(SourceSheet.Range("C2:C" & SourceLastRow).Value)
Dim Foreign_Field_1 As Variant
ReDim Foreign_Field_1(LBound(Foreign_Key, 1) To UBound(Foreign_Key, 1), _
LBound(Foreign_Key, 2) To UBound(Foreign_Key, 2))
Dim Foreign_Field_2 As Variant
ReDim Foreign_Field_2(LBound(Foreign_Key, 1) To UBound(Foreign_Key, 1), _
LBound(Foreign_Key, 2) To UBound(Foreign_Key, 2))
' / Write (Keys-IndexMatch) in Array offset Foreign_Field_1
Dim i As Long
For i = LBound(Foreign_Key, 1) To UBound(Foreign_Key, 1)
Foreign_Field_1(i, 1) = Primary_Field_1( _
WorksheetFunction.Match(Foreign_Key(i, 1), Primary_Key, 0))
Foreign_Field_2(i, 1) = Primary_Field_2( _
WorksheetFunction.Match(Foreign_Key(i, 1), Primary_Key, 0))
Next i
' / Write (Keys-IndexMatch) in Range offset Foreign_Field_1 2
ThisWorkbook.Worksheets("Sheet2").Range("H2:H" & TargetLastRow).Value = Foreign_Field_1
ThisWorkbook.Worksheets("Sheet2").Range("i2:i" & TargetLastRow).Value = Foreign_Field_2
End Sub
Starting from '/ Set Data Fields
I need to loop more than once without re-writing the procedures every time for each column.
As noted above, if you have a bunch of consecutively-named variables you probably should be considering arrays:
Dim ForeignFields(1 to 2), n
'...
For n = 1 to 2
ForeignFields(n) = EmptyCopy(Foreign_Key)
Next n
'...
Function EmptyCopy(arr)
Dim rv
Redim rv(lbound(arr, 1) to ubound(arr, 2), lbound(arr, 2) to ubound(arr, 2))
EmptyCopy = rv
End Function
Related
I want to create a variant array when using a union to join ranges.
If I select one of the ranges the variant array will work.
When I union, I only receive the row dimensions and not the column dimensions.
For example,
Sub arrTest()
'Declare varbs
Dim ws As Worksheet
Dim myArr() As Variant
Dim lRow As Integer
Dim myRng As Range
'Assign varbs
Set ws = ThisWorkbook.Worksheets("Sheet1")
With ws
lRow = .Cells(Rows.count, "C").End(xlUp).row
Set myRng = Application.Union(.Range("G3:G" & lRow), .Range("J3:O" & lRow), .Range("AD3:AE" & lRow), .Range("AI3:AI" & lRow))
myArr = myRng.Value2
End With
Will return a variant of
myArr(1, 1)
myArr(2, 1)
myArr(1, 3)
However if I were to select one of the ranges within the union for example:
Sub arrTest()
'Declare varbs
Dim ws As Worksheet
Dim myArr() As Variant
Dim lRow As Integer
Dim myRng As Range
'Assign varbs
Set ws = ThisWorkbook.Worksheets("Sheet1")
With ws
lRow = .Cells(Rows.count, "C").End(xlUp).row
Set myRng = .Range("J3:O" & lRow)
myArr = myRng.Value2
End With
I properly get
myArr(1, 1)
myArr(1, 2)
myArr(1, 3)
etc.
How do I return the column dimensions as well, without looping through the sheet?
Like this:
Sub ArrayTest()
Dim ws As Worksheet
Dim arr, lrow As Long
Set ws = ThisWorkbook.Worksheets("Sheet1")
lrow = ws.Cells(Rows.Count, "C").End(xlUp).Row
arr = GetArray(ws.Range("G3:G" & lrow), ws.Range("J3:O" & lrow), _
ws.Range("AD3:AE" & lrow), ws.Range("AI3:AI" & lrow))
With ThisWorkbook.Worksheets("Sheet2").Range("B2")
.Resize(UBound(arr, 1), UBound(arr, 2)).Value = arr
End With
End Sub
'Given a number of input ranges each consisting of one or more columns (assumed all input ranges have
' the same # of rows), return a single 1-based 2D array with the data from each range
Function GetArray(ParamArray sourceCols() As Variant) As Variant
Dim arr, rng, numCols As Long, numRows As Long, r As Long, c As Long, tmp, col As Long
numRows = sourceCols(0).Rows.Count
'loop over ranges and get the total number of columns
For Each rng In sourceCols
numCols = numCols + rng.Columns.Count
Next rng
ReDim arr(1 To numRows, 1 To numCols) 'size the output array
c = 0
For Each rng In sourceCols 'loop the input ranges
tmp = As2DArray(rng) 'get range source data as array ####
For col = 1 To UBound(tmp, 2) 'each column in `rng`
c = c + 1 'increment column position in `arr`
For r = 1 To numRows 'fill the output column
arr(r, c) = tmp(r, col)
Next r
Next col
Next rng
GetArray = arr
End Function
'Get a range's value, always as a 2D array, even if only a single cell
Function As2DArray(rng)
If rng.Cells.Count > 1 Then
As2DArray = rng.Value
Else
Dim arr(1 To 1, 1 To 1)
arr(1, 1) = rng.Value
As2DArray = arr
End If
End Function
I have been trying to match Date with week number i.e. ("B1:F1")
then date with Year-month i.e. ("A2:A500")
If matches then copy the value from this table that i have highlighted according to the date which is available in code where week is 2 and month is May-2021. Can someone please help me to achieve this.
There are multiple dates which i need to iterate with this table to get different values according to weeks and Year-Months.
Your help will be much appreciated.
Sub findMatchingRecords()
Dim rng1 As Range
Dim rng2 As Range
Dim ws As Worksheet
Dim getdate As String
Dim GetWeek As String
Set ws = Worksheets("Sheet1")
getdate = ws.Range("N1").Value
GetWeek = Int((Day(getdate) + 6) / 7)
Set rng1 = ws.Range("B1:F1")
Set rng2 = ws.Range("A2:A500")
For Each rng1cell In rng1
For Each rng2cell In rng2
If rng1cell = GetWeek And rng2cell = Format(getdate, "yyyy-mmm") Then
'Copy value and paste into Sheet1.Range("M2")
End If
Next rng1cell
Next rng2cell
End Sub
Here are the dates which needs to match with table and get relevant the value.
5/13/2021
5/16/2021
5/19/2021
5/22/2021
5/25/2021
5/28/2021
5/31/2021
6/3/2021
6/6/2021
6/9/2021
6/12/2021
6/15/2021
6/18/2021
6/21/2021
6/24/2021
Non-VBA Method
One way this could be done without using VBA is with a INDEX/MATCH formula.
The following formula assumes the data is in B2:F500, the month/years are in A2:A500, the weeks in B1:F1 and the dates to look for are in column N, all on the same sheet Sheet1.
=INDEX($B$2:$F$13,MATCH(TEXT(N1,"yyyy-mmm"),Sheet1!$A$2:$A$13,0),MATCH(INT((DAY(N1)+6)/7),Sheet1!$B$1:$F$1,0))
VBA Method
If you want VBA to do this here's one way.
Option Explicit
Sub findMatchingRecords()
Dim ws As Worksheet
Dim rngData As Range
Dim rngDates As Range
Dim arrData As Variant
Dim arrDates As Variant
Dim arrYearMonth As Variant
Dim arrValues As Variant
Dim arrWeeks As Variant
Dim Res As Variant
Dim idxCol As Long
Dim idxDate As Long
Dim idxRow As Long
Dim wk As Long
Set ws = Sheets("Sheet1")
With ws
Set rngData = .Range("A1").CurrentRegion
Set rngDates = .Range("N1", .Range("N" & Rows.Count).End(xlUp))
End With
With rngData
arrData = rngData.Offset(1, 1).Resize(.Rows.Count - 1, .Columns.Count - 1)
arrYearMonth = .Columns(1).Offset(1).Resize(.Rows.Count - 1)
arrWeeks = .Rows(1).Offset(, 1).Resize(, .Columns.Count - 1)
End With
arrDates = rngDates.Value
ReDim arrValues(1 To UBound(arrDates, 1), 1 To 1)
For idxDate = LBound(arrDates, 1) To UBound(arrDates, 1)
idxRow = 0
idxCol = 0
Res = Application.Match(Format(arrDates(idxDate, 1), "yyyy-mmm"), arrYearMonth, 0)
If Not IsError(Res) Then
idxRow = Res
wk = Int((Day(arrDates(idxDate, 1)) + 6) / 7)
Res = Application.Match(wk, arrWeeks, 0)
If Not IsError(Res) Then
idxCol = Res
End If
End If
If idxRow <> 0 And idxCol <> 0 Then
arrValues(idxDate, 1) = arrData(idxRow, idxCol)
End If
Next idxDate
rngDates.Offset(, 1).Value = arrValues
End Sub
Please, test the next code:
Sub MatchDate_WeekNo()
Dim sh As Worksheet, lastR As Long, arr, arrN, arrfin, i As Long, strDate As String
Dim weekN As Long, arrRow, arrCol, iCol As Variant, iRow As Variant, lastRN As Long
Set sh = Worksheets("Sheet1")
lastR = sh.Range("A" & sh.Rows.Count).End(xlUp).Row
lastRN = sh.Range("N" & sh.Rows.Count).End(xlUp).Row
arr = sh.Range("A1:F" & lastR).Value
arrRow = Application.Index(arr, 1, 0)
arrCol = Application.Transpose(Application.Index(arr, 0, 1))
arrN = sh.Range("N2:N" & lastRN).Value2
ReDim arrfin(1 To UBound(arrN), 1 To 1)
For i = 1 To UBound(arrN)
strDate = StringFromDate(CDate(arrN(i, 1)))
weekN = Int((Day(arrN(i, 1)) + 6) / 7)
iCol = Application.Match(weekN, arrRow, 0)
iRow = Application.Match(strDate, arrCol, 0)
If IsNumeric(iCol) And IsNumeric(iRow) Then
arrfin(i, 1) = arr(iRow, iCol)
End If
Next i
'drop the final array content:
sh.Range("O2").Resize(UBound(arrfin), 1).Value = arrfin
End Sub
Function StringFromDate(d As Date) As String
Dim arrM
Const strMonths As String = "Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec"
arrM = Split(strMonths, ",")
StringFromDate = Year(d) & "-" & Application.Index(arrM, Month(d))
End Function
Format(arrDates(idxDate, 1), "yyyy-mmm") does not return the month in case of localization different then English type and only that's why I am using a function...
I have got below coding for my huge data set VBA, I wish to manipulate columns according to my range criteria, Please help.
Dim Ary As Variant, Nary As Variant
Dim r As Long, Rw As Long
With Sheets("Sheet1")
Ary = .Range("A2:B" & .Range("A" & Rows.Count).End(xlUp).Row).Value2
End With
ReDim Nary(1 To UBound(Ary), 1 To 1)
With CreateObject("scripting.dictionary")
For r = 1 To UBound(Ary)
If Not .Exists(Ary(r, 1)) Then
.Add Ary(r, 1), r
Nary(r, 1) = Ary(r, 2)
Else
Rw = .Item(Ary(r, 1))
Nary(Rw, 1) = Nary(Rw, 1) + Ary(r, 2)
End If
Next r
End With
Sheets("sheet1").Range("C2").Resize(UBound(Nary)).Value = Nary
Sheets("sheet1").Range("C2").Resize(UBound(Nary)).Value = Nary
I want to columns re-arrange as per below criteria,
ColumnA = ColumnD (4)
ColumnB = ColumnN (14)
ColumnC - ColumnO (15)
Please re-codes above Ubound & Lbound coding as per above criteria, As I am not far used to with arrays
functions codes.
Above coding are working fine I just want to manipulate columns.
Thankyou
Get First Sums
The following sums up the values in a column for each unique value in another column and displays the result in a third column in the rows of the first occurrence of each unique value.
Option Explicit
Function getFirstSums( _
ws As Worksheet, _
ByVal LookUpColumn As Variant, _
ByVal ValuesColumn As Variant, _
Optional ByVal FirstRow As Long = 1) _
As Variant
Dim LastRow As Long
LastRow = ws.Cells(ws.Rows.Count, LookUpColumn).End(xlUp).Row
Dim rng As Range
Set rng = ws.Cells(FirstRow, LookUpColumn).Resize(LastRow - FirstRow + 1)
Dim Lookup As Variant: Lookup = rng.Value
Dim SumUp As Variant
SumUp = rng.Offset(, ws.Columns(ValuesColumn).Column _
- ws.Columns(LookUpColumn).Column).Value
Dim rCount As Long: rCount = UBound(Lookup)
Dim Result As Variant: ReDim Result(1 To rCount, 1 To 1)
Dim r As Long, rw As Long
With CreateObject("Scripting.Dictionary")
For r = 1 To rCount
If Not .Exists(Lookup(r, 1)) Then
.Add Lookup(r, 1), r
Result(r, 1) = SumUp(r, 1)
Else
rw = .Item(Lookup(r, 1))
Result(rw, 1) = Result(rw, 1) + SumUp(r, 1)
End If
Next r
End With
getFirstSums = Result
End Function
Sub TESTgetFirstSums()
Const wsName As String = "Sheet1"
Const LookUpColumn As Variant = "D"
Const ValuesColumn As Variant = "N"
Const ResultColumn As Variant = "O"
Const FirstRow As Long = 2
Dim ws As Worksheet: Set ws = ThisWorkbook.Worksheets("Sheet1")
Dim ary As Variant
ary = getFirstSums(ws, LookUpColumn, ValuesColumn, FirstRow)
ws.Range(ResultColumn & FirstRow).Resize(UBound(ary)).Value = ary
End Sub
Sub TESTgetFirstSumsSimple()
Dim ws As Worksheet: Set ws = ThisWorkbook.Worksheets("Sheet1")
Dim ary As Variant
ary = getFirstSums(ws, 4, 14, 2)
ws.Cells(2, 15).Resize(UBound(ary)).Value = ary
End Sub
EDIT:
Or you might rather write it as a sub procedure:
Sub writeFirstSums( _
ws As Worksheet, _
ByVal LookUpColumn As Variant, _
ByVal ValuesColumn As Variant, _
ByVal ResultColumn As Variant, _
Optional ByVal FirstRow As Long = 1)
Dim LastRow As Long
LastRow = ws.Cells(ws.Rows.Count, LookUpColumn).End(xlUp).Row
Dim rng As Range
Set rng = ws.Cells(FirstRow, LookUpColumn).Resize(LastRow - FirstRow + 1)
Dim Lookup As Variant: Lookup = rng.Value
Dim SumUp As Variant
SumUp = rng.Offset(, ws.Columns(ValuesColumn).Column _
- ws.Columns(LookUpColumn).Column).Value
Dim rCount As Long: rCount = UBound(Lookup)
Dim Result As Variant: ReDim Result(1 To rCount, 1 To 1)
Dim r As Long, rw As Long
With CreateObject("Scripting.Dictionary")
For r = 1 To rCount
If Not .Exists(Lookup(r, 1)) Then
.Add Lookup(r, 1), r
Result(r, 1) = SumUp(r, 1)
Else
rw = .Item(Lookup(r, 1))
Result(rw, 1) = Result(rw, 1) + SumUp(r, 1)
End If
Next r
End With
ws.Cells(FirstRow, ResultColumn).Resize(UBound(Result)) = Result
End Sub
Sub TESTwriteFirstSumsSimple()
Dim ws As Worksheet: Set ws = ThisWorkbook.Worksheets("Sheet1")
writeFirstSums ws, 4, 14, 15, 2
End Sub
Part I No problem here
Sub Get_Data_BYN()
' // Set Data Workplaces
' / Set Data WorkBooks
Dim SourceBook As Workbook
Set SourceBook = GetWorkbook(Source)
Dim TargetBook As Workbook
Set TargetBook = ThisWorkbook
' / Set Data WorkSheets
Dim SourceSheet As Worksheet
Set SourceSheet = SourceBook.Worksheets("Data")
Dim TargetSheet As Worksheet
Set TargetSheet = TargetBook.Worksheets("Sheet2")
' / Set Data Ranges
Dim SourceLastRow As Long
SourceLastRow = SourceSheet.Cells(Rows.Count, 1).End(xlUp).Row
Dim TargetLastRow As Long
TargetLastRow = TargetSheet.Cells(Rows.Count, 1).End(xlUp).Row
Dim Primary_Key As Variant '[SourceSheet Array Store]: LAVA ID
Primary_Key = WorksheetFunction.Transpose(SourceSheet.Range("A2:A" & SourceLastRow).Value)
Dim Foreign_Key As Variant '[TargetSheet Range Store]: LAVA ID
Foreign_Key = TargetSheet.Range("G2:G" & TargetLastRow).Value
Part II - Rest of code Where I need to loop through variants (for i = 1 to x) instead of (dim "variable" as variant every time), I need the full syntax as I am new to this topic... you can see below.
meaning that i want to loop through the variable itself, so that instead of writing the same procedure more than one time just loop through the same procedure.
' / Set Data Fields
Dim Primary_Field_1 As Variant '[SourceSheet Array Store]: Bayan ID
Primary_Field_1 = WorksheetFunction.Transpose(SourceSheet.Range("B2:B" & SourceLastRow).Value)
Dim Primary_Field_2 As Variant '[SourceSheet Array Store]: Bayan ID
Primary_Field_2 = WorksheetFunction.Transpose(SourceSheet.Range("C2:C" & SourceLastRow).Value)
Dim Primary_Field_3 As Variant '[SourceSheet Array Store]: Bayan ID
Primary_Field_3 = WorksheetFunction.Transpose(SourceSheet.Range("D2:D" & SourceLastRow).Value)
Dim Primary_Field_4 As Variant '[SourceSheet Array Store]: Bayan ID
Primary_Field_4 = WorksheetFunction.Transpose(SourceSheet.Range("E2:E" & SourceLastRow).Value)
Dim Foreign_Field_1 As Variant
ReDim Foreign_Field_1(LBound(Foreign_Key, 1) To UBound(Foreign_Key, 1), _
LBound(Foreign_Key, 2) To UBound(Foreign_Key, 2))
Dim Foreign_Field_2 As Variant
ReDim Foreign_Field_2(LBound(Foreign_Key, 1) To UBound(Foreign_Key, 1), _
LBound(Foreign_Key, 2) To UBound(Foreign_Key, 2))
Dim Foreign_Field_3 As Variant
ReDim Foreign_Field_3(LBound(Foreign_Key, 1) To UBound(Foreign_Key, 1), _
LBound(Foreign_Key, 2) To UBound(Foreign_Key, 2))
Dim Foreign_Field_4 As Variant
ReDim Foreign_Field_4(LBound(Foreign_Key, 1) To UBound(Foreign_Key, 1), _
LBound(Foreign_Key, 2) To UBound(Foreign_Key, 2))
' / Write (Keys-IndexMatch) in Array offset Foreign_Field_1
Dim i As Long
For i = LBound(Foreign_Key, 1) To UBound(Foreign_Key, 1)
Foreign_Field_1(i, 1) = Primary_Field_1( _
WorksheetFunction.Match(Foreign_Key(i, 1), Primary_Key, 0))
Foreign_Field_2(i, 1) = Primary_Field_2( _
WorksheetFunction.Match(Foreign_Key(i, 1), Primary_Key, 0))
Foreign_Field_3(i, 1) = Primary_Field_3( _
WorksheetFunction.Match(Foreign_Key(i, 1), Primary_Key, 0))
Foreign_Field_4(i, 1) = Primary_Field_4( _
WorksheetFunction.Match(Foreign_Key(i, 1), Primary_Key, 0))
Next i
' / Write (Keys-IndexMatch) in Range offset Foreign_Field_1 2
ThisWorkbook.Worksheets("Sheet2").Range("H2:H" & TargetLastRow).Value = Foreign_Field_1
ThisWorkbook.Worksheets("Sheet2").Range("i2:i" & TargetLastRow).Value = Foreign_Field_2
ThisWorkbook.Worksheets("Sheet2").Range("J2:J" & TargetLastRow).Value = Foreign_Field_3
ThisWorkbook.Worksheets("Sheet2").Range("K2:K" & TargetLastRow).Value = Foreign_Field_3
End Sub
Untested but try something like this:
Sub Get_Data_BYN()
Const NUM_DATA_COLS As Long = 4
Dim SourceSheet As Worksheet, TargetSheet As Worksheet
Dim rngPrimary_Key As Range '[SourceSheet Array Store]: LAVA ID
Dim Foreign_Key As Variant '[TargetSheet Range Store]: LAVA ID
Dim SourceLastRow As Long, TargetLastRow As Long
Dim Primary_Fields(1 To NUM_DATA_COLS), Foreign_Fields(1 To NUM_DATA_COLS), n As Long
Dim i As Long, v, m
Set SourceSheet = GetWorkbook(Source).Worksheets("Data")
Set TargetSheet = ThisWorkbook.Worksheets("Sheet2")
SourceLastRow = SourceSheet.Cells(Rows.Count, 1).End(xlUp).Row
TargetLastRow = TargetSheet.Cells(Rows.Count, 1).End(xlUp).Row
'match is much faster against a range on a sheet than against an array
Set rngPrimary_Key = SourceSheet.Range("A2:A" & SourceLastRow)
Foreign_Key = TargetSheet.Range("G2:G" & TargetLastRow).Value
For n = 1 To NUM_DATA_COLS
Primary_Fields(n) = SourceSheet.Range("B2:B" & SourceLastRow).Offset(0, n - 1).Value
Foreign_Fields(n) = EmptyCopy(Foreign_Key) 'empty array for results
Next n
' get matching rows and copy values to arrays
For i = LBound(Foreign_Key, 1) To UBound(Foreign_Key, 1)
v = Foreign_Key(i, 1)
m = Application.Match(v, rngPrimary_Key, 0)
If Not IsError(m) Then 'check got a match
For n = 1 To NUM_DATA_COLS
Foreign_Fields(n)(i, 1) = Primary_Fields(n)(m, 1)
Next n
End If
Next i
' / Write (Keys-IndexMatch) in Range offset Foreign_Field_1 2
Place2DArray TargetSheet.Range("H2"), Foreign_Fields(1)
Place2DArray TargetSheet.Range("i2"), Foreign_Fields(2)
Place2DArray TargetSheet.Range("J2"), Foreign_Fields(3)
Place2DArray TargetSheet.Range("K2"), Foreign_Fields(4)
End Sub
'return an empty array of same dimensions as 'arr'
Function EmptyCopy(arr)
Dim rv
ReDim rv(LBound(arr, 1) To UBound(arr, 1), LBound(arr, 2) To UBound(arr, 2))
EmptyCopy = rv
End Function
'copy a 1-based 2-d array 'arr' to a worksheet, starting at cell 'c'
Sub Place2DArray(c As Range, arr)
c.Resize(UBound(arr, 1), UBound(arr, 2)).Value = arr
End Sub
Unless you have a lot of data though, this would be much simpler as a vlookup in a loop. Arrays are sometimes faster, but there's a lot to be said for simplicity too.
# This is the input table for which I want to perform some action #
Public Sub mac()
Dim RangeOfChild As Range
For i = 1 To 10000
ActiveCell.Range("A" & i).Activate
Dim DirArray As Variant
Dim temp As Variant
Set RangeOfChild = Range(ActiveCell.Offset(0, 1),ActiveCell.End(xlToRight))
childCount = RangeOfChild.count
temp = ActiveCell.Value
ActiveCell = Null
DirArray = RangeOfChild.Value
RangeOfChild.ClearContents
ActiveCell.EntireRow.Resize(childCount - 1).Insert Shift:=xlDown
ActiveCell.Value = temp
Range(ActiveCell.Offset(0, 1), ActiveCell.Offset(RangeOfChild.count - 1, 1)) = Application.Transpose(Array(DirArray))
i = i + (childCount)
Next i
End Sub
I want a output similar to the below image
enter image description here
But the written for loop is only doing the operation to two of the rows , not the remaining, If someone could help me out with this , it would be a great help.
I accomplished this task by using two worksheets: worksheets("SheetInput") which contains the input data and worksheets("SheetOutput") which receives the formatted output.
Option Explicit
Public Sub mac()
Dim wsData As Worksheet, wsOutput As Worksheet
Dim rngInput As Range, RangeOfChild As Range, rngOutput As Range
Dim childCount As Long
Set wsData = ThisWorkbook.Worksheets("SheetInput")
Set wsOutput = ThisWorkbook.Worksheets("SheetOutput")
Set rngInput = ThisWorkbook.Worksheets("SheetInput").Cells(1, 1)
Set rngOutput = ThisWorkbook.Worksheets("SheetOutput").Cells(1, 1)
While Not (IsEmpty(rngInput))
Set RangeOfChild = Range(rngInput.Offset(0, 1), rngInput.End(xlToRight))
childCount = RangeOfChild.Count
rngInput.Copy
rngOutput.PasteSpecial Paste:=xlPasteAll
RangeOfChild.Copy
rngOutput.Offset(0, 1).PasteSpecial Paste:=xlPasteAll, Transpose:=True
Set rngInput = rngInput.Offset(1, 0)
Set rngOutput = rngOutput.Offset(childCount, 0)
Wend
End Sub
activate method is not good. use a variant array.
Sub test()
Dim rngDB As Range, rngCnt As Range
Dim rng As Range, rng2 As Range
Dim vCnt, vR()
Dim i As Integer, c As Integer, n As Long, s As Long
Set rngDB = Range("a1", Range("a" & Rows.Count).End(xlUp))
For Each rng In rngDB
Set rngCnt = Range(rng.Offset(, 1), rng.End(xlToRight))
s = n + 1
vCnt = rngCnt
c = rngCnt.Columns.Count
n = n + c
ReDim Preserve vR(1 To 2, 1 To n)
vR(1, s) = rng
For i = 1 To c
vR(2, s + i - 1) = vCnt(1, i)
Next i
Next rng
Sheets.Add
Range("a1").Resize(n, 2) = WorksheetFunction.Transpose(vR)
End Sub