以下是我发生的问题。我使用MS Excel 2013.Excel 2013无法在ThisWorkbook目录中找到并打开文件
使用下面的宏,我试图找到那些帐户(符合条件“范围内”,例如帐户12345678),复制它们以搜索相同的文件夹(其中ThisWorkbook是) ,找到另一个excel文件,其名称为账户号码(例如“12345678.xlsx”)并将其打开。
在下面提出的更正后,我的宏查找并打开所需的文件。但现在的问题是,无法对其执行任何操作:复制,粘贴等。
请问您可以帮忙吗?
Sub FileFinder()
'Excel variables:
Dim RngS As Excel.Range
Dim wbResults As Workbook
'Go to the column with specific text
Worksheets("Accounts source data").Activate
X = 3
Y = 25
While Not IsEmpty(Sheets("Accounts source data").Cells(X, Y))
Sheets("Accounts source data").Cells(X, Y).Select
If ActiveCell = "In scope" Then
Sheets("Accounts source data").Cells(X, Y - 22).Select
'Copy the account in scope
Set RngS = Selection
Selection.Copy
'Search, in same directory where the file is located, the file with that account (file comes with account number as name)
sDir = Dir$(ThisWorkbook.Path & "\" & RngS & ".xlsx", vbNormal)
Set oWB = Workbooks.Open(ThisWorkbook.Path & "\" & sDir)
'Here is where my error occurs
'[Run-time error 5: Invalid procedure call or argument]
Sheet2.Cells("B27:B30").Copy
oWB.Close
End If
X = X + 1
Wend
End Sub
最有可能你缺少ThisWorkbook.Path'之间'的“\”分隔符和文件名 –
什么@ShaiRado说。解决该问题后:'Sheets()'隐式引用'ActiveWorkbook'。执行Workbooks.Open时,新打开的工作簿将成为“ActiveWorkbook”。阅读[这里](https://stackoverflow.com/documentation/excel-vba/1576/common-mistakes/5110/qualifying-references)了解更多信息。您也可以通过阅读[this](https://stackoverflow.com/documentation/excel-vba/1107/vba-best-practices/9292/avoid-using-select-or-activate)来避免很多问题。快速阅读,不幸的是文档正在消失。 – FreeMan
@FreeMan - 我知道我的代码并不像应该那么优雅,但我是VBA的初学者。下一步的改进将会出现!谢谢! ;) – VSE