我正在尝试获取文件夹路径,然后在此文件夹中为Excel工作表循环
Imports Excel= Microsoft.Office.Interop.Excel
Public Sub Combine()
Dim objApp As Excel.Application
Dim objBook As Excel.Workbook
Dim objSheet As Excel.Worksheet
Dim myrange As Excel.Range
Dim folderPath As String
Dim fileName As String
folderPath = @"FolderPath"
fileName = Dir(folderPath & "*.xls")
Do While (fileName <> "")
objBook = objApp.Workbooks.Open(Filename:=Txt_GetPath.Text & fileName = True)
objBook.Activate()
For Each objSheet In objBook.Sheets
objSheet.Copy(After:=objBook.Sheets(1))
Next objSheet
objBook.Close()
Loop
End Sub
但是在objBook =objApp.Workbooks.open(...)
行,我得到了一个错误
路径必须是完整的
代码有什么问题?
答案 0 :(得分:2)
要处理目录中的所有文件,可以使用Directory.EnumerateFiles函数。
在代码使用完毕后,处置Excel应用程序并不完全简单,因此我从The proper way to dispose Excel com object using VB.NET?中为您添加了一些内容。
我不知道您在打开工作簿的命令中使用= True
的意图,因此我将其遗漏了。
Option Strict On
Imports System.IO
Imports Excel = Microsoft.Office.Interop.Excel
Public Sub DoCombine()
Dim objApp As New Excel.Application
Dim objBook As Excel.Workbook
Dim objSheet As Excel.Worksheet
Dim folderPath As String = Txt_GetPath.Text
For Each excelFile In Directory.EnumerateFiles(folderPath, "*.xls")
objBook = objApp.Workbooks.Open(Filename:=excelFile)
objBook.Activate()
For Each objSheet In objBook.Sheets
objSheet.Copy(After:=objBook.Sheets(1))
Next objSheet
objBook.Close()
Next
objApp.Quit()
End Sub
Public Sub Combine()
' Call the method to do the actual work
DoCombine()
' Now Let the GC clean up (twice, to clean up cycles too)
GC.Collect()
GC.WaitForPendingFinalizers()
GC.Collect()
GC.WaitForPendingFinalizers()
End Sub
使用Combine()
方法-它会调用您在DoCombine()
方法中使用的代码,并确保计算机上没有剩余的大量Excel副本–您会在任务管理器,即使它们不在屏幕上。
使用Option Strict On
(几乎)总是一个好主意,因为它可以使Visual Studio向您显示代码中有些地方不正确。
答案 1 :(得分:0)
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim strFileName As String
Dim xl As New Excel.Application
Dim wb As Excel.Workbook
Dim ws As Excel.Worksheet
If FolderBrowserDialog1.ShowDialog = System.Windows.Forms.DialogResult.OK Then
Dim Directory = FolderBrowserDialog1.SelectedPath
Dim Files() As System.IO.FileInfo
Dim DirInfo As New System.IO.DirectoryInfo(Directory)
Files = DirInfo.GetFiles("*", IO.SearchOption.AllDirectories)
For Each File In Files
wb = xl.Workbooks.Open(File.FullName)
For Each ws In wb.Sheets
strFileName = Microsoft.VisualBasic.Left(File.Name,
(InStrRev(File.Name, ".", -1, vbTextCompare) - 1))
If ws.Name = "SCHEDULE" Then
ws.Range("S7", "S50").Value2 = strFileName
End If
Next
wb.Close()
Next
xl.Quit()
End If
End Sub