Excel VBA高级编程 - 根据关键字自动搜索,自动生成下拉菜单

关注微信公众号:万能的Excel,回复关键词【下拉菜单】获取Excel源文件

功能说明:

因为工作需要,每一次都要从SAP查找物料信息,手动生成物料清单(Boom表),繁琐且容易出错。

使用VBA实现了如下功能:

1、根据关键字,自动检索符合条件的产品信息

2、自动生成下拉菜单

3、选定物料名称,其他产品信息将自动对应输入

1

 

附件代码:

Private Sub Worksheet_Change(ByVal Target As Range)
Dim whereStr$, sql$, conn, mr%, j%, k%, l%, n%
Dim i As Long, w1 As String
    j = Target.Row
    On Error Resume Next
    k = Application.WorksheetFunction.Match(Sheet6.Cells(Target.Row, 3), Sheet2.Range("D1:D103"), 0)
    l = Application.WorksheetFunction.Match(Sheet6.Cells(Target.Row, 2), Sheet2.Range("C1:C103"), 0)
    n = Application.WorksheetFunction.Match(Sheet6.Cells(Target.Row, 1), Sheet2.Range("b1:b103"), 0)
    If k > 0 And l = 0 Then
            Cells(Target.Row, 2) = Application.WorksheetFunction.Index(Sheet2.Range("C:C"), k)
    ElseIf k > 0 And l > 0 And n = 0 Then
        Cells(Target.Row, 1) = Application.WorksheetFunction.Index(Sheet2.Range("B:B"), k)
        
    ElseIf Target.Count = 1 And Not Intersect(Range("A3:C999"), Target) Is Nothing Then
        whereStr = whereStr & IIf(Cells(j, 1) = "", "", " and [Manufacturer] like '%" & Cells(j, 1) & "%'")
        whereStr = whereStr & IIf(Cells(j, 2) = "", "", " and [ID] like '%" & Cells(j, 2) & "%'")
        whereStr = whereStr & IIf(Cells(j, 3) = "", "", " and [Type] like '%" & Cells(j, 3) & "%'")
        mr = Sheet5.Cells(Rows.Count, 1).End(xlUp).Row
        If mr > 2 Then Sheet5.Range("A3:G" & mr).Clear
        If whereStr <> "" Then
            Set conn = CreateObject("ADODB.connection")
            conn.Open "Provider=Microsoft.Ace.oledb.12.0;extended properties='excel 12.0;HDR=yes';data source=" & ThisWorkbook.FullName
            sql = "select * from [产品库$B6:D] where" & Mid(whereStr, 5)
            [Search!A3].CopyFromRecordset conn.Execute(sql)
            conn.Close
            Set conn = Nothing
        End If
        
    End If


    w1 = ""


    With Sheet6


        ''首先创建下拉列表数据
        n = Sheet5.Range("c1").End(xlDown).Row()


        For i = 3 To n Step 1


            w1 = w1 & IIf(w1 <> "", ",", "")


            w1 = w1 & Trim$(Sheet5.Cells(i, 3))


        Next


        ''添加数据有效性
        


        With .Cells(j, 3).Validation
    
            .Delete
            
                If w1 <> "" And k = 0 Then
    
                    .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:=xlBetween, Formula1:=w1
        
                    .InCellDropdown = True
                    
                End If
    
        End With


    End With
    
End Sub

关注微信公众号:万能的Excel,回复关键词【下拉菜单】获取Excel源文件

 

 

 

 

评论 9
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值