简体   繁体   English

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

[英]Macro to autofill a cell based on a value in a different sheet

I'm having a hard time trying to find a macro for the following use: 我很难找到用于以下用途的宏:

Taking in consideration this example: 考虑以下示例:

在此处输入图片说明

Consider that i have in the "sheet 1" the table with the columns Country and Food with its values. 考虑我在“工作表1”中的表格中有“国家”和“食品”列及其值。

In the sheet 2, i have two columns named Country#1 and Food#1. 在工作表2中,我有两列分别名为Country#1和Food#1。 The macro i want, needs to autofill the Food#1 cell that is associated with the right text in Country#1 cell, via the drop down list. 我想要的宏需要通过下拉列表自动填充与Country#1单元格中正确文本关联的Food#1单元格。

Example: When i select "Madrid" in Country#1, it needs to autofill the Food#1 with the text "Tapas and tortillas". 示例:当我在1号国家/地区中选择“马德里”时,它需要使用文本“塔帕斯和玉米饼”自动填充1号食物。

I'm sorry if this is a re-post question, but i didn't saw anything close as this :| 很抱歉,这是一个重新发布的问题,但是我没有看到任何类似的内容:|

Best regards, Luís 最好的问候,路易斯

You need a Sheet Change Event like below... 您需要如下的工作表更改事件...

The following code assumes that you have a list of Countries and their food in column A and B respectively on Sheet1 and the country dropdown list is in column A on Sheet2. 以下代码假定您在Sheet1的A列和B列中分别有一个国家及其食物的列表,并且国家/地区下拉列表在Sheet2的A列中。

Right click the Sheet2 Tab --> View code --> Past the following code into the opened code window. 右键单击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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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