简体   繁体   中英

Excel - populating a column header with contents from a row on a different sheet

Here's my scenario - I have a customer list in COLUMN A on a sheet - along with relevant data... I have another sheet where I want to create a matrix...BUT have the customer list along ROW 1.

I want NEW customers that are ADDED to the COLUMN on sheet 1 - to be ADDED to the ROW on sheet 2

How is this done?

I'm not sure of your level of VBA capabilities, but in the code-behind for your first sheet you can capture the Workhseet_Change event.

You can check to see if the updated cell is in column A. And if it is, you can then add that value to sheet 2, on the first row.

Here is some code to help get you started:

Private Sub Worksheet_Change(ByVal Target As Range)

    'check to make sure the updated cell (Target) is in column 1 (column A)
    If Target.Column = 1 Then addToSheet2 (Target.Value2)

End Sub

Private Sub addToSheet2(ByVal newValue As Variant)

    Dim ws As Worksheet
    Dim columnCount As Integer
    Dim nextColumn As Integer

    On Error GoTo errTrap

    Set ws = ThisWorkbook.Sheets(2) 'probably want to use the sheet name, instead of the index

    'probably a good idea to check if it already exists in row 1 of sheet 2

    'get the number of columns used in sheet 2
    columnCount = ws.UsedRange.Columns.Count

    'this may be overkill, but if you are starting from scratch, columnCount will be 1 even if
    'there is no data in sheet 2 row 1
    If columnCount = 1 And ws.Range("A1").Value2 = vbNullString Then
        nextColumn = columnCount
    Else
        nextColumn = columnCount + 1
    End If

    ws.Cells(1, nextColumn).Value2 = newValue

errTrap:
    Set ws = Nothing

End Sub

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