excel - 使用 vba 选择要在其中扫描特定工作表以获取数据的文件夹

标签 excel vba

所以我正在尝试创建一个将打开文件资源管理器的宏。然后,这将允许我选择要从中扫描数据的特定工作簿。
这是我当前的代码,导致错误 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/

相关文章:

python - 使用python将多个excel文件转换为csv文件

vba - 创建一个宏,复制列中的特定数据并将数据粘贴到不同工作簿的不同列中

vba - VBA 中的 StringFromIID - 避免手动管理内存的好方法是什么?

excel - 减少重复代码以避免 "Procedure Too Large"错误

vba - Err.Raise 的 COM 错误号在哪里注册?

Excel 每行分隔一个单元格值

c# - 通过 Workbook_Open 事件更改 VSTO 选项卡的可见属性

excel - 如果从范围中删除数据,则删除时间戳

excel - Office Open XML satMod 导致超过 100% 的饱和度

ms-access - MS Access/VBA : add if condition to vba code