如何激活一个Excel工作簿,而不使用其名称或至less部分? 提取的表格具有dynamic名称

我几乎完成我的代码从我们公司的服务器提取数据,并将其粘贴到我已经创build,已经托pipe我的代码的工作表…问题是,我想从这个Excel工作簿,我从服务器但问题是,它有一个dynamic的名称,每当我从服务器检索它被改变。 但是,工作簿名称的初始部分不会改变,所以有没有一种方法可以只使用未更改的名称部分激活工作簿? 提取的工作簿的常量部分通常以BFUK开始,然后数字,空格和下划线以.txt.xls结尾“BFUK *****。txt.xls”

Sub test() Set objIE = CreateObject("InternetExplorer.Application") WebSite = "company website" logSite = "/logoff.do" With objIE .Visible = True .Navigate WebSite Do While .Busy Or .readyState <> 4 DoEvents Loop Set unElement = .Document.getElementsByName("username") unElement.Item(0).Value = "username" Set pwElement = .Document.getElementsByName("password") pwElement.Item(0).Value = "password" .Document.forms(0).submit '.quit Do While .Busy Or .readyState <> 4 DoEvents Loop Set expElement = .Document.getElementsByClassName("nav__action dropdown-trigger js--tooltip") expElement(0).Click Do While .Busy Or .readyState <> 4 DoEvents Loop .Document.getElementById("obb_EXPORT_EXCEL").Click End With application.Wait (Now + TimeValue("0:00:04")) SendKeys "%O", True With objIE .Navigate logSite > End With Windows("sheet with the dynamic name.xls").Activate ActiveSheet.Range("A1:BC600").Copy Windows("macro testing.xlsm").Activate Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _ :=False, Transpose:=False [L:L].Select With Selection .NumberFormat = "General" .Value = .Value End With End Sub 

我真的很需要这个家伙,所以我会感谢你的帮助,如果能完成这项工作,我欢迎新的想法。

在这里你有一个页面如何列出目录中的所有文件 。 一旦你有文件的名字,你可以像这样比较它:

 If fileName Like "BFUK*.txt.xls" Then Windows(fileName) .... 'rest of your code... End If 

它将匹配以“BFUK”开始并以“.txt.xls”结尾的文件的名称。 之间可以是任何数量的任何字符。

这里是macros的例子:

 Sub ListFilesMatchingPattern() Dim objFSO, objFolder, objFile As Object Dim i As Integer Dim path As String 'choose folder with your Excel files Application.FileDialog(msoFileDialogFolderPicker).Show path = Application.FileDialog(msoFileDialogFolderPicker).SelectedItems(1) 'Create an instance of the FileSystemObject Set objFSO = CreateObject("Scripting.FileSystemObject") 'Get the folder object Set objFolder = objFSO.GetFolder(path) i = 1 'loops through each file in the directory and prints their names For Each objFile In objFolder.Files 'open the Excel file if it matches pattern If objFile.Name Like "BFUK*txt.xls" Then 'in your macro, you should do work on the file here Workbooks.Open (path & "\" & objFile.Name) End If Next objFile End Sub 

@Michal我发现它,并最终工作

 > > Sub Tester() > > Const File_PATH As String = "C:\Users\Ali\Desktop\Ali\" > > > Dim file As String > > file = Dir$(File_PATH & "BFUK*" & ".xlsx") > > If (Len(file) > 0) Then Workbooks.Open(File_PATH & file).Activate > End If > > End Sub 

我唯一的方法是使用SendKeys "%S", True将文件保存在特定的文件夹中,然后上面的代码调用它