以下是我發生的問題。我使用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