这是我的场景 - 我在工作表上的 COLUMN A 中有一个客户列表 - 以及相关数据......我有另一个工作表,我想在其中创建一个矩阵......但是在第 1 行有客户列表。
我希望添加到工作表 1 上的列的新客户 - 被添加到工作表 2 上的行
这是怎么做到的?
这是我的场景 - 我在工作表上的 COLUMN A 中有一个客户列表 - 以及相关数据......我有另一个工作表,我想在其中创建一个矩阵......但是在第 1 行有客户列表。
我希望添加到工作表 1 上的列的新客户 - 被添加到工作表 2 上的行
这是怎么做到的?
我不确定您的 VBA 功能水平,但在您的第一张工作表的代码隐藏中,您可以捕获 Workhseet_Change 事件。
您可以检查更新后的单元格是否在 A 列中。如果是,则可以将该值添加到表 2 的第一行。
以下是一些帮助您入门的代码:
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