我有一个xlsm,amonst其他人运行目录中的所有.xslx文件,运行sub,保存它们。 (谢谢你Tabias) 在这个子里面,我现在正在尝试添加一些可以添加第三个文件中最后一列的内容。 我的第一个问题是如何定义源文件。我们需要从具有类似名称的确切文件中获取数据。所以MC.xslx要从MC12february.xlsx复制,而KA.xlsx必须从KAwhateverdate.xlsx导入
query = query.replace(comp, "");
不幸的是,active.workbook.name包含了扩展,所以或者你们可以告诉我一个解决方案或者我必须首先保存文件date + name并将其更改为Set wbA = Workbooks.Open("C:\files" & "\" & ActiveWorkbook.Name & "*.xlsx")
对吗?
表格也是如此。根据文件,这些将被称为MC,KA,KC,...... 接下来,因为我只想将文件的最后一列复制到另一个文件的最后一列,我很困惑。 I found this code并认为这是最容易理解的。
wbA = Workbooks.Open("C:\files" & "\*" & ActiveWorkbook.Name)
更简单的解决方案似乎也不合适。 example
如您所见,我完全坚持如何定义最后一列和工作表的名称。这段代码是不完整的,我可以通过这样做来检查。有人能把我放在正确的道路上吗?谢谢。
答案 0 :(得分:0)
作为补充,我建议创建一个simeple,可重用的文件打开函数,您可以在其中提供一个文件名作为您想要搜索的字符串。该函数将遍历一个目录(如蝙蝠侠建议的那样),并可选择拉出该文件的最新版本(使用修改日期)。下面是我经常使用的一组函数。有一个子文件夹参数`subF',允许您在子文件夹中搜索相对于当前文件位置。
'FUNCTION opnWB
'--Opens a workbook based on filename parameter
'----WILDCARDS before and after the filename are used to allow for filename flexibility
'----Subfolder is an OPTIONAL PARAMETER used if the location of the file is located in a subfolder
Public Function opnWB(ByVal flNM As String, Optional ByVal subF As String = "") As Workbook
If subF <> "" Then subF = "\" & subF
Dim pthWB As String
pthWB = "\*" & flNM & "*" 'wildcard characters before and after filename
pthWB = filePull(subF, pthWB)
Set opnWB = Workbooks.Open(ActiveWorkbook.path & subF & "\" & pthWB, UpdateLinks:=0)
End Function
'FUNCTION filePull
'--Cycles through folder for files that match the filename parameter (with WILDCARDS)
'--If there is more than one file that matches the filename criteria (with WILDCARDS),
'----the file "Date Modified" attribute is used and the most recent file is "selected"
Private Function filePull(ByVal subF As String, ByVal path As String) As String
Dim lDate, temp As Date
Dim rtrnFl, curFile As String
Filename = Dir(ActiveWorkbook.path & subF & path)
Do While Filename <> ""
curFile = Filename
curFile = ActiveWorkbook.path & subF & "\" & Filename
If lDate = 0 Then
rtrnFl = Filename
lDate = GetModDate(curFile)
Else
temp = GetModDate(curFile)
End If
If temp > lDate Then
rtrnFl = Filename
lDate = temp
End If
Filename = Dir()
Loop
filePull = rtrnFl
End Function
'FUNCTION GetModDate
'--Returns the date a file was last modified
Public Function GetModDate(ByVal filePath As String) As Date
GetModDate = CreateObject("Scripting.FileSystemObject").GetFile(filePath).DateLastModified
End Function
您可以通过简单地删除flNM
之前的通配符来调整此方法,其中文件名必须通过传入的String来启动文件。要使用,您只需调用opnWB
函数,传入“MC”或您要打开的任何常规文件名:
Dim wbTarMC as Workbook
Set wbMC = opnWB("MC", "Source Files") 'this would open up MC.xlsx file within the subfolder "Source Files" (relative to current file location)
希望这有帮助。