using a variable as a sheet name!

phonesdontfly

New Member
Joined
Mar 2, 2016
Messages
16
I have this code (adapted from this forum) that compares sheet 1 and sheet 2, and identifies the differences:


Code:
Sub compareSheets(shtSheet1 As String, shtSheet2 As String)
Dim mycell As Range
Dim mydiffs As Integer


'For each cell in sheet2 that is not the same in Sheet1, color it yellow
For Each mycell In ActiveWorkbook.Worksheets(shtSheet2).UsedRange
    If Not mycell.Value = ActiveWorkbook.Worksheets(shtSheet1).Cells(mycell.row, mycell.Column).Value Then
        
        mycell.Interior.Color = vbYellow
        mydiffs = mydiffs + 1
        
    End If
Next


'Display a message box to demonstrate the differences
MsgBox mydiffs & " differences found (highlighted in yellow)", vbInformation


ActiveWorkbook.Sheets(shtSheet2).Select

end sub


My question --> I am adapting this to be able to be used for any two sheets- not just sheet 1 and 2. I have a userform + combo boxes that display the sheet name options from any given workbook, and then it stores the sheet names as variables. How do I adapt the above code to use the variable values in place of sheet1 and sheet2? ​My variable names are A and B.


The closest I have come is (sht & A.value) and it doesn't work. Thanks!
 
Last edited:

Excel Facts

Test for Multiple Conditions in IF?
Use AND(test, test, test, test) or OR(test, test, test, ...) as the logical_test argument of IF.
Can't you just pass in A and B (or any other sheetnames) for the method?

Example:
Code:
Dim A as String
Dim B as String
Dim C as String

A = "SheetName1"
B = "SheetName2"
C = "SheetName3"

compareSheets A, B 'compares SheetName1 with SheetName2 and highlights in SheetName2

compareSheets B, C 'compares SheetName2 with SheetName3 and highlights in SheetName3
 
Upvote 0

Forum statistics

Threads
1,214,932
Messages
6,122,332
Members
449,077
Latest member
jmsotelo

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top