excelcode.vb 1.9 KB
Newer Older
leaky114's avatar
leaky114 已提交
1 2 3
Imports Microsoft.Office.Interop

Module excelcode
leaky114's avatar
leaky114 已提交
4 5 6 7 8 9
    Public Excel_File_Name As String       'excel文件名
    Public Sheet_Name As String          '搜索的表
    Public Table_Array As String            '搜索的范围
    Public Col_Index_Num As String        '搜索列

    'VLOOKUP (lookup_value, table_array, col_index_num, [range_lookup])
leaky114's avatar
leaky114 已提交
10 11

    Public Function VLookUpValue(ByVal oExcel_File_Name As String, ByVal oStochNum As String, ByVal oSheet_Name As String, _
leaky114's avatar
21.12.3  
leaky114 已提交
12
                                 ByVal oTable_Array As String, ByVal oCol_Index_Num As String, ByVal oRange_LookUp As Integer) As String
leaky114's avatar
leaky114 已提交
13

leaky114's avatar
leaky114 已提交
14 15 16 17
        VLookUpValue = Nothing

        Dim excelApp As Excel.Application
        excelApp = New Excel.Application
leaky114's avatar
21.12.3  
leaky114 已提交
18
        excelApp.Visible = True
leaky114's avatar
leaky114 已提交
19
        Dim wb As Excel.Workbook = excelApp.Workbooks.Open(oExcel_File_Name)
leaky114's avatar
leaky114 已提交
20 21 22 23 24 25
        Dim sht As Excel.Worksheet
        sht = wb.Sheets(Sheet_Name)

        Dim userange As Excel.Range
        userange = sht.Range(oTable_Array)

leaky114's avatar
21.12.3  
leaky114 已提交
26
        'Dim oCol_Index_Num(10) As String
leaky114's avatar
leaky114 已提交
27

leaky114's avatar
21.12.3  
leaky114 已提交
28
        'oCol_Index_Num = Split(oCol_Index_Nums, ",")
leaky114's avatar
leaky114 已提交
29

leaky114's avatar
21.12.3  
leaky114 已提交
30 31 32 33 34 35 36 37
        'For Each a In oCol_Index_Num
        VLookUpValue = excelApp.WorksheetFunction.VLookup(oStochNum, userange, oCol_Index_Num, oRange_LookUp)
        If VLookUpValue <> Nothing Then
            wb.Close()
            excelApp.Quit()
            Return VLookUpValue
        End If
        'Next
leaky114's avatar
leaky114 已提交
38 39 40 41 42

        '关闭文件
        wb.Close()
        ' 8.退出Excel程序
        excelApp.Quit()
leaky114's avatar
leaky114 已提交
43

leaky114's avatar
leaky114 已提交
44 45 46 47 48 49 50
        '9.释放资源
        System.Runtime.InteropServices.Marshal.ReleaseComObject(userange)
        System.Runtime.InteropServices.Marshal.ReleaseComObject(sht)
        System.Runtime.InteropServices.Marshal.ReleaseComObject(wb)
        System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApp)

        '方法来源 https://blog.csdn.net/hsyj_0001/article/details/7686364
leaky114's avatar
21.12.3  
leaky114 已提交
51

leaky114's avatar
leaky114 已提交
52
        Return VLookUpValue
leaky114's avatar
leaky114 已提交
53

leaky114's avatar
leaky114 已提交
54
    End Function
leaky114's avatar
leaky114 已提交
55

leaky114's avatar
21.12.3  
leaky114 已提交
56
End Module