Extracting data in the same cell locations from multiple excel files into one single excel file

huangapple go评论59阅读模式
英文:

Extracting data in the same cell locations from multiple excel files into one single excel file

问题

我有一堆Excel文件,每个文件包含一个联系人姓名、公司名称、电话号码和电子邮件地址。我想从存储在文件夹中的所有单独Excel文件中提取这些信息(联系人姓名、公司名称、电话号码和电子邮件地址),然后将它们放入一个名为“Customers”的Excel文件中,分为四个标题(联系人姓名、公司名称、电话号码、电子邮件地址)。

所有信息都位于所有单独Excel文件的相同单元格位置。

Extracting data in the same cell locations from multiple excel files into one single excel file

如何根据这些单元格位置提取它们?并将它们导出到一个名为“Customers”的Excel文件中?

我尝试过Excel的“获取数据”命令,但没有成功。我对编程了解有限,但似乎没有非编程解决方案。

英文:

I have a bunch of excel files, each file contain a contact name, company name, phone number and email address. I would like to extract those information (contact name, company name, phone number and email address) from all the individual excel files sitting in a file folder and put them into one excel file called Customers under 4 headings (contact name, company name, phone number, email address).

All the information are located in the same cell locations for all the individual excel files.

Extracting data in the same cell locations from multiple excel files into one single excel file

How do I extract them based on those cell locations? and export them to one excel file called Customers?

I have tried excel get Data command but no success. I have limited knowledge of coding but it doesn't look like I have any non coding solution for this.

答案1

得分: 2

是的,有一个使用PowerQuery(也称为“获取数据”)的低代码/无代码解决方案:

  1. 选择数据 > 获取数据 > 从文件 > 从文件夹。

  2. 选择包含您想要合并的文件的文件夹。

  3. 文件夹中的文件列表将显示在<文件夹路径>对话框中。确保所有您想要的文件都在那里。

  4. 进一步的步骤选择合并 > 合并并加载。

  5. 在合并文件对话框中:选择一个文件用作样本数据,用于创建查询(在样本文件框中)。

我确信您不是第一个提出这个问题的人,所以您可能希望向您喜欢的搜索引擎寻求更多详细信息。

例如,可以参考以下链接:

https://support.microsoft.com/en-us/office/import-data-from-a-folder-with-multiple-files-power-query-94b8023c-2e66-4f6b-8c78-6a00041c90e4

英文:

Yes, there is a low code/no code solution with PowerQuery (aka “Get Data”):

  1. Select Data > Get Data > From File > From Folder.

  2. Select the folder containing the files you want to combine.

  3. A list of the files in the folder appears in the <Folder path> dialog box. Check that all the files you want are there.

  4. For further steps choose Combine > Combine & Load.

  5. In the Combine Files dialog box: select a file to use as sample data used to create the queries (in the Sample File box)

I am sure you are not the first with this question, so you may want to ask your favorite search engine for further details.

For example, there is:

https://support.microsoft.com/en-us/office/import-data-from-a-folder-with-multiple-files-power-query-94b8023c-2e66-4f6b-8c78-6a00041c90e4

答案2

得分: 1

假设每个文件要复制的范围是B4到B7
将子程序保存在“Customers”工作簿中

Sub CopyValuesFromFiles()
    Dim sourceFolder As String
    Dim sourceFiles As Object
    Dim sourceFile As Object
    Dim wbSource As Workbook
    Dim wsDestination As Worksheet
    Dim destinationRow As Long
    
    Application.ScreenUpdating = False
    Application.DisplayAlerts = False

    ' 设置源文件夹的路径,根据需要进行修改
    sourceFolder = "C:\Your\Source\Folder\Path"
    
    ' 设置目标工作表,根据需要修改工作表名称
    Set wsDestination = ThisWorkbook.Worksheets("Customers")
    
    ' 初始化目标行
    destinationRow = 2
    
    ' 创建一个用于处理文件的FileSystemObject
    Set sourceFiles = CreateObject("Scripting.FileSystemObject").GetFolder(sourceFolder).Files
    
    ' 遍历文件夹中的每个文件
    For Each sourceFile In sourceFiles
        ' 检查文件是否是Excel文件
        If sourceFile.Name Like "*.xls*" Then
            ' 打开源工作簿
            Set wbSource = Workbooks.Open(sourceFile.Path)
            
            ' 复制B4到B7范围的数值
            wbSource.Worksheets(1).Range("B4:B7").Copy
            
            ' 将数值粘贴到目标工作表
            wsDestination.Range("A" & destinationRow).PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=True
            
            ' 为下一组数值更新目标行
            destinationRow = destinationRow + 1
            
            ' 不保存更改关闭源工作簿
            wbSource.Close SaveChanges:=False
        End If
    Next sourceFile
    
    ' 清空剪贴板
    Application.CutCopyMode = False
    
    ' 复制完成时显示消息
    MsgBox "从文件复制客户信息完成。"

    Application.ScreenUpdating = True
    Application.DisplayAlerts = True
End Sub

这是您提供的VBA代码的中文翻译部分。

英文:

assuming the range to copy for each file is B4 to B7
save the sub in the Customers workbook

Sub CopyValuesFromFiles()
    Dim sourceFolder As String
    Dim sourceFiles As Object
    Dim sourceFile As Object
    Dim wbSource As Workbook
    Dim wsDestination As Worksheet
    Dim destinationRow As Long
    
Application.ScreenUpdating = False
Application.DisplayAlerts = False

    &#39; Set the path to the source folder modify accordingly
    sourceFolder = &quot;C:\Your\Source\Folder\Path&quot;
    
    &#39; Set the destination worksheet modify sheet name accordingly
    Set wsDestination = ThisWorkbook.Worksheets(&quot;Customers&quot;)
    
    &#39; Initialize the destination row
    destinationRow = 2
    
    &#39; Create a FileSystemObject to work with files in the folder
    Set sourceFiles = CreateObject(&quot;Scripting.FileSystemObject&quot;).GetFolder(sourceFolder).Files
    
    &#39; Loop through each file in the folder
    For Each sourceFile In sourceFiles
        &#39; Check if the file is an Excel file
        If sourceFile.Name Like &quot;*.xls*&quot; Then
            &#39; Open the source workbook
            Set wbSource = Workbooks.Open(sourceFile.Path)
            
            &#39; Copy the values from B4 to B7
            wbSource.Worksheets(1).Range(&quot;B4:B7&quot;).Copy
            
            &#39; Paste the values to the destination worksheet
            wsDestination.Range(&quot;A&quot; &amp; destinationRow).PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=True
            
            &#39; Update the destination row for the next set of values
            destinationRow = destinationRow + 1
            
            &#39; Close the source workbook without saving changes
            wbSource.Close SaveChanges:=False
        End If
    Next sourceFile
    
    &#39; Clear the clipboard
    Application.CutCopyMode = False
    
    &#39; Display a message when the copying is complete
    MsgBox &quot;Copying customer information from files complete.&quot;

Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub

答案3

得分: 0

这可以通过使用 openpyxl 完成。文档写得很好。确保仔细阅读。

import os
import openpyxl

# 存储所有电子表格的目录
# 假设所有文件都是电子表格
DIR = r"C:\Users\Todd Bonzalez\Desktop\Spreadsheets"

# 电子表格中的详细信息将存储在字典列表中
records = []

# 遍历目录中的每个文件,加载电子表格,记录值并附加到记录列表中

for filename in os.listdir(DIR):
    filepath = os.path.join(DIR, filename)

    wb = openpyxl.load_workbook(filepath)
    ws = wb[wb.sheetnames[0]] # 获取第一个工作表
    
    record = {}
    # 键 = 输出电子表格中的列名
    record["联系人姓名"] = ws["B4"].value
    record["公司名称"] = ws["B5"].value
    record["电话号码"] = ws["B6"].value
    record["电子邮件地址"] = ws["B7"].value
    records.append(record)

# 创建一个新的电子表格
wb = openpyxl.Workbook()
ws = wb.active

# 写入标题行
ws.append(tuple(record))

# 写入记录
for record in records:
    ws.append(tuple(record.values()))

# 保存
wb.save("combined.xlsx")

# 启动新的电子表格
os.startfile("combined.xlsx")
英文:

This can be done by using openpyxl. The documentation is pretty good. Be sure to get it a good read.

import os
import openpyxl

# The directory with all the spreadsheets
# All files assumed to be only spreadsheets
DIR = r&quot;C:\Users\Todd Bonzalez\Desktop\Spreadsheets&quot;

# The details from the spreadsheet will be stored in a list of dicts
records = []

# Iterate over every file in the directory, load the spreadsheet, record the 
# values and append to the records list

for filename in os.listdir(DIR):
    filepath = os.path.join(DIR, filename)

    wb = openpyxl.load_workbook(filepath)
    ws = wb[wb.sheetnames[0]] # Get the first sheet
    
    record = {}
    # key = column name in the output spreadsheet
    record[&quot;Contact name&quot;] = ws[&quot;B4&quot;].value
    record[&quot;Company name&quot;] = ws[&quot;B5&quot;].value
    record[&quot;Phone number&quot;] = ws[&quot;B6&quot;].value
    record[&quot;Email address&quot;] = ws[&quot;B7&quot;].value
    records.append(record)

# Create a new spreadsheet
wb = openpyxl.Workbook()
ws = wb.active

# Write header row
ws.append(tuple(record))

# Write records
for record in records:
    ws.append(tuple(record.values()))

# Save
wb.save(&quot;combined.xlsx&quot;)

# Launch the new spreadsheet
os.startfile(&quot;combined.xlsx&quot;)

答案4

得分: 0

你可以使用 INDIRECT 函数来完成这个操作,无需使用任何 Power Query、VBA 或其他代码。该函数接受一个字符串,并返回该字符串作为单元格引用时的值。

步骤如下:

  1. 获取要从中提取的文件列表(包括路径)。在Windows上,您可以在文件资源管理器中选择它们,按住 Shift 键,然后右键单击,然后选择“复制为路径”。(在其他操作系统上,我建议使用 ls 命令。)
  2. 将此列表放入Excel电子表格中,并将路径放入A列,文件名放入B列。(也可以使用公式完成此部分。)
  3. 然后在C1单元格中编写以下公式:=INDIRECT("&'""&A1&"\"&B1&""]Sheet1'!$B$4")
英文:

You can do this without any Power Query or VBA or other code using the INDIRECT function. This function takes a string and returns the value that string would have if you entered it as a cell reference.

Steps would be:

  1. Obtain a list of files (including paths) you want to extract from. On Windows you select them all in the file explorer, hold shift and right-click, then select "Copy as path". (On other operating systems I would suggest using the ls command.)
  2. Put this list into an Excel spreadsheet and separate the paths into column A and the filenames into column B. (A formula could do this part as well.)
  3. Then in C1 write a formula like: =INDIRECT("'"&A1&"["&B1&"]Sheet1'!$B$4")

huangapple
  • 本文由 发表于 2023年6月2日 10:44:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/76386833.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定