-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathUtilsPub.bas
2541 lines (2085 loc) · 97.5 KB
/
UtilsPub.bas
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
Attribute VB_Name = "Utils"
'**************************************************************************
'********************* FUNCTIONS PACKAGE ***********************************
'**************************************************************************
'# Version 2.3.7
'# All functions are assumed to be compatible with non .xls formats only
'# Updated on 8/1/2012 - Added new parameter on lastColNum function
'# Updated on 7/12/2012 - lastColNum function - Revised to use a loop as the primary last row detection mechanism instead of lastUsedCol built in function (was causing too many problems)
'# Updated on 7/9/2012: Refactored getMonthNameAndYear function to use built-in Format function instead of a dictionary structure (Thanks to Randal B!)
' Updated move_entries to make the move of the header row as optional
'# Updated on 7/3/2012: Added vbaLookup2 function. Many times faster than vbalookup, and exponentially faster than vlookup. See function for more details.
Public Declare Function GetTickCount Lib "kernel32.dll" () As Long '//
'**************************************************************************
Public Function isxls(ByVal ws As Worksheet) As Boolean
'// Tests to see whether a given worksheet is in the old excel format.
'// Authored by Nathan N on 7/6/2012
If Right(ws.Name, 4) = ".xls" Then isxls = True
End Function
Public Sub trim_data_fields(ByVal ws As Worksheet, ByVal fieldName As String)
'// Authored by Nathan N on 6/21/2012
Dim i As Long
For i = 2 To lastRow(ws)
ws.Cells(i, FieldColNum(ws, fieldName)) = Trim(ws.Cells(i, FieldColNum(ws, fieldName)))
Next i
End Sub
Public Sub move_all_entries(ByVal wsSource As Worksheet, ByVal wsDest As Worksheet)
'// Authored by Nathan N on 6/28/2012
'// Moves all data from one worksheet to another. Strips all data of any previous formatting as well.
'// Assumes that data has no 'pre headers' in the first few rows
wsDest.Range(wsDest.Cells(1, 1), wsDest.Cells(lastRow(wsSource), lastColNum(wsSource))) = wsSource.Range(wsSource.Cells(1, 1), wsSource.Cells(lastRow(wsSource), lastColNum(wsSource))).value
End Sub
Public Sub mergeWorksheets(ByVal wsSource As Worksheet, ByVal wsDest As Worksheet, ByVal sourceKey As String, ByVal destKey As String)
'// Authored by Nathan N on 1/14/2015
'// Merges all fields of a source worksheet into a destination worksheet
'// sourceKey must be located in column 1 (or col "A")
Dim sourceColCount As Integer, destColCount As Integer
Dim destFieldName As String
Dim i As Long, j As Long
sourceColCount = lastColNum(wsSource)
destColCount = lastColNum(wsDest)
If wsSource.Cells(1, 1) <> sourceKey Then
MsgBox ("SourceKey is not located in column 1 of the Source worksheet! Quitting mergeWorksheets routine!")
Exit Sub
End If
Application.ScreenUpdating = False
For i = 1 To sourceColCount
If wsSource.Cells(1, i) = sourceKey Then GoTo NextColumn
'//destColNum = destColCount + i
destFieldName = wsSource.Cells(1, i)
vbaLookup2 wsDest, destFieldName, destKey, wsSource, sourceKey, destFieldName, , , , , , True
NextColumn:
Next i
Application.ScreenUpdating = True
End Sub
Public Sub getMonthNameAndYear(ByVal ws As Worksheet, ByVal dateField As Worksheet, newDateFieldName As String)
'// Inserts a condensed month name and year based on the original date field
'// Added 7/2/2012 by Nathan N
'// Updated 7/9/2012: Refactored function to use built-in Format function instead of a dictionary structure (Thanks to Randal B!)
Dim dateColNum As Integer, monthColNum As Integer
Dim dateColLet As String
Dim dateValue As Date, monthValue As Integer, yearValue As Integer, fullMonthName As String
Dim newDateValue As String
Dim i As Long
Application.ScreenUpdating = False
Set ws = ActiveWorkbook.ActiveSheet
dateColLet = InputBox("Enter the Date Column Letter:")
Application.ScreenUpdating = False
dateColNum = LetToColNum(dateColLet)
monthColNum = dateColNum + 1
ws.Columns(monthColNum).Insert
ws.Columns(monthColNum).NumberFormat = "@"
ws.Cells(1, monthColNum) = "Month"
For i = 2 To lastRow(ws)
dateValue = ws.Cells(i, dateColNum)
newDateValue = Format(dateValue, "mmm yyyy")
ws.Cells(i, monthColNum) = newDateValue
Next i
Application.ScreenUpdating = True
End Sub
Public Sub move_entries(ByVal wsSource As Worksheet, ByVal wsDest As Worksheet, ByVal fieldName As String, ByVal keywordInFieldName As String, Optional ByVal copyHeader As Boolean, Optional ByVal deleteMovedEntries As Boolean)
Dim startRow As Long, endRow As Long, startRowDest As Long, endRowDest As Long
'// Moves larges swathes of entries to a destination sheet quickly and as values (removes all formatting)
'// Authored by Nathan N on 6/28/2012
'// Updated 'itemToMove' to 'keywordInFieldName'
'// Updated on 7/9/2012 to make the copy over of the Header row as optional (header row is assumed to be located on row 1)
Application.ScreenUpdating = False
SortCol wsSource, fieldName
startRow = FieldRowNum(wsSource, keywordInFieldName, FieldColNum(wsSource, fieldName))
endRow = FieldRowNum(wsSource, keywordInFieldName, FieldColNum(wsSource, fieldName), , , , True)
If startRow = 0 Then '// if no matching keywordInFieldName was found then function exits
Debug.Print "Function move_entries: keywordInFieldName was not found. No entries moved."
Exit Sub
End If
If copyHeader = True Then wsDest.Rows(1) = wsSource.Rows(1).value
startRowDest = lastRow(wsDest) + 1
endRowDest = endRow - startRow + startRowDest
wsDest.Range(wsDest.Cells(startRowDest, 1), wsDest.Cells(endRowDest, lastColNum(wsSource))) = wsSource.Range(wsSource.Cells(startRow, 1), wsSource.Cells(endRow, lastColNum(wsSource))).value
If deleteMovedEntries = True Then wsSource.Rows(startRow & ":" & endRow).Delete
End Sub
Public Sub convert_string_to_int(ByVal ws As Worksheet, ByVal zipcodeFieldName As String)
'// Authored by Nathan N on 7/5/2012
'// Converts numbers that are in string format to int
Dim i As Long
Dim zipColNum As Integer
On Error Resume Next
zipColNum = FieldColNum(ws, zipcodeFieldName)
For i = 2 To lastRow(ws, , FieldColNum(ws, zipcodeFieldName))
ws.Cells(i, zipColNum) = Int(ws.Cells(i, zipColNum))
Next i
On Error GoTo 0
End Sub
Public Sub zipcode_county_lookup_manual() '(ByVal ws As Worksheet, ByVal zipcodeFieldName As String, Optional ByVal stateFieldName As String, Optional ByVal singleStateName As String, Optional ByVal listStates As Boolean)
'// Matches zip codes with county names in worksheets with multiple states listed
'// Authored by Nathan N on 6/26/2012
Dim wb As Workbook, ws As Worksheet, wbCounty As Workbook, wsCounty As Worksheet, wsState As Worksheet
Dim state As String, zipCode As Long
Dim colLet As String
Dim zipColLet As String, zipColNum As Integer, countyColNum As Integer, stateColNum As Integer
Dim zipToCountyMappingPath As String
Dim rngCounty As Range
Dim stateFieldName As String, zipcodeFieldName As String, singleStateName As String, listStates As Boolean
Dim i As Long
Application.DisplayAlerts = False
Application.ScreenUpdating = False
zipToCountyMappingPath = file_reference_path() & "\ZipCodeAndCountyMappingDataPub.xlsx"
Set wb = ActiveWorkbook
Set ws = wb.ActiveSheet
If Right(wb.Name, 4) = ".xls" Then
MsgBox (FirstName() & ", it looks like you're using a workbook that's saved in the old excel format." & vbCrLf & vbCrLf & "Please resave your workbook as an .xlsx format. Then close and reopen.")
Exit Sub
End If
'// Attempt to auto detect the zip code column
zipColNum = FieldColNum(ws, "zip", , True)
If zipColNum = 0 Then zipColNum = FieldColNum(ws, "zip c", , True)
If zipColNum = 0 Then zipColNum = FieldColNum(ws, "zip_c", , True)
If zipColNum = 0 Then zipColNum = FieldColNum(ws, "zip_", , True)
If zipColNum = 0 Then zipColNum = FieldColNum(ws, "zip", , True)
If zipColNum = 0 Then
zipColLet = InputBox("Enter the zip code column letter:")
zipColNum = LetToColNum(zipColLet)
End If
'// This corrects data for which zip codes are listed as Strings on a work sheet instead of int. String data types will cause the vbalookup function to not find the zip codes.
zipcodeFieldName = ws.Cells(1, zipColNum)
convert_string_to_int ws, zipcodeFieldName
countyColNum = zipColNum + 1
If zipColNum = -1 Then
Debug.Print ("Error: zipcode_county_lookup function. Zip Code Column could not be located. Ended function.")
Exit Sub
End If
If Not (FieldExists(ws, "County")) Then
ws.Columns(countyColNum).Insert
ws.Cells(1, countyColNum) = "County"
countyColNum = FieldColNum(ws, "County")
End If
If stateFieldName = "" And singleStateName = "" Then
stateColNum = FieldColNum(ws, "state", , True)
ElseIf stateFieldName <> "" And singleStateName = "" Then
stateColNum = FieldColNum(ws, stateFieldName, , True)
ElseIf stateFieldName = "" And singleStateName <> "" Then
state = singleStateName
stateColNum = 0
End If
'
'If listStates = True Then
' If FieldExists(ws, "State") Then
' Debug.Print "State Field Already Exists. Please Delete before continuing."
' Exit Sub
' End If
' ws.Columns(countyColNum + 1).Insert
' ws.Cells(1, countyColNum + 1) = "State"
'End If
stateColNum = -1
If stateColNum = -1 Then '//If no state field was found or listed, the program assumes that we are to search all states to match counties
If Not (FieldExists(ws, "State")) Then
ws.Cells(1, countyColNum + 1) = "State"
ws.Columns(countyColNum + 1).Insert
End If
listStates = True
Set wbCounty = Workbooks.Open(zipToCountyMappingPath, , True)
Set wsState = wbCounty.Worksheets.Add
wsState.Move , wbCounty.Worksheets(wbCounty.Worksheets.Count)
wsState.Cells(1, 1) = "Zip Code"
wsState.Cells(1, 2) = "City Name"
wsState.Cells(1, 3) = "State"
wsState.Cells(1, 4) = "Primary County Name"
For Each wss In wbCounty.Worksheets
If wss.Name = wsState.Name Then Exit For
wsState.Range(wsState.Cells(lastRow(wsState) + 1, 1), wsState.Cells(lastRow(wsState) - 1 + lastRow(wss), 4)) = wss.Range(wss.Cells(2, 1), wss.Cells(lastRow(wss), 4)).value
Next wss
Set wsCounty = wsState
VbaZipLookup ws, "County", zipcodeFieldName, wsCounty, "ZIP Code", "Primary County Name", listStates
'// Check for unmatched items
For i = 2 To lastRow(ws)
Set rngCounty = ws.Cells(i, FieldColNum(ws, "County"))
zipCode = ws.Cells(i, FieldColNum(ws, zipcodeFieldName))
If rngCounty.value = "" Then rngCounty.value = "0 Not Found"
Next i
Debug.Print ("Used All State Information because State Column could not originally be located.")
wbCounty.Close
Application.DisplayAlerts = True
Application.ScreenUpdating = True
MsgBox (FirstName() & ", the counties have been added to your data." & vbCrLf & vbcrl & "-Report Robot")
Exit Sub
End If
'// If a valid state field name was provided, then the program limits the scope to only states that are listed
Set wbCounty = Workbooks.Open(zipToCountyMappingPath, , True)
ws.Activate
If singleStateName = "" Then
For i = 2 To lastRow(ws)
Set rngCounty = ws.Cells(i, FieldColNum(ws, "County"))
If stateColNum > 0 Then state = ws.Cells(i, stateColNum)
zipCode = ws.Cells(i, FieldColNum(ws, zipcodeFieldName))
On Error GoTo errhandler
Set wsCounty = wbCounty.Worksheets(state)
rngCounty.value = wsCounty.Cells(Application.WorksheetFunction.Match(zipCode, wsCounty.Columns(FieldColNum(wsCounty, "ZIP Code")), 0), FieldColNum(wsCounty, "Primary County Name"))
On Error GoTo 0
NextZipCode:
Next i
Else
Set wsCounty = wbCounty.Worksheets(singleStateName)
For i = 2 To lastRow(ws)
Set rngCounty = ws.Cells(i, FieldColNum(ws, "County"))
zipCode = ws.Cells(i, FieldColNum(ws, zipcodeFieldName))
On Error GoTo ErrHandler2
rngCounty.value = wsCounty.Cells(Application.WorksheetFunction.Match(zipCode, wsCounty.Columns(FieldColNum(wsCounty, "ZIP Code")), 0), FieldColNum(wsCounty, "Primary County Name"))
On Error GoTo 0
NextZipCode2:
Next i
End If
wbCounty.Close
Exit Sub
errhandler:
Err.Clear
rngCounty.value = "0 Not Found"
Resume NextZipCode
ErrHandler2:
Err.Clear
rngCounty.value = "0 Not Found"
Resume NextZipCode2
End Sub
Public Sub zipcode_county_lookup(ByVal ws As Worksheet, ByVal zipcodeFieldName As String, Optional ByVal stateFieldName As String, Optional ByVal singleStateName As String, Optional ByVal listStates As Boolean)
'// Matches zip codes with county names in worksheets with multiple states listed
'// Authored by Nathan N on 6/11/2012
'// Updated 6/14/2012 - compiles all state zip code information if no state is listed
Dim wbCounty As Workbook, wsCounty As Worksheet, wsState As Worksheet
Dim wb As Workbook
Dim state As String, zipCode As Long
Dim rngCounty As Range
Dim colLet As String
Dim zipColNum As Integer, countyColNum As Integer, stateColNum As Integer
Dim zipToCountyMappingPath As String
Dim i As Long
Application.DisplayAlerts = False
zipToCountyMappingPath = file_reference_path() & "\ZipCodeAndCountyMappingDataPub.xlsx"
zipColNum = FieldColNum(ws, zipcodeFieldName, , True)
countyColNum = zipColNum + 1
If zipColNum = -1 Then
Debug.Print ("Error: zipcode_county_lookup function. Zip Code Column could not be located. Ended function.")
Exit Sub
End If
ws.Columns(countyColNum).Insert
ws.Cells(1, countyColNum) = "County"
If stateFieldName = "" And singleStateName = "" Then
stateColNum = FieldColNum(ws, "state", , True)
ElseIf stateFieldName <> "" And singleStateName = "" Then
stateColNum = FieldColNum(ws, stateFieldName, , True)
ElseIf stateFieldName = "" And singleStateName <> "" Then
state = singleStateName
stateColNum = 0
End If
'
'If listStates = True Then
' If FieldExists(ws, "State") Then
' Debug.Print "State Field Already Exists. Please Delete before continuing."
' Exit Sub
' End If
' ws.Columns(countyColNum + 1).Insert
' ws.Cells(1, countyColNum + 1) = "State"
'End If
If stateColNum = -1 Then '//If no state field was found or listed, the program assumes that we are to search all states to match counties
ws.Columns(countyColNum + 1).Insert
ws.Cells(1, countyColNum + 1) = "State"
listStates = True
Set wbCounty = Workbooks.Open(zipToCountyMappingPath, , True)
Set wsState = wbCounty.Worksheets.Add
wsState.Move , wbCounty.Worksheets(wbCounty.Worksheets.Count)
wsState.Cells(1, 1) = "Zip Code"
wsState.Cells(1, 2) = "City Name"
wsState.Cells(1, 3) = "State"
wsState.Cells(1, 4) = "Primary County Name"
For Each wss In wbCounty.Worksheets
If wss.Name = wsState.Name Then Exit For
wsState.Range(wsState.Cells(lastRow(wsState) + 1, 1), wsState.Cells(lastRow(wsState) - 1 + lastRow(wss), 4)) = wss.Range(wss.Cells(2, 1), wss.Cells(lastRow(wss), 4)).value
Next wss
Set wsCounty = wsState
VbaZipLookup ws, "County", zipcodeFieldName, wsCounty, "ZIP Code", "Primary County Name", listStates
'// Check for unmatched items
For i = 2 To lastRow(ws)
Set rngCounty = ws.Cells(i, FieldColNum(ws, "County"))
zipCode = ws.Cells(i, FieldColNum(ws, zipcodeFieldName))
If rngCounty.value = "" Then rngCounty.value = zipCode & " Not Found"
Next i
Debug.Print ("Used All State Information because State Column could not originally be located.")
wbCounty.Close
Exit Sub
End If
'// If a valid state field name was provided, then the program limits the scope to only states that are listed
Set wbCounty = Workbooks.Open(zipToCountyMappingPath, , True)
ws.Activate
If singleStateName = "" Then
For i = 2 To lastRow(ws)
Set rngCounty = ws.Cells(i, FieldColNum(ws, "County"))
If stateColNum > 0 Then state = ws.Cells(i, stateColNum)
zipCode = ws.Cells(i, FieldColNum(ws, zipcodeFieldName))
On Error GoTo errhandler
Set wsCounty = wbCounty.Worksheets(state)
rngCounty.value = wsCounty.Cells(Application.WorksheetFunction.Match(zipCode, wsCounty.Columns(FieldColNum(wsCounty, "ZIP Code")), 0), FieldColNum(wsCounty, "Primary County Name"))
On Error GoTo 0
NextZipCode:
Next i
Else
Set wsCounty = wbCounty.Worksheets(singleStateName)
For i = 2 To lastRow(ws)
Set rngCounty = ws.Cells(i, FieldColNum(ws, "County"))
zipCode = ws.Cells(i, FieldColNum(ws, zipcodeFieldName))
On Error GoTo ErrHandler2
rngCounty.value = wsCounty.Cells(Application.WorksheetFunction.Match(zipCode, wsCounty.Columns(FieldColNum(wsCounty, "ZIP Code")), 0), FieldColNum(wsCounty, "Primary County Name"))
On Error GoTo 0
NextZipCode2:
Next i
End If
wbCounty.Close
Exit Sub
errhandler:
Err.Clear
rngCounty.value = "0 Not Found"
Resume NextZipCode
ErrHandler2:
Err.Clear
rngCounty.value = "0 Not Found"
Resume NextZipCode2
End Sub
Public Sub zipcode_state_lookup(ByVal ws As Worksheet, ByVal zipcodeFieldName As String)
'// Authored by Nathan N on 6/11/2012
'// Updated 6/14/2012 - compiles all state zip code information if no state is listed
'// Matches zip codes with county names in worksheets with multiple states listed
Dim wbCounty As Workbook, wsCounty As Worksheet, wsState As Worksheet
Dim wb As Workbook
Dim state As String, zipCode As Long
Dim rngCounty As Range
Dim colLet As String
Dim stateColNum As Integer, zipColNum As Integer
Dim i As Long
zipColNum = FieldColNum(ws, zipcodeFieldName, , True)
stateColNum = zipColNum + 1
If zipColNum = -1 Then
Debug.Print ("Error: zipcode_county_lookup function. Zip Code Column could not be located. Ended function.")
Exit Sub
End If
ws.Columns(stateColNum).Insert
ws.Cells(1, stateColNum) = "State"
Set wbCounty = Workbooks.Open(file_reference_path() & "\ZipCodeAndCountyMappingDataPub.xlsx", , True)
Set wsState = wbCounty.Worksheets.Add
wsState.Move , wbCounty.Worksheets(wbCounty.Worksheets.Count)
wsState.Cells(1, 1) = "Zip Code"
wsState.Cells(1, 2) = "City Name"
wsState.Cells(1, 3) = "State"
wsState.Cells(1, 4) = "Primary County Name"
For Each wss In wbCounty.Worksheets
If wss.Name = wsState.Name Then Exit For
wsState.Range(wsState.Cells(lastRow(wsState) + 1, 1), wsState.Cells(lastRow(wsState) - 1 + lastRow(wss), 4)) = wss.Range(wss.Cells(2, 1), wss.Cells(lastRow(wss), 4)).value
Next wss
Set wsCounty = wsState
vbaLookup ws, "State", zipcodeFieldName, wsCounty, "ZIP Code", "State"
'// Check for unmatched items
For i = 2 To lastRow(ws)
Set rngCounty = ws.Cells(i, FieldColNum(ws, "State"))
zipCode = ws.Cells(i, FieldColNum(ws, zipcodeFieldName))
If rngCounty.value = "" Then rngCounty.value = zipCode & " Not Found"
Next i
wbCounty.Close
End Sub
Public Function sigPath() As String
'// Authored by Nathan N on 6/6/2012
'// Returns the email signature path for the user
If windows7os() Then
sigPath = user_root(True) & "\AppData\Roaming\Microsoft\Signatures"
Else
sigPath = user_root(True) & "\Application Data\Microsoft\Signatures"
End If
End Function
Public Function user_root(Optional ByVal excludeMyDocuments As Boolean) As String
Dim docPath As String
'* Authored by Nathan N on 6/4/2012
'* Modified 6/6/2012
'* Returns the Path to windows 7 user's "My Documents" folder
'* If excludeMyDocuments = true, the function returns the path only up to the UserName folder
If excludeMyDocuments = False Then docPath = "\My Documents"
If windows7os() = True Then
If docPath <> "" Then
docPath = "\" & Right(docPath, Len(docPath) - 4)
user_root = "C:\Users\" & loginName() & docPath
Else
user_root = "C:\Users\" & loginName()
End If
Else
user_root = "C:\Documents and Settings\" & loginName() & docPath
End If
End Function
Public Function windows7os() As Boolean
'* Authored by Nathan N on 6/4/2012
'* Determines if user is using windows 7
If Left(Application.OperatingSystem, 21) = "Windows (32-bit) NT 5" Then
windows7os = False
Else
windows7os = True
End If
End Function
Public Function hub_path() As String
'// Created by Nathan N on 7/9/2012
hub_path = "\\hqclienthub\Client Hub"
End Function
Public Function file_reference_path() As String
'// Created by Nathan N on 7/9/2012
'// Helper function used avoid using long absolute file paths for common file resources
'// You must specify the path within the quotations below.
file_reference_path = ""
End Function
Public Sub delete_empty_entries(ByVal ws As Worksheet, ByVal fieldName As String)
'Authored by Nathan N on 4/9/2012
Dim i As Long
For i = 2 To lastRow(ws)
If (ws.Cells(i, FieldColNum(ws, fieldName)) = "") Then
ws.Rows(i).Delete Shift:=xlUp
i = i - 1
If (i = lastRow(ws)) Then
Exit For
End If
End If
Next i
End Sub
Public Sub AggregateServices(ByVal ws As Worksheet, ByVal WOFieldName As String, ByVal serviceFieldName As String, ByVal newFieldName As String, Optional ByVal sortBeforehand As Boolean)
'*** Created on 3/20/2012 by Nathan N ***
'*** Combines services on seperate row entries into one line for the same work order number***
'*** User needs to remove duplicate work orders seperately ***
Dim currentWO As String
Dim aggServiceType As String, newServiceType As String
Dim WOCol As Integer, currentServiceCol As Integer, newServiceCol As Integer
Dim i As Long, j As Long
WOCol = FieldColNum(ws, WOFieldName)
currentServiceCol = FieldColNum(ws, serviceFieldName)
newServiceCol = lastColNum(ws) + 1
ws.Cells(1, newServiceCol) = newFieldName
If sortBeforehand = True Then SortMultiCol ws, ws.Cells(1, WOCol), ws.Cells(1, currentServiceCol)
For i = 2 To lastRow(ws)
currentWO = ws.Cells(i, WOCol)
aggServiceType = ""
For j = i To lastRow(ws)
If currentWO = ws.Cells(j, WOCol) Then
newServiceType = ws.Cells(j, currentServiceCol)
aggServiceType = aggServiceType & ", " & newServiceType
End If
If currentWO <> ws.Cells(j + 1, WOCol) Then
ws.Cells(i, newServiceCol) = aggServiceType
If j >= lastRow(ws) Then
ws.Cells(i, newServiceCol) = aggServiceType
'// Last Row error correction
ws.Cells(lastRow(ws), newServiceCol) = Right(ws.Cells(lastRow(ws), newServiceCol), Len(ws.Cells(lastRow(ws), newServiceCol)) - 2)
Exit Sub
End If
If (Len(ws.Cells(i, newServiceCol)) > 0) Then
ws.Cells(i, newServiceCol) = Right(ws.Cells(i, newServiceCol), Len(aggServiceType) - 2)
End If
i = j
GoTo nextWO
End If
Next j
nextWO:
Next i
End Sub
Public Function InArray(ByRef arrayName() As Variant, ByVal elementValue As Variant) As Boolean
'Created on 3/13/2012 by Nathan N
Dim i As Long
For i = 0 To UBound(arrayName())
If (elementValue = arrayName(i)) Then 'If the elementValue is found at any point in the array, then TRUE
InArray = True
Exit Function
End If
Next i
InArray = False 'Otherwise, InArray is false
End Function
Public Function DateStamp(Optional AMPM As Boolean, Optional dateOnly As Boolean, Optional AMPMDateStamp As Boolean, Optional AMPMTimeStamp As Boolean) As String
'***************************************************
'**** created by Nathan N on 1/25/2012 ****
'Updated on 3/9/2012 to correct for the extra space in the AMPMTimeStamp
Dim timeStamp As String, timeStampAMPM As String, AMPMAndDateStamp As String
If dateOnly = True Then
DateStamp = Date
DateStamp = Replace(DateStamp, "/", " ")
Exit Function
End If
If AMPM = True Then
timeStamp = Time()
timeStamp = Replace(timeStamp, ":", " ")
timeStamp = Left(Trim(timeStamp), 2)
timeStampAMPM = Time()
timeStampAMPM = Right(Trim(Now()), 2)
DateStamp = timeStampAMPM
Exit Function
End If
If AMPMTimeStamp = True Then
DateStamp = Date
DateStamp = Replace(DateStamp, "/", " ")
timeStamp = Time()
timeStamp = Replace(timeStamp, ":", " ")
timeStamp = Replace(Left(Trim(timeStamp), 2), " ", "")
timeStampAMPM = Time()
timeStampAMPM = Right(Trim(Now()), 2)
AMPMAndDateStamp = timeStampAMPM & " - " & DateStamp
timeAndDateStamp = timeStamp & " " & timeStampAMPM & " - " & DateStamp
DateStamp = timeAndDateStamp
Exit Function
End If
If AMPMDateStamp = True Then
DateStamp = Date
DateStamp = Replace(DateStamp, "/", " ")
timeStamp = Time()
timeStamp = Replace(timeStamp, ":", " ")
timeStamp = Left(Trim(timeStamp), 2)
timeStampAMPM = Time()
timeStampAMPM = Right(Trim(Now()), 2)
AMPMAndDateStamp = timeStampAMPM & " - " & DateStamp
DateStamp = AMPMAndDateStamp
Exit Function
End If
End Function
Public Sub CleanServiceName(ByVal ws As Worksheet, ByVal serviceColNum As Integer)
'*** 3/6/2012 ***
Dim i As Long
Dim serviceName As String
For i = 2 To lastRow(ws)
serviceName = LCase(ws.Cells(i, serviceColNum))
If (serviceName Like "*recut*") Or (serviceName Like "*lawn*") Then
ws.Cells(i, serviceColNum) = "Ongoing Recut"
ElseIf serviceName Like "*maid*" Then
ws.Cells(i, serviceColNum) = "Ongoing Maid"
ElseIf serviceName Like "*pool*" Then
ws.Cells(i, serviceColNum) = "Ongoing Pool"
ElseIf serviceName Like "*snow*" Then
ws.Cells(i, serviceColNum) = "Ongoing Snow"
End If
Next i
End Sub
Public Sub CopyMultiValRows(sourceSheet As Worksheet, colLet As String, destSheet As Worksheet, copyValues As String, Optional copyHeader As Boolean)
Dim inverseRow As Long
Dim lastRowCurrent As Long
Dim lastRowDest As Long
Dim i As Long
If copyHeader <> False Then
copyHeader = True
End If
lastRowCurrent = sourceSheet.Range("A" & Rows.Count).End(xlUp).Row
origRowCount = sourceSheet.Range("A" & Rows.Count).End(xlUp).Row
If copyHeader = True Then
destSheet.Rows(1) = sourceSheet.Rows(1).value
lastRowDest = destSheet.Range("A" & Rows.Count).End(xlUp).Row
End If
For i = 2 To lastRowCurrent
inverseRowNum = origRowCount - i + 2
currentCellValue = sourceSheet.Range(colLet & inverseRowNum).value
If InStr(1, copyValues, currentCellValue) >= 1 Then
destSheet.Rows(lastRowDest + 1) = sourceSheet.Rows(inverseRowNum).value
lastRowDest = destSheet.Range("A" & Rows.Count).End(xlUp).Row
End If
Next i
End Sub
Sub CutMultiValRows(ByVal sourceSheet As Worksheet, ByVal colLet As String, ByVal destSheet As Worksheet, ByVal cutValues As String, Optional copyHeader As Boolean)
Dim inverseRow As Long
Dim lastRow As Long
Dim lastRowDest As Long
Dim i As Long
If copyHeader = "" Then
copyHeader = True
End If
lastRow = sourceSheet.Range(colLet & Rows.Count).End(xlUp).Row
origRowCount = sourceSheet.Range(colLet & Rows.Count).End(xlUp).Row
If copyHeader = True Then
destSheet.Rows(1) = sourceSheet.Rows(1).value
lastRowDest = destSheet.Range("A" & Rows.Count).End(xlUp).Row
End If
For i = 2 To lastRow
inverseRowNum = origRowCount - i + 2
currentCellValue = sourceSheet.Range(colLet & inverseRowNum).value
If InStr(1, cutValues, currentCellValue) >= 1 Then
destSheet.Rows(lastRowDest + 1) = sourceSheet.Rows(inverseRowNum).value
lastRowDest = destSheet.Range("A" & Rows.Count).End(xlUp).Row
sourceSheet.Rows(inverseRowNum).Delete Shift:=xlUp
End If
Next i
End Sub
Public Sub SortCol(ByVal ws As Worksheet, ByVal fieldName As String, Optional ByVal headerRowNum As Integer)
'*********************************************************
'*** Authored by Nathan N, on 1/18/2012
'***
'*** Updateed on 2/1/2012 at 11:19AM - Switched from function to sub
'*** Updated on 2/3/2012 at 1:00PM - Switched out sortColNum parameter with fieldname:string
'*** - Removed the application.visible property and implemented a Wait method
'*********************************************************
Dim sortColNum As Integer
sortColNum = FieldColNum(ws, fieldName)
If headerRowNum = 0 Then
headerRowNum = 1
End If
ws.Activate
ws.Sort.SortFields.Clear
ws.Sort.SortFields.Add ws.Cells(headerRowNum, sortColNum)
ws.Sort.Header = xlNo
ws.Sort.MatchCase = False
ws.Sort.SetRange ws.Range(Cells(headerRowNum + 1, 1), Cells(lastRow(ws), lastColNum(ws)))
'Application.Visible = True
Application.Wait Now + 0.000008
ws.Sort.Apply
'Application.Visible = False
End Sub
Public Sub SortMultiCol(ByVal ws As Worksheet, ByVal fieldName1 As String, Optional ByVal fieldName2 As String, Optional ByVal fieldName3 As String, Optional ByVal headerRowNum As Integer)
'*********************************************************
'*** Authored by Nathan N, on 2/27/2012
'*** Updated 2/28/2012 8:17AM - Added functionality for 3 columns to be sorted
'*********************************************************
Dim sortColNum1 As Integer, sortColNum2 As Integer
sortColNum1 = FieldColNum(ws, fieldName1)
If (FieldExists(ws, fieldName2)) And (fieldName2 <> "") Then
sortColNum2 = FieldColNum(ws, fieldName2)
End If
If FieldExists(ws, fieldName3) And (fieldName3 <> "") Then
sortColNum3 = FieldColNum(ws, fieldName3)
End If
If headerRowNum = 0 Then headerRowNum = 1
ws.Activate
ws.Sort.SortFields.Clear
ws.Sort.SortFields.Add ws.Cells(headerRowNum, sortColNum1)
If FieldExists(ws, fieldName2) And (fieldName2 <> "") Then ws.Sort.SortFields.Add ws.Cells(headerRowNum, sortColNum2)
If FieldExists(ws, fieldName3) And (fieldName3 <> "") Then ws.Sort.SortFields.Add ws.Cells(headerRowNum, sortColNum3)
ws.Sort.Header = xlNo
ws.Sort.MatchCase = False
ws.Sort.SetRange ws.Range(Cells(headerRowNum + 1, 1), Cells(lastRow(ws), lastColNum(ws)))
'Application.Visible = True
Application.Wait Now + 0.000008 '// This is needed in order for the function to work successfully
ws.Sort.Apply
'Application.Visible = False
End Sub
Public Sub remove_dupes(ByVal ws As Worksheet, ByVal fieldName As String)
'// Created on 5/3/2012 by Nathan N
Dim colNum As Integer
colNum = FieldColNum(ws, fieldName)
ws.Range(ws.Cells(1, 1), ws.Cells(lastRow(ws), lastColNum(ws))).RemoveDuplicates Columns:=colNum, Header:=xlYes
End Sub
Public Function lastRow(ByVal ws As Worksheet, Optional ByVal colLet As String, Optional ByVal colNum As Integer, Optional ByVal startRow As Long) As Long
'*********************************************************
'*** Authored by Nathan N, on 1/13/2012
'*** Updated 3/2/2012 - Added startRow functionality to find last rows of irregular data
'*** Updated 6/13/2012 - Added conditional block that took into account if a ColNum greater than 0 was used.
'*** Optional [colLet] parameter takes precedence over Optional [colNum]
'*** Detects the last row with data in a specified column letter
'*** PreCondition: 1. At least one worksheet row must have data
'*** 2. Optional: A specific column letter can be declared.
'*** If no column letter is declared, function will default
'*** to the "A" column
'*** PostCondition: Returns a number (Long type)
'*** Updated 3/9/2012 - included IF statement for colNum = 1 and startRow = 1
'*** Updated 4/3/2012 - Corrected bug that ended up adding one to the last row if the startRow>0
'*********************************************************
If colLet = "" And colNum = 0 Then colLet = "A"
If colLet <> "" And startRow = 0 Then
lastRow = ws.Range(colLet & Rows.Count).End(xlUp).Row
Exit Function
End If
If colLet = "" And colNum > 0 And startRow = 0 Then
lastRow = ws.Cells(Rows.Count, colNum).End(xlUp).Row
Exit Function
End If
If (colNum = 0) Then colNum = 1
If (startRow = 0) Then startRow = 1
If colNum = 1 And startRow = 1 Then
lastRow = ws.Range("A" & Rows.Count).End(xlUp).Row
Exit Function
End If
If startRow > 0 Then
For i = startRow To 500000
If ws.Cells(i, colNum) = "" Then
lastRow = i - 1
Exit Function
End If
Next i
End If
End Function
Public Function lastColNum(ByVal ws As Worksheet, Optional ByVal rowNum As Long = 1, Optional ByVal ignoreBreaks As Boolean = False) As Integer
'*********************************************************
'*** Authored byNathan N, on 1/13/2012
'*** Updated 6/13/2012 - Added Optional [rowNum] parameter to detect lastCol of a specific row
'*** This detects the last column number
'*** PreCondition: At least one column needs to be used on a worksheet
'*** PostCondition: Returns an integer of the last most column number
'*** that has data
'// Updated 7/12/2012 - Revised to use a loop as the primary last row detection mechanism instead of lastUsedCol built in function (was causing too many problems)
'// Updated 8/1/2012 - included optional ignoreBreaks parameter
'*********************************************************
Dim i As Integer
If ignoreBreaks Then
lastColNum = ws.UsedRange.Columns.Count
Exit Function
End If
For i = 1 To ws.UsedRange.Columns.Count + 1
If ws.Cells(rowNum, i) = "" Then
lastColNum = i - 1
Exit For
End If
Next i
If lastColNum = 0 Then lastColNum = ws.UsedRange.Columns.Count
End Function
Public Function LastColtoLet(ByVal currentSheet As Worksheet) As String
'*********************************************************
'*** Authored by Nathan N, on 1/13/2012
'***
'*** This returns the letter of an automatically detected last column number
'*** PreCondition: 1. A specific worksheet name must be declared
'*** 2. At least one column must have data within the column
'*** range of A to Z
'***
'*** PostCondition: Returns the letter (String Type) that was associated with
'*** the detected last column
'*********************************************************
Dim letArray() As Variant
Dim maxArrayCount As Long
Dim lastCol As Integer
ReDim letArray(0 To 100)
'--- More letters can be added to the letArray(0 to 25) to extend functionality, however
'--- the letArray must be redimensioned with more elements to match the
'--- quantity of letters listed. For instance, if "AA", "AB","AC" were added to letArray,
'--- we must redimension the letArray with the following: ReDim letArray(0 to 28)
letArray = Array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "AA", "AB", "AC", "AD", "AE", "AF", "AG", "AH", "AI", "AJ", "AK", "AL", "AM", "AN", "AO", "AP", "AQ", "AR", "AS", "AT", "AU", "AV", "AW", "AX", "AY", "AZ", "BA", "BB", "BC", "BD", "BE", "BF")
maxArrayCount = (Application.WorksheetFunction.CountA(letArray))
ReDim Preserve letArray(0 To maxArrayCount - 1)
lastCol = currentSheet.UsedRange.Columns.Count
LastColtoLet = letArray(lastCol - 1)
End Function
Public Function LetToColNum(ByVal s As String) As Integer
'*********************************************************
'*** Authored by Nathan N, on 3/20/2012
'***
'*** This returns the Col Num of a specified Col Let, up to BF
'*********************************************************
Dim letArray() As Variant
Dim maxArrayCount As Long
ReDim letArray(0 To 100)
letArray = Array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "AA", "AB", "AC", "AD", "AE", "AF", "AG", "AH", "AI", "AJ", "AK", "AL", "AM", "AN", "AO", "AP", "AQ", "AR", "AS", "AT", "AU", "AV", "AW", "AX", "AY", "AZ", "BA", "BB", "BC", "BD", "BE", "BF")
maxArrayCount = (Application.WorksheetFunction.CountA(letArray))
ReDim Preserve letArray(0 To maxArrayCount - 1)
For i = 0 To maxArrayCount
If UCase(s) = letArray(i) Then
LetToColNum = i + 1
Exit Function
End If
Next i
End Function
Public Function ColNumToLet(ByVal currentSheet As Worksheet, ByVal colNum As Integer) As String
'*********************************************************
'*** Authored by Nathan N, on 1/13/2012
'***
'*** This returns the letter of an automatically detected last column number
'*** PreCondition: 1. A specific worksheet name must be declared
'*** 2. At least one column must have data within the column
'*** range of A to Z
'***
'*** PostCondition: Returns the letter (String Type) that was associated with
'*** the detected last column
'*********************************************************
Dim letArray() As Variant
Dim maxArrayCount As Long
ReDim letArray(0 To 100)
'--- More letters can be added to the letArray(0 to 25) to extend functionality, however
'--- the letArray must be redimensioned with more elements to match the
'--- quantity of letters listed. For instance, if "AA", "AB","AC" were added to letArray,
'--- we must redimension the letArray with the following: ReDim letArray(0 to 28)
letArray = Array("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "AA", "AB", "AC", "AD", "AE", "AF", "AG", "AH", "AI", "AJ", "AK", "AL", "AM", "AN", "AO", "AP", "AQ", "AR", "AS", "AT", "AU", "AV", "AW", "AX", "AY", "AZ", "BA", "BB", "BC", "BD", "BE", "BF")
maxArrayCount = (Application.WorksheetFunction.CountA(letArray))
ReDim Preserve letArray(0 To maxArrayCount - 1)
'colNum = currentSheet.UsedRange.Columns.Count
ColNumToLet = letArray(colNum - 1)
End Function
Public Function FieldColLet(ByVal currentSheet As Worksheet, ByVal fieldName As String, Optional ByVal rowNum As Integer) As String
'*********************************************************