我尝试创建一个程序,可以收集每个“UTP”表在一个文件夹到一个“主UTP”工作簿(位于同一个文件夹)
所以,首先我需要读取文件夹中的所有文件xls。复制“UTP”表并将其粘贴到“主UTP”。然后再次循环。
这是我在“Master UTP”中编写的代码:
Public Sub myImport()
Dim sPathName As String, sFileName As String
Dim sourceWb As Workbook, targetWb As Workbook
Set sourceWb = ActiveWorkbook
sPathName = ThisWorkbook.Path & "\"
sFileName = Dir(sPathName & "*.xls", vbNormal)
Do While Len(sFileName) > 0
sFileName = sPathName & sFileName
If sFileName <> sourceWb Then
Set targetWb = Workbooks.Open(sName)
targetWb.Sheets("UTP").Copy After:=sourceWb.Sheets("Master UTP")
targetWb.Close
End If
sFileName = Dir
Loop
End Sub
这个程序中还有一些错误。请帮帮我谢谢
4条答案
按热度按时间5rgfhyps1#
基于@chrisneilsen的解决方案,这里有一个更紧凑的代码:
如果可以安全地假设
ActiveWorkbook
是“宏”的话,则其应该甚至稍微更紧凑,即,在它的名字中有一个“xlsm”类型,所以它永远不能匹配任何“xls”名字:最后,您可以在打开任何xls文件时消除 Flink ,因此您可以将循环包含在
Application.ScreenUpdating = False/True
语句中:evrscar22#
第一个问题是您尝试打开
sName
而不是sFileName
(使用Option Explicit
将检测到此错误)第二个问题,您正在将字符串与
If sFileName <> sourceWb Then
中的工作簿进行比较第三个问题,
workbook.name
不包含路径您的代码,重构,并添加了一些错误处理
dwthyt8l3#
代码看起来很好,除了在尝试打开其他工作簿时出现错误。您尝试从从未使用过的变量
sName
打开工作簿。您还不必要地重置了sFileName
变量,而是尝试使用sPathName & sFileName
作为Workbooks.Open()
的输入。此外,您尝试比较
sFileName
和sourceWb
这两种不同的数据类型,而不是比较sFileName
和sourceWb.Name
。最后,假设工作簿将有一个名为
"UTP"
的工作表,如果没有,代码将崩溃。而是先检查表是否存在。查看https://stackoverflow.com/a/6040390/8520655了解更多信息。请看下面的例子; Public Sub myImport()Dim sPathName As String,sFileName As String Dim sourceWb As Workbook,targetWb As Workbook
sz81bmfz4#
Sub ImportFirstSheet()Dim filePath As Variant Dim wb Source As Workbook Dim wsSource As Worksheet Dim wsDestination As Worksheet Dim destRange As Range
结束子
Sub HighlightCellsContainingSearchString()Dim searchString As String Dim searchRange As Range Dim cell As Range
结束子