VBA Code: Lookup Value in Column (Sheet2) Matches Value in Column (Sheet1) - One-Click Data Validation

Abstract: Eliminate manual VLOOKUP clutter by using this VBA macro to instantly validate Sheet1 Column C against Sheet2 Column X with one click.

Created: 2026-09-03 by

Use this VBA macro to validate data in Sheet1 Column C against Sheet2 Column X. The script iterates through entered values, returning "True" for matches and "No" for mismatches, providing instant one-click feedback without manual lookup functions.

The Problem with Manual Validation

When working with large datasets in Excel, verifying that a specific entry exists in a reference list can be tedious. Traditionally, users might employ VLOOKUP or XLOOKUP formulas to check if a value from one sheet exists in another. However, these formulas require setting up helper columns, which clutters the workspace. Furthermore, if the reference data changes frequently, maintaining static formula references can lead to errors. A more dynamic approach involves using Visual Basic for Applications (VBA) to perform the check programmatically. This method allows for immediate feedback within the cell itself, eliminating the need for separate result columns and reducing the risk of formula breakage when rows are inserted or deleted.

Setting Up the VBA Environment

To implement this solution, you must access the VBA editor within your Excel workbook. Press Alt + F11 to open the Microsoft Visual Basic for Applications window. Once opened, navigate to the Insert menu and select Module. This action creates a new code module where you will paste the validation logic. It is crucial to save your workbook as a Macro-Enabled Workbook (.xlsm) to ensure the code persists after closing the file. If you attempt to save it as a standard .xlsx file, all VBA code will be permanently removed. For those concerned about security warnings, consider adjusting your Trust Center settings to allow macros from trusted locations, though this should be done with caution to maintain system integrity. You can also explore related techniques such as Excel VBA Code Autofit to automatically adjust column widths after running your validation scripts, ensuring your data remains readable.

The VBA Validation Logic

The core of this solution relies on a subroutine that loops through the target range in Sheet1. Below is the complete code structure. Copy and paste this into your module. The code uses a Dictionary object from the Microsoft Scripting Runtime library for faster lookups compared to nested loops, especially in large datasets. Ensure you have enabled the reference by going to Tools > References in the VBA editor and checking Microsoft Scripting Runtime.

Sub ValidateSheet1ColumnC()
    Dim wsSource As Worksheet
    Dim wsRef As Worksheet
    Dim dict As Object
    Dim lastRow As Long
    Dim i As Long
    Dim cellValue As Variant
    
    ' Set worksheet references
    Set wsSource = ThisWorkbook.Sheets("Sheet1")
    Set wsRef = ThisWorkbook.Sheets("Sheet2")
    
    ' Create dictionary for fast lookup
    Set dict = CreateObject("Scripting.Dictionary")
    
    ' Load Sheet2 Column X into dictionary
    lastRow = wsRef.Cells(wsRef.Rows.Count, "X").End(xlUp).Row
    If lastRow >= 1 Then
        For i = 1 To lastRow
            dict.Add wsRef.Cells(i, "X").Value, True
        Next i
    End If
    
    ' Validate Sheet1 Column C
    lastRow = wsSource.Cells(wsSource.Rows.Count, "C").End(xlUp).Row
    For i = 1 To lastRow
        cellValue = wsSource.Cells(i, "C").Value
        
        ' Check if value exists in dictionary
        If dict.exists(cellValue) Then
            wsSource.Cells(i, "C").Offset(0, 1).Value = "True"
        Else
            wsSource.Cells(i, "C").Offset(0, 1).Value = "No"
        End If
    Next i
    
    MsgBox "Validation Complete", vbInformation
End Sub

Understanding the Code Mechanics

The script begins by defining two worksheet objects: wsSource for Sheet1 and wsRef for Sheet2. It then initializes a Dictionary object, which acts like a hash map, allowing O(1) average time complexity for lookups. The code first determines the last used row in Column X of Sheet2 and populates the dictionary with every unique value found there. This step is critical because it converts the reference data into a format optimized for rapid searching. Next, the script identifies the last used row in Column C of Sheet1. It iterates through each cell in this column, retrieving its value. The dict.exists method checks if the current cell's value is present in our pre-loaded dictionary. If it returns true, the adjacent cell in Column D receives the text "True". Otherwise, it receives "No". This offset strategy keeps the original input clean while providing clear validation status. If you are dealing with complex data structures, you might also find Macro Development: Looping Two Arrays in Excel VBA useful for understanding alternative iteration methods.

Executing and Troubleshooting

To run the validation, return to Excel and press Alt + F8. Select ValidateSheet1ColumnC from the list and click Run. The macro will process the data instantly. If you encounter runtime errors, ensure that both sheets exist exactly as named in the code. Common issues include typos in sheet names or empty ranges causing the End(xlUp) method to fail. Additionally, if you receive an error regarding missing references, verify that the CreateObject line is used instead of early binding if you cannot enable the Scripting Runtime reference. For advanced users, consider adding error handling blocks to manage unexpected data types or protected sheets. Remember that macros do not recalculate automatically upon cell change; they must be triggered manually or via event handlers like Worksheet_Change, which requires additional coding complexity. Always backup your file before running new macros to prevent accidental data overwrites.

Frequently Asked Questions

Can I make this validation happen automatically when I type?

Yes, but it requires modifying the code to use the Worksheet_Change event instead of a standalone subroutine. You would need to place the logic in the specific sheet's code module rather than a general module. This triggers the check immediately after a user enters data, though it may slow down performance if applied to very large ranges.

What happens if there are duplicate values in Sheet2 Column X?

The Dictionary object automatically handles duplicates by keeping only the last key added. Since we are only checking for existence (dict.exists), duplicates in the reference list do not affect the outcome. All instances of a matching value in Sheet1 will still correctly return "True".

How do I handle case sensitivity in the lookup?

By default, VBA Dictionary comparisons are case-sensitive. If you want "Apple" and "apple" to match, you must set dict.CompareMode = vbTextCompare after creating the dictionary object. Without this setting, exact character casing must match between the source and reference columns.

Can I highlight invalid cells instead of just writing "No"?

Absolutely. You can replace the text assignment with conditional formatting commands or directly modify the cell's interior color property. For example, you could add wsSource.Cells(i, "C").Interior.Color = RGB(255, 0, 0) inside the Else block to visually flag mismatches in red.

Why does my macro return an error when the sheet is empty?

The End(xlUp) method can sometimes return unexpected results if the entire column is empty, potentially pointing to cell A1. To fix this, add a check to ensure the last row number is greater than zero before attempting to loop through the dictionary population or validation steps.

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