Working with two worksheets

LosingMyMindAgain

New Member
Joined
Sep 22, 2014
Messages
11
Hello. I am fairly new to Excel macros and apologize ahead of time if this is a stupid question. I am looking to work with two sheets of a workbook. I found a macro that does what I want, but only when dealing with one sheet. Sheet1 is the data entry portion and Sheet2 is where the totals will be. With this macro I am hoping to cycle through Sheet1 Column N to distinguish the unique counties listed and then count the occurrences of each county. I'd then like to paste the unique counties on Sheet2 starting at E3. Then also paste the counts on Sheet2 starting at F3. How do I go about tweaking this so I can reference back and forth between the two sheets? Any tips would be greatly appreciated. Thank you!

Sub Special_Countif()
Dim i, LastRowA, LastRowB
'A=Data Column B=Unique Names C=Count
LastRowA = Range("A" & Rows.Count).End(xlUp).Row
Application.ScreenUpdating = False
Application.EnableEvents = False
Columns("B:C").ClearContents
For i = 1 To LastRowA
If Application.CountIf(Range("B:B"), Cells(i, "A")) = 0 Then
Cells(i, "B").Offset(1, 0).Value = Cells(i, "A").Value
End If
Next
Columns("B:B").Select
Selection.Sort Key1:=Range("B1"), Order1:=xlAscending, Header:=xlYes, _
OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
DataOption1:=xlSortNormal
LastRowB = Range("B" & Rows.Count).End(xlUp).Row
For i = 2 To LastRowB
Cells(i, "C").Value = Application.CountIf(Range("A:A"), Cells(i, "B"))
Next i
Range("B1").Value = "Entry"
Range("C1").Value = "Occurrences"
Range("B1:C1").HorizontalAlignment = xlCenter
Range("B1").Select
Columns("B:C").AutoFit
Application.EnableEvents = True
End Sub
 
LosingMyMindAgain,

In my last reply, I had asked for:

In order to continue please post another workbook with Sheet1, and, Sheet2, with their actual raw data, and, results (manually formatted by your) for the results you are looking for.

So that I can get it right this next time, please supply the same workbook, but, with Sheet2, range H3:I? manually completed by you for the results you are looking for.
 
Upvote 0

Excel Facts

