用Excel提取数据

发布于 2024-07-29 05:43:15 字数 140 浏览 4 评论 0原文

我每月收到 100 多个 Excel 电子表格,我从中选取固定范围并粘贴到其他电子表格中以制作报告。

我正在尝试编写一个 VBA 脚本来迭代我的 Excel 文件并将范围复制到一个电子表格中,但我无法做到这一点。

是否有捷径可寻?

I monthly receive 100+ Excel spreadsheets from which I take a fixed range and paste in other spreadsheets to make a report.

I'm trying to write a VBA script to iterate my Excel files and copy the range in one spreadsheet, but I haven't been able to do it.

Is there an easy way to do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

李白 2024-08-05 05:43:15

下面是一些 VBA 代码,演示了对目录中的一堆 Excel 文件进行迭代并打开每个文件:

Dim sourcePath As String
Dim curFile As String
Dim curWB As Excel.Workbook
Dim destWB As Excel.Workbook

Set destWB = ActiveWorkbook
sourcePath = "C:\files"

curFile = Dir(sourcePath & "\*.xls")
While curFile <> ""
    Set curWB = Workbooks.Open(sourcePath & "\" & curFile)

    curWB.Close
    curFile = Dir()
Wend 

希望这对于您使用现有的宏代码来说是一个足够好的起点。

Here's some VBA code that demonstrates iterating over a bunch of Excel files in a directory and opening each one:

Dim sourcePath As String
Dim curFile As String
Dim curWB As Excel.Workbook
Dim destWB As Excel.Workbook

Set destWB = ActiveWorkbook
sourcePath = "C:\files"

curFile = Dir(sourcePath & "\*.xls")
While curFile <> ""
    Set curWB = Workbooks.Open(sourcePath & "\" & curFile)

    curWB.Close
    curFile = Dir()
Wend 

Hopefully that'll be a good enough starting point for you to work your existing macro code.

坦然微笑 2024-08-05 05:43:15

我几年前写过这篇文章,但也许​​它会对你有所帮助。 我添加了最新版本 Excel (xlsx) 的扩展名。 似乎有效。

Sub MergeExcelDocs()
    Dim lastRow As Integer
    Dim docPath As String
    Dim baseCell As Excel.range
    Dim sysObj As Variant, folderObj As Variant, fileObj As Variant
    Application.ScreenUpdating = False
    docPath = Application.GetOpenFilename(FileFilter:="Text Files (*.txt),*.txt,Excel Files (*.xls),*.xls,Excel 2007 Files (*.xlsx),*.xlsx", FilterIndex:=2, Title:="Choose any file")
    Workbooks.Add
    Set baseCell = range("A1")
    Set sysObj = CreateObject("scripting.filesystemobject")
    Set fileObj = sysObj.getFile(docPath)
    Set folderObj = fileObj.ParentFolder
    For Each fileObj In folderObj.Files
        Workbooks.Open Filename:=fileObj.path
        range(range("A1"), ActiveCell.SpecialCells(xlLastCell)).Copy
        lastRow = baseCell.SpecialCells(xlLastCell).row
        baseCell.Offset(lastRow, 0).PasteSpecial (xlPasteValues)
        baseCell.Copy
        ActiveWindow.Close SaveChanges:=False
    Next
End Sub

编辑:

我应该提到它是如何工作的。 当您启动宏时,它会弹出一个“打开文件”对话框。 双击列表中的第一个文件(或任何与此相关的文件)。 它将创建一个新的工作簿,然后循环遍历文件夹中的所有文件。 对于每个文件,它会复制第一个工作表中的所有内容并将其粘贴到新工作簿的末尾。 这几乎就是全部内容了。

I wrote this years ago, but maybe it will help you out. I added the extension for the latest version of Excel (xlsx). Seems to work.

Sub MergeExcelDocs()
    Dim lastRow As Integer
    Dim docPath As String
    Dim baseCell As Excel.range
    Dim sysObj As Variant, folderObj As Variant, fileObj As Variant
    Application.ScreenUpdating = False
    docPath = Application.GetOpenFilename(FileFilter:="Text Files (*.txt),*.txt,Excel Files (*.xls),*.xls,Excel 2007 Files (*.xlsx),*.xlsx", FilterIndex:=2, Title:="Choose any file")
    Workbooks.Add
    Set baseCell = range("A1")
    Set sysObj = CreateObject("scripting.filesystemobject")
    Set fileObj = sysObj.getFile(docPath)
    Set folderObj = fileObj.ParentFolder
    For Each fileObj In folderObj.Files
        Workbooks.Open Filename:=fileObj.path
        range(range("A1"), ActiveCell.SpecialCells(xlLastCell)).Copy
        lastRow = baseCell.SpecialCells(xlLastCell).row
        baseCell.Offset(lastRow, 0).PasteSpecial (xlPasteValues)
        baseCell.Copy
        ActiveWindow.Close SaveChanges:=False
    Next
End Sub

EDIT:

I should mention how it works. When you start the macro, it brings up an Open File dialog. Double-click the first file in the list (or any file for that matter). It will create a new workbook then loop through all the files in the folder. For each file, it copies all the content from the first worksheet and pastes it at the end of the new workbook. That's pretty much all there is to it.

紅太極 2024-08-05 05:43:15

另一个解决方案是让您的汇总电子表格通过文件名访问其他电子表格并获取数据本身。

为此,您需要同时打开所有电子表格,以便它可以更新链接,但这仍然可能比一次打开并复制/粘贴一个电子表格更快,即使使用宏也是如此。 每个电子表格都需要有一个唯一的文件名。

如果电子表格的名称在您收到之前不知道,或者它们定期更改,请在汇总表中创建一列来存储工作表的文件名,然后使用字符串操作构建所需的地址并获取数据使用间接()。

从一个特定文件中获取一个数据单元格的示例:

=INDIRECT("'[C:\path\workbook.xls]MyWorksheet'!$A$2")

对您想要获取的每个电子表格的每个单元格进行冲洗并重复上述操作。

您应该清楚如何将字符串传递给 INDIRECT()。 将其构建为公式,以便您可以对需要检索的每个单元格使用相同的公式。

示例:

= INDIRECT("'[" & $A2 & "]MyWorksheet'!$" & ADDRESS(3, COL()))

上面的公式将转到文件名为 $A2 的电子表格(请注意“2”之前缺少 $,以便您可以将相同的公式粘贴到其他文件的其他行),并获取MyWorksheet 工作表位于第三行和当前 列(因此,如果该工作表位于汇总的 B2 中,则它会从其他文件获取 B3)。

调整 ADDRESS 函数以添加所需行和列的偏移量。

上述解决方案的优点是,可以在需要填充的行和列中复制并粘贴相同的公式,Excel 将根据需要调整 $A2 和 COL()。 非常易于维护。

编辑曾经遇到过类似的情况,但我无法一次加载所有电子表格(超过 200 个)。 我认为我最终编写了 VBA,因此它没有实际打开并读取 Excel 文件。 相反,我让它循环遍历文件名,打开每个文件名的 ODBC 连接,并使用 ADO 从规定的命名范围中读取我需要的值(在 ODBC 中显示为“表”,工作表也显示为“表”) “但有关于允许的名称的规则)。 这比打开和关闭 Excel 文件要快得多,并且具有不会使 Excel 崩溃的额外优点。

Another solution is to have your roll-up spreadsheet access the other spreadsheets by filename and grab the data itself.

To do that, you'll need to have all of the spreadsheets open at the same time so it can update the links, but that's still probably faster than opening and copying/pasting one at a time, even with a macro. Every spreadsheet will need to have a unique filename.

If the names of the spreadsheets aren't known until you receive them, or they change regularly, create a column in your roll-up table to store the filename of the sheets, then build the address you need using string manipulation and get the data using INDIRECT().

Example to grab one cell of data from one particular file:

=INDIRECT("'[C:\path\workbook.xls]MyWorksheet'!$A$2")

Rinse and repeat the above for each cell of each spreadsheet you want to get.

You should be clever about how to get the string to pass to INDIRECT(). Build it as a formula so you can use literally the same formula for every cell you need to retrieve.

Example:

= INDIRECT("'[" & $A2 & "]MyWorksheet'!$" & ADDRESS(3, COL()))

The formula above will go to the spreadsheet whose filename is in $A2 (note the lack of $ before "2" so you can paste the same formula to other rows for other files), and get the value of the cell on the MyWorksheet sheet on row three and the current column (so, if this is in B2 on your roll-up, it gets B3 from the other file).

Adjust the ADDRESS function to add offsets to the row and column needed.

The advantage of the solution above is that the same formula can be copied and pasted across the rows and columns you need to populate, and Excel will adjust the $A2 and COL() as needed. Very maintainable.

Edit once I had a similar situation, and I couldn't load all of the spreadsheets at once (more than 200). I think I ended up writing the VBA so it did not actually open and read the Excel files. Instead, I had it loop through the filenames, open an ODBC connection to each, and use ADO to read the values I needed from a prescribed named range (which appears as a "table" in ODBC--the worksheets also appear as "tables" but there are rules about allowed names). This was much faster than opening and closing Excel files, and had the added advantage of not crashing Excel.

⒈起吃苦の倖褔 2024-08-05 05:43:15

你是否尝试过

Tools->Macro->Record New Macro 

创建 maco 来做同样的事情

Did you try

Tools->Macro->Record New Macro 

to create maco to do the same thing

笨笨の傻瓜 2024-08-05 05:43:15

Rodrigo,

我猜您的意思是需要单独打开 100 多个工作簿,然后将其复制并粘贴到其中? 听起来很有趣:)

