所以我正在尝试创建一个将打开文件资源管理器的宏。然后,这将允许我选择要从中扫描数据的特定工作簿。
这是我当前的代码,导致错误 424,需要对象:
Sub getDataFromWbs()
Dim wb As Workbook, ws As Worksheet
Set fso = CreateObject("Scripting.FileSystemObject")
'This is where you put YOUR folder name
Dim sFolder As String
' Open the select folder prompt
With Application.FileDialog(msoFileDialogFolderPicker)
If .Show = -1 Then ' if OK is pressed
sFolder = .SelectedItems(1)
End If
End With
If sFolder <> "" Then ' if a file was chosen
'Next available Row on Master Workbook
y = ThisWorkbook.Sheets("sheet1").Cells(Rows.Count, 1).End(xlUp).Row + 1
'Loop through each file in that folder
'THE LINE UNDER THIS GETS THE ERROR
For Each wbFile In fldr.Files
'Make sure looping only through files ending in .xlsx (Excel files)
If fso.GetExtensionName(wbFile.Name) = "xlsx" Then
'Open current book
Set wb = Workbooks.Open(wbFile.Path)
'Loop through each sheet (ws)
For Each ws In wb.Sheets
'check WS name
If UCase(ws.Name) = "DATA" Then
'Last row in that sheet (ws)
wsLR = ws.Cells(Rows.Count, 1).End(xlUp).Row
'Loop through each record (row 2 through last row)
For x = 2 To wsLR
'Put column 1,2,3 and 4 of current sheet (ws) into row y of master sheet, then increase row y to next row
ThisWorkbook.Sheets("sheet1").Cells(y, 1) = ws.Cells(x, 1) 'col 1
ThisWorkbook.Sheets("sheet1").Cells(y, 2) = ws.Cells(x, 2) 'col 1
ThisWorkbook.Sheets("sheet1").Cells(y, 3) = ws.Cells(x, 3) 'col 1
ThisWorkbook.Sheets("sheet1").Cells(y, 4) = ws.Cells(x, 4) 'col 1
ThisWorkbook.Sheets("sheet1").Cells(y, 5) = ws.Cells(x, 5) 'col 1
y = y + 1
Next x
End If
Next ws
'Close current book
wb.Close
End If
Next wbFile
End If
End Sub
请注意,当我运行代码时,它会打开文件资源管理器,但是没有可见的 Excel 工作簿,只有文件夹
最佳答案
声明以下内容
Dim Fso As FileSystemObject, fldr As Folder
然后在
If sfolder <> "" Then
之后添加 Set fldr = Fso.GetFolder(sfolder)
最好使用
.value
正在将数据提取到 ThisWorkbook.Sheets("sheet1")
的位置
关于excel - 使用 vba 选择要在其中扫描特定工作表以获取数据的文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53146890/