VBA Macro to Compare Two Files to Determine if They are Identical

This function will allow you to compare one file to another.

VBA Macro to Compare Two Files to Determine if They are Identical

VBA Macro to Compare Two Files to Determine if They are Identical

Copy code below and paste directly into your VB project.

Sub CompareTextFiles()
‘**********************************************************
‘PURPOSE: Check to see if two files are identical
‘File1 and File2 = FullPaths of files to compare
‘will compare complete content of the file, including length of the document (Bit to Bit)
‘**********************************************************

Dim File1Path, File1Content, File2Path, File2Content As Variant

‘Change the file 1 path
File1Path = “C:UsersRaghu Ram AllaCompareTextFilesTest1.txt”
File1Content = GetFileContent(File1Path)

‘Change the file 2 path
File2Path = “C:UsersRaghu Ram AllaCompareTextFilesTest2.txt”
File2Content = GetFileContent(File2Path)

If File1Content = File2Content Then
MsgBox “Given Files are identical”
Else
MsgBox “Given Files are not identical”
End If

End Sub

Function GetFileContent(Name As Variant) As Variant
Dim intUnit As Integer

On Error GoTo ErrGetFileContent
intUnit = FreeFile
Open Name For Input As intUnit
GetFileContent = Input(LOF(intUnit), intUnit)

ErrGetFileContent:
Close intUnit
Exit Function
End Function

Hope this helps.

If you like the code, please share it.

Show Comments

One Response

  1. Pingback: comparing 2 text file in VBA -- fastest method
  2. Vivek Pare

Leave a Reply