Reputation: 135
I am using the below code to populate a table with weekly data via an index match function through VBA.
In the 1st week, column C of the Weekly sheet needs to be populated and this works like a charm.
However, starting from the 2nd week when new data is provided, I will need to make sure not to overwrite 1st week data and add new data into the next column which should be D. And so on.
Any suggestion about how to accomplish this objective with the below code?
Sub IndexMatchFunctionDynamic()
Dim destinationWs As Worksheet, dataWs As Worksheet
Dim destinationLastRow As Long, dataLastRow As Long, x As Long
Dim IndexRng As Range, MatchRng As Range
Set destinationWs = ThisWorkbook.Worksheets("Weekly")
Set dataWs = ThisWorkbook.Worksheets("Market Data")
destinationLastRow = destinationWs.Range("A" & Rows.Count).End(xlUp).Row
dataLastRow = dataWs.Range("A" & Rows.Count).End(xlUp).Row
Set IndexRng = dataWs.Range("P3:P" & dataLastRow)
Set MatchRng = dataWs.Range("A3:A" & dataLastRow)
For x = 2 To destinationLastRow
On Error Resume Next
a = Application.Match(destinationWs.Range("A" & x).Value, MatchRng, 0)
Nights = Application.Index(IndexRng, a)
If (IsError(a) Or IsEmpty(Nights)) Or (IsError(a) And IsEmpty(Nights)) Then
destinationWs.Range("C" & x).Value = 0
Else
destinationWs.Range("C" & x).Value = Nights
End If
On Error GoTo 0
Next x
End Sub
Thanks in advance
Upvotes: 0
Views: 113
Reputation: 11
First get next available column in the sheet
PrintToColumn = destinationWs.Cells(1,Columns.Count).XlEnd(XlToLeft).Column + 1
Then print values in that column
destinationWs.Cells(x, PrintToColumn).Value = Nights
Upvotes: 1