|
现在有这个需求:遍历的选择文件夹中所有excel文件,并把所有excel文件有值列实现自动列宽。
拟写代码如下:
Public Sub SmFilePathSelectBox1_TextChanged(sender As Object,e As System.EventArgs)
Dim ExlApp As Microsoft.Office.Interop.Excel.Application
Dim ExlBook As Microsoft.Office.Interop.Excel.Workbook
Dim ExlSheet As Microsoft.Office.Interop.Excel.Worksheet
Dim smFpb As SmFilePathSelectBox = sender
Dim diTop As New DirectoryInfo(smFpb.Value) '未实现仅excel文件筛选
Dim Slb As SmListBox = Me.SmForm.Controls("SmListBox1")
For Each fi As Object In ditop.EnumerateFiles()
ExlBook = ExlApp.Workbooks.Open(fi.fullname)
ExlSheet = ExlBook.Worksheets(0)
ExlSheet... '未实现自动列宽
Slb.Items.add(fi.name)
Next
End Sub
参考宏代码:
Dim dataExcel As Object, myPath$, myFile$, WB As Workbook '这个$是相当于定义字符串
Set dataExcel = CreateObject("Excel.application")
myPath = ActiveSheet.Range("B2").Value '把文件路径定义给变量,这里请自行更改,记得最后要加一个反斜杠
myFile = Dir(myPath & "*.xls*") '依次找寻指定路径中的*.x1s,或者x1sx文件
Do While myFile <> "" '当指定路径中有文件时进行循环
If myFile <> ThisWorkbook.Name Then '如果我们这个宏文件在需要处理的文件夹之中,这个判断就会跳过下面的操作
Set WB = dataExcel.Workbooks.Open(myPath & myFile) '打开符合要求的文件
Columns("A:N").Select
Columns("A:N").EntireColumn.AutoFit
WB.Save
WB.Close 1 '保存文件直接关闭
End If
myFile = Dir '找寻下一个*.x15,或者x1sx文件
Loop
Set WB = Nothing '释放变量内存
|
|