如何使用vb.net代码从各种C文件夹中查找特定文件

时间:2015-04-18 06:08:57

标签: vb.net

Option Explicit On
Imports excel = Microsoft.Office.Interop.Excel
Imports System.IO

Public Class Form1

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim objExcelApplication As New excel.Application
    Dim objExcelWorkbook As excel.Workbook
    Dim aname As String
    Dim bname As String
    Dim cname As String

    Dim directory = "C:\Project\"
    For Each filename As String In IO.Directory.GetFiles(directory, "*.xlsm", IO.SearchOption.AllDirectories)
        Dim fname As String = IO.Path.GetFileName(filename)
        aname = TextBox1.Text
        bname = "-001"
        cname = aname & bname
        If fname = cname & ".xlsm" Then
            objExcelWorkbook = objExcelApplication.Workbooks.Open(fname)
        End If
    Next

End Sub

End Class

1 个答案:

答案 0 :(得分:1)

试试这个:

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Dim objExcelApplication As New excel.Application
    Dim objExcelWorkbook As excel.Workbook
    Dim directory = "C:\Project\"
    For Each filename As String In IO.Directory.GetFiles(directory, "*.xlsm", IO.SearchOption.AllDirectories)
        Dim fname As String = IO.Path.GetFileName(filename)
        If fname = TextBox1.Text & "-001" & ".xlsm" Then
            ' Since the filename already contains the full path: 
            objExcelWorkbook = objExcelApplication.Workbooks.Open(filename)
        End If
    Next

End Sub
  1. 不需要anamebnamecname,因为您只使用它们来构建文件名以与fname进行比较。
  2. 您尝试仅根据文件名打开文件,而不是根据它的完整路径。因为您已经在名为filename的变量中拥有完整的文件名(包括它的路径),所以只需使用它来打开excel工作簿。