Wildcard in VLOOKUP
Use =VLOOKUP("Apple*" to find apple, Apple, or applesauce
LosingMyMindAgain,

Thanks for the updated workbook.

Sample worksheets:


Excel 2007
MNO
1Service 1County 2State1
2Service AAlleghenyPA
3Service AAlleghenyPA
4Service BBeaverPA
5Service CButlerPA
6Service CWestmorelandPA
7Service CWestmorelandPA
8Service CWestmorelandPA
9Service CDE
10Service AOH
11Service BButlerPA
12
Sheet1



Excel 2007
EFGHI
1SERVICECOUNTY
2
3Service A3
4Service B2
5Service C5
6
7
8
Sheet2


After the new macro using the Scripting.Dictionary:


Excel 2007
EFGHI
1SERVICECOUNTY
2
3Service A3Allegheny2
4Service B2Beaver1
5Service C5Butler2
6Westmoreland3
7Not Recorded2
8
Sheet2


Please TEST this FIRST in a COPY of your workbook (always make a backup copy before trying new code, you never know what you might lose).

Code:
Sub GetUniqueCounts_V2()
' hiker95, 09/23/2014, ME807082
Dim w1 As Worksheet, w2 As Worksheet
Dim lr1 As Long, lr2 As Long, n As Long
Dim rng As Range, c As Range
Application.ScreenUpdating = False
Set w1 = Sheets("Sheet1")
Set w2 = Sheets("Sheet2")
With w2
  lr2 = .Cells(Rows.Count, "I").End(xlUp).Row
  If lr2 > 2 Then .Range("H3:I" & lr2).ClearContents
End With
With w1
  .Activate
  lr1 = .Cells(Rows.Count, "O").End(xlUp).Row
  n = Application.CountIf(.Range("N2:N" & lr1), "")
  Set rng = Range("N2:N" & lr1)
  With CreateObject("Scripting.Dictionary")
    .CompareMode = vbTextCompare
    For Each c In rng
      If Not .Exists(c.Value) Then
        .Add c.Value, 1
      Else
        .Item(c.Value) = .Item(c.Value) + 1
      End If
    Next
  w2.Range("H3").Resize(.Count, 2) = Application.Transpose(Array(.keys, .Items))
  End With
End With
With w2
  lr2 = .Cells(Rows.Count, "H").End(xlUp).Row
  If n > 0 Then
    .Cells(lr2 + 1, 8) = "Not Recorded"
  End If
  .Columns("H:I").AutoFit
  .Activate
End With
Application.ScreenUpdating = True
End Sub

You may have to add the Microsoft Scripting Runtime to the References - VBA Project.

With your workbook that contains the above:

Press the keys ALT + F11 to open the Visual Basic Editor

In the VBA Editor, click on:
Tools
References...

Put a checkmark in the box marked
Microsoft Scripting Runtime

Then click on the OK button.

And, exit out of the VBA Editor.

Before you use the macro with Excel 2007 or newer, save your workbook, Save As, a macro enabled workbook with the file extension .xlsm

Then run the GetUniqueCounts_V2 macro.
 
Upvote 0
Thanks so much Hiker! I tested it on some of our previous months workbooks where we had to manually total everything. I noticed it pulled a blank county with a count of 8 and Not Recorded had no entries. I was able to use the macro recorder to create this to sort the counties. I tried setting Range("H3:I500").Select and SetRange Range("H3:I500") to H3:I, but that didn't work. I am assuming it requires a specific end cell? I uploaded an example of what I saw on one of our older workboooks.

Sub SortCounty()'
' SortCounty Macro
'


'
Range("H3:I500").Select
ActiveWorkbook.Worksheets("Sheet2").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Sheet2").Sort.SortFields.Add Key:=Range("H3"), _
SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Sheet2").Sort
.SetRange Range("H3:I500")
.Header = xlNo
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End Sub

https://app.box.com/s/crjnmm5tkbyjsbimgk90

You have been so extremely helpful!
 
Upvote 0
LosingMyMindAgain,

I have added a sort routine to the new macro, that will sort in Sheet2, range H3:I the lastrow
by H3, ascending.


Sample raw data in worksheet Sheet1 (not all 474 rows are shown for brevit):


Excel 2007
NO
1County 2State1
2El OasoCO
3El PasoCO
4El PasoCO
5St. AugustineFL
6BartowGA
7AndersonIN
8MadisonIN
9MadisonIN
10MadisonIN
11LaurelMD
12St. ClairMI
50SteubenvilleOH
51OH
52OH
53WagnerOK
455YorkPA
456PA
457PA
458PA
459PA
460MorovisPR
461ShelbyTN
462ShelbyTN
463ShelbyTN
464ShelbyTN
465StauntonVA
466VA
467BerkeleyWV
468ElkinsWV
469HancockWV
470MarshallWV
471NewellWV
472OhioWV
473WoodWV
474WV
475
Sheet1


Sheet2 after the new macro:


Excel 2007
HI
1COUNTY
2
3Allegheny110
4Anderson1
5Armstrong6
6Bartow1
7Beaver34
8Belmont3
9Berkeley1
10Blair8
11Blazo1
12Buchanan1
13Butler20
14Cambria19
15Charlotte1
16Chautauqua1
17Clarion7
18Clearfield3
19Crawford12
20Cumberland3
21Dauphin1
22El Oaso1
23El Paso2
24Elk 1
25Elkins1
26Erie13
27Fayette28
28Greene5
29Greenville1
30Grove City1
31Hancock1
32Harrison1
33Hermitage1
34Huntingdon1
35Indiana11
36Jefferson16
37Lackawana2
38Lancaster4
39Laurel1
40Lawrence12
41Livingston2
42Lorraine1
43Luzerne1
44Madison3
45Mahoning9
46Marshall1
47Masontown1
48McKean2
49Mercer19
50Monroe5
51Morovis1
52Newell1
53Ohio1
54Philadelphia2
55Pittsburgh1
56Richland1
57Shelby4
58St. Augustine1
59St. Clair4
60Staunton1
61Steubenville2
62Venango6
63Wagner1
64Warren2
65Washington20
66Westmoreland35
67Wood1
68York1
69Not Recorded8
70
Sheet2



Please TEST this FIRST in a COPY of your workbook (always make a backup copy before trying new code, you never know what you might lose).

Code:
Sub GetUniqueCounts_V3()
' hiker95, 09/24/2014, ME807082
Dim w1 As Worksheet, w2 As Worksheet
Dim lr1 As Long, lr2 As Long, n As Long
Dim rng As Range, c As Range
Application.ScreenUpdating = False
Set w1 = Sheets("Sheet1")
Set w2 = Sheets("Sheet2")
With w2
  lr2 = .Cells(Rows.Count, "I").End(xlUp).Row
  If lr2 > 2 Then .Range("H3:I" & lr2).ClearContents
End With
With w1
  .Activate
  lr1 = .Cells(Rows.Count, "O").End(xlUp).Row
  n = Application.CountIf(.Range("N2:N" & lr1), "")
  Set rng = .Range("N2:N" & lr1)
  With CreateObject("Scripting.Dictionary")
    .CompareMode = vbTextCompare
    For Each c In rng
      If Not .Exists(c.Value) Then
        .Add c.Value, 1
      Else
        .Item(c.Value) = .Item(c.Value) + 1
      End If
    Next
  w2.Range("H3").Resize(.Count, 2) = Application.Transpose(Array(.keys, .Items))
  End With
End With
With w2
  lr2 = .Cells(Rows.Count, "I").End(xlUp).Row
  .Range("H3:I" & lr2).Sort key1:=.Range("H3"), order1:=1
  If n > 0 Then
    .Cells(lr2, 8) = "Not Recorded"
  End If
  .Columns("H:I").AutoFit
  .Activate
End With
Application.ScreenUpdating = True
End Sub

Before you use the macro with Excel 2007 or newer, save your workbook, Save As, a macro enabled workbook with the file extension .xlsm

Then run the GetUniqueCounts_V3 macro.
 
Last edited:
Upvote 0
I apologize for the lack of response. I was ill the past few days. Hiker this is terrific! It does exactly what I need. Thank you so much for taking the time to do it!
 
Upvote 0
LosingMyMindAgain,

Thanks for the feedback.

You are very welcome. Glad I could help.

And, come back anytime.
 
Upvote 0
LosingMyMindAgain,

Is there a way to base it counting the counties only if the next column over lists PA?

I do not understand.

Can we have another workbook containing the raw data worksheets, and, the worksheet results?
 
Upvote 0
Hello again Hiker. You had previously created a macro for me that counted all the counties. I was hoping to track just PA counties now instead of all the state counties. We are located in PA and those are the ones we really want to keep an eye on. The spreadsheet link is below. On Sheet1 column N list the counties and column O list the state. I wanted to see if there was anyway to adjust the macro to determine and count unique N cells that had an adjacent O cell that said PA. If a N cell next to a O cell with PA didn't then maybe count is as No PA County. Is that feasible or is that too much for a macro to do? I hope that made sense. I mocked up the results on Sheet2.

https://app.box.com/s/mz0rh97qoqwsngdpy1g8
 
Upvote 0

Forum statistics

Threads
1,215,615
Messages
6,125,854
Members
449,266
Latest member
davinroach

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