简体   繁体   中英

Insert data in next empty column when “sheet.range” column is not empty

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

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

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM