Populating Columns in Sheet 2 with Information from Sheet 1

Abstract: Use VBA to populate Sheet 2 columns with data from Sheet 1 by matching unique IDs.

Created: 2026-10-15 by
You can populate columns in Sheet 2 with data from Sheet 1 by writing a VBA macro that iterates through the ID column in Sheet 2, uses the Application.Match function to find the corresponding row in Sheet 1, and copies the values from specific columns into the adjacent cells. This approach ensures accurate data alignment based on unique identifiers without manual intervention or complex formulas that might break if rows are inserted or deleted.

Understanding the Data Structure

Before writing the code, it is essential to define how your two worksheets are structured. Assume Sheet1 acts as the master database where all information resides. It typically contains an ID number in the first column (Column A) and other details like names or addresses in subsequent columns. Sheet2 serves as the target sheet where you want to pull this information. It also has an ID column in Column A, but the adjacent columns (B, C, D, etc.) are empty and need to be filled with data from Sheet1. The core logic relies on matching the ID in Sheet2 with the ID in Sheet1. If the IDs match, the script retrieves the value from the specified column in Sheet1 and places it into the correct cell in Sheet2. This method is robust because it does not rely on row positions remaining static; it only cares about the unique ID value.

Setting Up the VBA Editor

To begin, press Alt + F11 to open the Visual Basic for Applications editor in Excel. From the menu bar, select Insert and then Module to create a new blank module. This is where you will paste the VBA code. Ensure that your workbook is saved as a macro-enabled file with the extension .xlsm, otherwise the code will not be preserved when you close the application. You should also enable macros in your trust center settings to allow the script to run securely.

The VBA Code Solution

The following code demonstrates a reliable way to perform this task. It uses a loop to check each ID in Sheet2 against the list in Sheet1. The key component here is the Application.Match function, which returns the relative position of the lookup value within a range. If a match is found, the code proceeds to copy the data; if not, it skips that row to avoid errors.
Sub PopulateSheet2FromSheet1()
    Dim wsSource As Worksheet
    Dim wsTarget As Worksheet
    Dim lastRowSource As Long
    Dim lastRowTarget As Long
    Dim i As Long
    Dim matchRow As Variant
    Dim colIndex As Integer
    
    ' Set references to your sheets
    Set wsSource = ThisWorkbook.Sheets("Sheet1")
    Set wsTarget = ThisWorkbook.Sheets("Sheet2")
    
    ' Find the last row with data in both sheets
    lastRowSource = wsSource.Cells(wsSource.Rows.Count, "A").End(xlUp).Row
    lastRowTarget = wsTarget.Cells(wsTarget.Rows.Count, "A").End(xlUp).Row
    
    ' Loop through each ID in Sheet2
    For i = 2 To lastRowTarget ' Assuming row 1 is headers
        ' Clear previous data in column B for this row
        wsTarget.Cells(i, 2).Value = ""
        
        ' Try to find the ID from Sheet2 in Sheet1's Column A
        On Error Resume Next
        matchRow = Application.Match(wsTarget.Cells(i, 1).Value, wsSource.Columns(1), 0)
        On Error GoTo 0
        
        ' If a match is found, copy data from Column B of Sheet1 to Column B of Sheet2
        If Not IsError(matchRow) Then
            wsTarget.Cells(i, 2).Value = wsSource.Cells(matchRow, 2).Value
            ' You can add more lines to copy other columns, e.g., Column C:
            ' wsTarget.Cells(i, 3).Value = wsSource.Cells(matchRow, 3).Value
        End If
    Next i
    
    MsgBox "Data population complete.", vbInformation
End Sub
This script starts at row 2 to skip headers, which is a common best practice. It clears any existing data in the target column before populating it to ensure no stale information remains. The On Error Resume Next block is used carefully around the Match function to handle cases where an ID in Sheet2 does not exist in Sheet1. Instead of crashing the macro, it assigns an error value, which is then checked using IsError. This makes the process safe for datasets with missing matches.

Extending the Logic for Multiple Columns

Often, you will need to populate more than just one column. To do this, simply replicate the line inside the If Not IsError(matchRow) block. For example, if you want to copy data from Column C in Sheet1 to Column C in Sheet2, add wsTarget.Cells(i, 3).Value = wsSource.Cells(matchRow, 3).Value. You can continue this pattern for as many columns as needed. However, for very large datasets involving hundreds of thousands of rows, looping cell-by-cell can be slow. In such cases, consider loading the data into arrays as described in Macro Development: Looping Two Arrays in Excel VBA to significantly improve performance.

Running and Testing the Macro

Once the code is entered, close the VBA editor and return to Excel. Press Alt + F8 to open the Macro dialog box, select PopulateSheet2FromSheet1, and click Run. Verify the results by checking a few rows in Sheet2 to ensure the data matches the corresponding IDs in Sheet1. If you encounter issues, check that the sheet names in the code exactly match your actual sheet tabs, including capitalization. Also, ensure there are no leading or trailing spaces in your ID numbers, as these can cause match failures. For more insights on navigating between sheets efficiently, see Excel: Switching Referenced Sheet to Another.

Frequently Asked Questions

What happens if an ID in Sheet 2 is not in Sheet 1?

The macro will skip that row and leave the target cell empty or unchanged, depending on your initial setup. It does not throw an error because the IsError check handles the mismatch gracefully.

Can I use this method for non-numeric IDs?

Yes, the Application.Match function works equally well with text strings. Just ensure that the format of the text in both sheets is identical, including case sensitivity if applicable, though standard matching is usually case-insensitive.

How do I speed up the macro for large datasets?

For datasets exceeding 10,000 rows, consider disabling screen updating by adding Application.ScreenUpdating = False at the start of the sub and setting it back to True at the end. Additionally, using array-based processing as mentioned in related articles can drastically reduce execution time.

Why is my macro returning #N/A errors?

This usually indicates that the Match function failed to find the ID. Check for hidden spaces in your ID columns using the TRIM function or ensure that the data types (text vs. number) match exactly between the two sheets.

Do I need to reference specific sheet names in the code?

Yes, the code explicitly sets wsSource and wsTarget to "Sheet1" and "Sheet2". If your sheets have different names, you must update these string literals in the code to match your actual worksheet names.
Tags: Excel VBA Macro

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More