如果您可以将它们全部放在一个目录中,那么打开每个文件相当容易,请先搜索一下。 (@Mark Biek 为您发布了一个很好的示例)

打开文件后,我会将数据复制到 ADO 记录集中,然后您将附加到该记录集中。 我已经发布了一些代码,用于执行与合并多个非常相似的操作一本工作簿中的工作表。

这不完全是您所需要的,但应该有所帮助。 如果没有,请发布您走了多远,我将在本周内再看一次。

Rodrigo,

I'm guessing you mean 100+ workbooks that you need to individually open and copy and paste into one? Sounds like fun :)

If you could put them all in a single directory, opening each file is reasonably easy, have a search on that first. (@Mark Biek has posted a good example for you )

Once you have a file open, i would then copy the data into an ADO recordset which you would then append to. I have posted some code for a doing something very similar with merging multiple sheets in one workbook.

It's not exactly what you need, but it should help. If not, post how far you get and i'll have a another look during the week.

横笛休吹塞上声 2024-08-05 05:43:15

这可以通过使用 Access 中的 TransferSpreadsheet 来实现。
请参阅此链接:

This can be achieved by using TransferSpreadsheet in Access.
See this link:

http://datapigtechnologies.com/blog/index.php/using-access-to-combine-multiple-excel-files-method-2/comment-page-1/#comment-1741

This solution doesn't require any VBA.

反目相谮 2024-08-05 05:43:15

过去,我使用 VBA 创建外部引用(链接)。

我在这里发布了有关它的信息(参见示例 2):

最佳简短示例需要 Excel VBA

这与使用 INDIRECT 类似,但不需要打开 Excel 工作簿。

唯一的缺点是旧电脑或旧版本的 Excel(不确定是哪一个)会使此过程变慢。 我相信这是因为每次添加新的外部引用时,所有其他外部引用都会更新。 为了使其运行得更快,我将“计算”设置为“手动”,添加了外部引用,并将“计算”设置为“自动”以更新它们。

之后,如果您只需要这些值,可以使用“断开链接”或“复制并粘贴特殊值”。

In the past, I used VBA to create external references (links).

I posted about it here (see example 2):

Best short examples of the need for Excel VBA

It's similar to using INDIRECT, but without needing to have the excel workbooks open.

The only disadvantage is that an old computer or an old version of excel, not sure which, can make this process slow. I believe it is because every time a new external reference is added, all the other external references gets updated. In order to make it go faster, I set Calculation to Manual, added the external references, and set Calculation to Automatic to update them.

After that, if you just want the values, you can use Break Links, or Copy and Paste Special Values.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文