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
答案 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
aname
,bname
和cname
,因为您只使用它们来构建文件名以与fname
进行比较。filename
的变量中拥有完整的文件名(包括它的路径),所以只需使用它来打开excel工作簿。