macros根据不同工作表中的值自动填充单元格

我正在努力寻找一个macros的以下用途:

考虑到这个例子:

在这里输入图像说明

考虑一下,我在“表1”中列出了“国家与食品”栏以及其值。

在表2中,我有两列名为国家#1和食物#1。 我想要的macros,需要通过下拉列表自动填充与#1单元格中的正确文本相关联的Food#1单元格。

例如:当我在国家#1中select“马德里”时,它需要自动填充文本“Tapas and tortillas”的食物#1。

对不起,如果这是一个重新发布的问题,但我没有看到任何接近这个:|

最好的问候,路易斯

您需要像下面的表单更改事件…

下面的代码假定您在Sheet1的列A和B分别有一个国家和他们的食物列表,国家下拉列表在Sheet2的列A中。

右键单击Sheet2选项卡 – >查看代码 – >将以下代码拖到打开的代码窗口中。

Private Sub Worksheet_Change(ByVal Target As Range) If Target.CountLarge > 1 Then Exit Sub Dim wsSource As Worksheet Dim r As Long Set wsSource = Sheets("Sheet1") 'Source sheet which contains a table of countries and their food If Target.Column = 1 And Target.Row > 1 Then If Application.CountIf(wsSource.Columns(1), Target.Value) > 0 Then Application.EnableEvents = False r = Application.Match(Target.Value, wsSource.Columns(1), 0) Target.Offset(0, 1) = wsSource.Cells(r, 2) Application.EnableEvents = True End If End If End Sub