Wrong Value In Trying To Determine Last Occupied Cell in A Column

Ark68

Well-known Member
Joined
Mar 23, 2004
Messages
4,564
Office Version
  1. 365
  2. 2016
Platform
  1. Windows
I have this code that is intended to either insert, or delete, a range of cells depending on a default minimum and maximum number of rows in the "pda services" range. The "pda services" range is dynamic, and starts at the first row after the value "ADD" in column A of the worksheet (in my testing is currently row 22). The last row should always be 31 or greater if all rows up to and 31 are including. Once the range at row 31 is filled, the "pda services" range can continue to expand. The "pda_services" range cannot ever be less than 31.

I use the procedure 'rng_pdasvc' to determine the current "pda services range". I set that range to a variable "rng_pdaservices". It encompasses all the cells between columns A and R of the upper and lower rows identified in this procedure.

Code:
Sub rng_pdasvc()
  
  
    With ws_master
        'define pda service range
        rng_svctop = Application.Match("ADD", .Columns(1), 0) + 1 'row 22 in my testing
        If IsError(rng_svctop) = True Then MsgBox CLng(Split(CStr(rng_svctop), " ")(1))
          
        rng_svcbot = Application.Match("Facility Maintenance Activities", .Columns(1), 0) - 3
        If IsError(rng_svcbot) = True Then MsgBox CLng(Split(CStr(rng_svcbot), " ")(1))
      
        Set rng_pdaservices = .Range("A" & rng_svctop & ":Q" & rng_svcbot)
      
        dr_pdasvc = Range("A" & rng_svcbot).End(xlUp).Row + 1
    End With
      
End Sub

I then have code which finds the last row in range "rng_pdaservices". Despite "rng_pdaservices" being properly set, the value for strow is always 22, even if A23:A25 are occupied with values. I would expect a value of 26 in this case, but I only get 22.

Rich (BB code):
Sub trn_srv_svcrng()
 'determine pda service range
 'eliminate current RID entries in pda service range (rewritten in full)
 'export services from thold to pda service range (last row of data)
 'sort new pda range (inclusive of previous non rid rentals)
 'add rows to default pda size (21 rows between 12 and 32, shared rows 36/37 with staff - EVL1 & EVL2)
 'Stop
 Dim DelRng As Range
 Application.ScreenUpdating = False
   
    'define current pda services range
    rng_pdasvc
'Stop
    With ws_master
        .Unprotect
        mbevents = False
       
        'eliminate crid entries from rng_pdaservices
        .Activate
        For Each cell In rng_pdaservices.Columns(1).Rows
            Debug.Print "Cell Value" & cell.Value & "  cell: " & cell.Address
            If cell.Value = crid Then
                If DelRng Is Nothing Then Set DelRng = cell Else Set DelRng = Union(DelRng, cell)
            End If
        Next cell
        If Not DelRng Is Nothing Then Intersect(DelRng.EntireRow, rng_pdaservices).Delete
       
        'rng_pdasvc
        'strow = Application.WorksheetFunction.Match("ADD", .Columns(1), 0) + 1
        'On Error Resume Next
        'strow = rng_pdaservices.Columns(1).Find(What:="*", SearchDirection:=xlPrevious).Address(0, 0) + 1
        'On Error GoTo 0
        'ui1 = MsgBox("Insert row at: " & strow, vbQuestion + vbYesNo, "PDA Services")
        'If ui1 = vbYes Then
        '    .Range("A" & strow & ":R" & strow).Insert Shift:=xlDown
        'End If
        'svclr = Application.WorksheetFunction.Match("Facility Maintenance Activities", Columns(1), 0)
        'If svclr < 34 Then
        '    .Range("A31:R31").Insert Shift:=xlDown
        'End If
'Stop
        'add service to pda services range
        'determine destination row
        drow = Application.WorksheetFunction.Match("ADD", .Columns(1), 0) + 1
        On Error Resume Next
        drow = rng_pdaservices.Columns(1).Find(What:="*", SearchDirection:=xlPrevious).Address(0, 0) + 1
        On Error GoTo 0
        'MsgBox drow
   
        srvcs_no = Application.WorksheetFunction.CountA(ws_thold.Range("AK1:AK8"))
        scol = 13 'destination ws_master column M (row = srow)
        srccol = 1 'source row ws_thold column AI
       
       
        For L1 = 1 To srvcs_no
            If drow > 32 Then 'add row
                drow = drow + 1
                MsgBox "Not enough room. Row added at " & drow + 1, , "UNTESTED"
                Stop
                .Range("A" & drow & ":R" & drow).Insert Shift:=xlDown
            End If
            With .Range("H" & drow & ":Q" & drow)
                .Cells.Value = ""
                .Cells.Interior.Color = RGB(166, 166, 166)
                .Cells.locked = True
            End With
            If L1 = 5 Then
                scol = scol - 4
            End If
            Set rng_cpy = ws_master.Range("A" & srow & ":G" & srow)
            rng_cpy.Copy ws_master.Range("A" & drow)
            With .Cells(drow, scol)
                .Value = ws_thold.Cells(srccol, 39)
                .Interior.ColorIndex = 0
            End With
            If ws_thold.Cells(srccol, 36) = "RLN" Then
                d1 = "Reline"
            Else
                d1 = "Change"
            End If
            dmsg = d1 & " " & ws_thold.Cells(srccol, 37) & "-" & ws_thold.Cells(srccol, 38)
            With .Cells(drow, 2)
                .Font.Size = 6
                .Font.Color = vbBlack
                .Font.Bold = True
                .Value = dmsg
                .HorizontalAlignment = xlCenter
            End With
            With .Cells(drow, 8) '.Cells(drow, 18)
                .Value = ws_thold.Cells(srccol, 43)
                .Font.Size = 6
                .Font.Color = vbBlue 'RGB(229, 242, 251)
            End With

            .Rows(drow).AutoFit
            .Rows(drow).Cells.locked = True
            .Range(.Cells(drow, 1), .Cells(drow, 17)).VerticalAlignment = xlCenter
            scol = scol + 1
            srccol = srccol + 1
            drow = drow + 1
        Next L1
        Stop
        rng_pdasvc
        strow = Application.WorksheetFunction.Match("ADD", .Columns(1), 0) + 1
        On Error Resume Next
        strow = rng_pdaservices.Columns(1).Find(What:="*", SearchDirection:=xlPrevious).Address(0, 0) + 1
        On Error GoTo 0
        
        mtrow = Application.WorksheetFunction.Match("Facility Maintenance Activities", .Columns(1), 0) - 3
        If mtrow > 31 And .Range("A31") <> "" Then
            ui1 = MsgBox("Delete row at: " & strow, vbQuestion + vbYesNo, "PDA Services")
            If ui1 = vbYes Then
                .Range("A" & strow & ":R" & strow).Delete Shift:=xlUp
            End If
        End If
        If mtrow < 31 Then
            ui1 = MsgBox("Add row at: " & strow, vbQuestion + vbYesNo, "PDA Services")
            If ui1 = vbYes Then
                .Range("A" & strow & ":R" & strow).Insert Shift:=xlDown
            End If
        End If
       
'Stop
        pda_sort rng_pdaservices
        .Protect
        mbevents = True
    End With
    Application.ScreenUpdating = True
'Stop 'try save      SAVE FAILS
End Sub

Any ideas.
 
Last edited:

Excel Facts

What did Pito Salas invent?
Pito Salas, working for Lotus, popularized what would become to be pivot tables. It was released as Lotus Improv in 1989.
Your sub rng_pdasvc is not doing anything.
Yes you are calling it but the variable you are setting has a scope of just that module so it is gone when Sub trn_srv_svcrng() continues.

Your strow is being set by this and I expect this always returns 22 + 1 = 23
strow = Application.WorksheetFunction.Match("ADD", .Columns(1), 0) + 1
(I didn't test that the find statement after that fails but I expect that it is not doing anything)
 
Upvote 0
Oops scope is that procedure (not module)
Thank your Alex! I'm not 100% I understand what the solution might be. It doesn't show in the code I provided, but "rng_pdaservices" is declared publically. I actually use this same code at the beginning of procedure Sub trn_srv_svcrng() and its results are consistently correct. I reexecute 'sub rng_pdasvc" to adjust the range of 'rng_pdaservices'.

Am I still missing something?
 
Upvote 0
I am struggling to understand what you want the Sub rng_pdasvc() to return.
Do you want to give me a picture or an XL2BB of the worksheet and explain what range you are trying to get ?
So based on the image you send me what should rng_pdaservices be and what should strow be ?

This line doesn't seem to do anything:-
dr_pdasvc = Range("A" & rng_svcbot).End(xlUp).Row + 1

And this line doesn't look like it would work:-
strow = rng_pdaservices.Columns(1).Find(What:="*", SearchDirection:=xlPrevious).Address(0, 0) + 1
 
Upvote 0
Thank you Alex for your continued support, and for anyone else that is trying to follow along. I am a novice VBA user so much of my work is linear and not the most efficient. For now, I'm just working to get results. For these reasons I have to apologize for the lack of proper terms or rationale approach. I will try to explain my logic and expectations the best I can.

First ...
This line doesn't seem to do anything:-
dr_pdasvc = Range("A" & rng_svcbot).End(xlUp).Row + 1
You're right. It's extraneous code without a purpose I haven't removed yet.

task allocation.xlsm
ABCDEFGHIJKLMNOPQ
103-Jun 9:12 AMSunday July 12, 2020
2
3
4Min TimeALLMax Time
5
6
7
8Program Delivery ActivitiesDocument times completed
9TOURNAMENT RELINING
10Record IDDispatchRentalLocationActivityGroomPrepareSignatureLights OnLights Off1/52/63/74/8Close
11
12
134.4E+07iniR2683vvvvvv9:00A8:00PCUE1RPE1RPE1WPE1WPE1RPL1
144.4E+07DRR2685vvvvvv9:00A11:00A
154.4E+07DRR2688vvvvvv9:00A8:00P
164.4E+07DRR2686vvvvvv3:00P11:00P
174.4E+07DRR2687vvvvvv6:00P8:00P
184.4E+07FRR1960vvvvvv9:30A6:00P
194.4E+07FRR1960vvvvvv9:30A6:00P
204.4E+07CRR2710vvvvvv6:30P8:00P
21ADD
22
234.4E+07Reline 10:00A-10:30AR2683vvvvvv9:00A8:00P0.416666667WPE1
244.4E+07Reline 12:00P-12:30PR2683vvvvvv9:00A8:00P0.5WPE1
25
26
27
28
29
30
31
32
Master


With reference with the clip above, let me relate my approach and code. Remember, this worksheet ("ws_master")and its two ranges -PDA Booking Range (in this example A12:Q21) and PDA Service Range (in this example A22:Q32) - are very dynamic and this represents test data only.

A few rules exist for these combined areas.
Row 12 , must always remain empty, and
the last row for the PDA Service range (row 32 in this case) must remain empty.
No empty rows between the PDA Booking and PDA Service ranges when data exists for the PDA services range (ie no empty row between add and the first row of data in the PDA Services range
the combined PDA Booking and PDA Service ranges must be maintained at 21 rows (12-32), even if the balance is maintained as empty cells. The PDA Service range can expand, but only after the default Service range has been filled (ie last row of data in row 31.

What I call the "PDA Booking range" is represented by range "A13:Q20". It is populated in another procedure within my project. The PDA Booking range is always followed by "ADD" in the next empty cell incolumn A, in this case 21.

The "PDA Service Range" are cells A:Q between the row after "ADD" (in this case 22). The PDA Service range is defined publically as a range and is created and set in this procedure below. It has a variable name of rng_pdaservices. The PDA range gets populated, row by row, based on data imported from user manipulated data from another worksheet. Data can be added to the range thuis expanding the PDA Service range, or deleted thuis reducing the PDA Service range. Because the PDA service range has to be maintained at a certain size, it is necessary to add and delete empty rows.

Code:
Sub rng_pdasvc()
    With ws_master
        'define pda service range
        rng_svctop = Application.Match("ADD", .Columns(1), 0) + 1
        If IsError(rng_svctop) = True Then MsgBox CLng(Split(CStr(rng_svctop), " ")(1))
            
        rng_svcbot = Application.Match("Facility Maintenance Activities", .Columns(1), 0) - 3
        If IsError(rng_svcbot) = True Then MsgBox CLng(Split(CStr(rng_svcbot), " ")(1))
        
        Set rng_pdaservices = .Range("A" & rng_svctop & ":Q" & rng_svcbot)
    End With
End Sub

The PDA range gets populated, row by row, based on data imported from user manipulated data from another worksheet. Data can be added to the range thuis expanding the PDA Service range, or deleted thuis reducing the PDA Service range. Because the PDA service range has to be maintained at a certain size, it is necessary to add and delete empty rows. The procedure below is supposed to accomplish this, and for the most part it does. (I've added green comments to explain each action of the code to help understand my approach).

Rich (BB code):
Sub trn_srv_svcrng()

   Dim DelRng As Range 'range of and deleted ranges from within PDA Service range
   Application.ScreenUpdating = False
    
   rng_pdasvc   'define the PDA service range ("ADD"+1):("Facility Maintenance Activities"-3) - Sets range variable rng_pdaservices

    With ws_master 'the worksheet in my post
        .Unprotect
        mbevents = False 'don't trigger any worksheet change events
        
        'reset the PDA services range by eliminating any/all previous data relating to that  particular RID (crid). The PDA service range could hold data from
        '     several different RID's, but this procedure is intended only to manipute the one specified RID by recreating it particular data within the shared range
        .Activate
        'the next section (in purple) deletes those ranges identified having the target RID in column A of rng_pdaservices.

        For Each cell In rng_pdaservices.Columns(1).Rows
            Debug.Print "Cell Value" & cell.Value & "  cell: " & cell.Address
            If cell.Value = crid Then
                If DelRng Is Nothing Then Set DelRng = cell Else Set DelRng = Union(DelRng, cell)
            End If
        Next cell
        If Not DelRng Is Nothing Then Intersect(DelRng.EntireRow, rng_pdaservices).Delete
        
        'rng_pdasvc
        'strow = Application.WorksheetFunction.Match("ADD", .Columns(1), 0) + 1
        'On Error Resume Next
        'strow = rng_pdaservices.Columns(1).Find(What:="*", SearchDirection:=xlPrevious).Address(0, 0) + 1
        'On Error GoTo 0
        'ui1 = MsgBox("Insert row at: " & strow, vbQuestion + vbYesNo, "PDA Services")
        'If ui1 = vbYes Then
        '    .Range("A" & strow & ":R" & strow).Insert Shift:=xlDown
        'End If
        'svclr = Application.WorksheetFunction.Match("Facility Maintenance Activities", Columns(1), 0)
        'If svclr < 34 Then
        '    .Range("A31:R31").Insert Shift:=xlDown
        'End If
'Stop
        'add service to pda services range
        'determine destination row
        drow = Application.WorksheetFunction.Match("ADD", .Columns(1), 0) + 1
        On Error Resume Next
        drow = rng_pdaservices.Columns(1).Find(What:="*", SearchDirection:=xlPrevious).Address(0, 0) + 1
        On Error GoTo 0
        'MsgBox drow
    
        srvcs_no = Application.WorksheetFunction.CountA(ws_thold.Range("AK1:AK8"))
        scol = 13 'destination ws_master column M (row = srow)
        srccol = 1 'source row ws_thold column AI
        
        
        For L1 = 1 To srvcs_no
            If drow > 32 Then 'add row
                drow = drow + 1
                MsgBox "Not enough room. Row added at " & drow + 1, , "UNTESTED"
                Stop
                .Range("A" & drow & ":R" & drow).Insert Shift:=xlDown
            End If
            With .Range("H" & drow & ":Q" & drow)
                .Cells.Value = ""
                .Cells.Interior.Color = RGB(166, 166, 166)
                .Cells.locked = True
            End With
            If L1 = 5 Then
                scol = scol - 4
            End If
            Set rng_cpy = ws_master.Range("A" & srow & ":G" & srow)
            rng_cpy.Copy ws_master.Range("A" & drow)
            With .Cells(drow, scol)
                .Value = ws_thold.Cells(srccol, 39)
                .Interior.ColorIndex = 0
            End With
            If ws_thold.Cells(srccol, 36) = "RLN" Then
                d1 = "Reline"
            Else
                d1 = "Change"
            End If
            dmsg = d1 & " " & ws_thold.Cells(srccol, 37) & "-" & ws_thold.Cells(srccol, 38)
            With .Cells(drow, 2)
                .Font.Size = 6
                .Font.Color = vbBlack
                .Font.Bold = True
                .Value = dmsg
                .HorizontalAlignment = xlCenter
            End With
            With .Cells(drow, 8) '.Cells(drow, 18)
                .Value = ws_thold.Cells(srccol, 43)
                .Font.Size = 6
                .Font.Color = vbBlue 'RGB(229, 242, 251)
            End With

            .Rows(drow).AutoFit
            .Rows(drow).Cells.locked = True
            .Range(.Cells(drow, 1), .Cells(drow, 17)).VerticalAlignment = xlCenter
            scol = scol + 1
            srccol = srccol + 1
            drow = drow + 1
        Next L1
        Stop
        rng_pdasvc
        strow = Application.WorksheetFunction.Match("ADD", .Columns(1), 0) + 1
        On Error Resume Next
        strow = rng_pdaservices.Columns(1).Find(What:="*", SearchDirection:=xlPrevious).Address(0, 0) + 1
        On Error GoTo 0
        
        mtrow = Application.WorksheetFunction.Match("Facility Maintenance Activities", .Columns(1), 0) - 3
        If mtrow > 31 And .Range("A31") <> "" Then
            ui1 = MsgBox("Delete row at: " & strow, vbQuestion + vbYesNo, "PDA Services")
            If ui1 = vbYes Then
                .Range("A" & strow & ":R" & strow).Delete Shift:=xlUp
            End If
        End If
        If mtrow < 31 Then
            ui1 = MsgBox("Add row at: " & strow, vbQuestion + vbYesNo, "PDA Services")
            If ui1 = vbYes Then
                .Range("A" & strow & ":R" & strow).Insert Shift:=xlDown
            End If
        End If
        
'Stop
        pda_sort rng_pdaservices
        .Protect
        mbevents = True
    End With
    Application.ScreenUpdating = True
'Stop 'try save      SAVE FAILS
End Sub
 
Upvote 0
Where is “Facility Maintenance Activities” which seems to be required to determine the bottom of the range?
 
Upvote 0
Disregard post 6 (mods please delete it) , the post was submitted before I had a chance to complete it. Here is the complete submission....

Thank you Alex for your continued support, and for anyone else that is trying to follow along. I am a novice VBA user so much of my work is linear and not the most efficient. For now, I'm just working to get results. For these reasons I have to apologize for the lack of proper terms or rationale approach. I will try to explain my logic and expectations the best I can.

First ...
This line doesn't seem to do anything:-
dr_pdasvc = Range("A" & rng_svcbot).End(xlUp).Row + 1
You're right. It's extraneous code without a purpose I haven't removed yet.

task allocation.xlsm
ABCDEFGHIJKLMNOPQ
103-Jun 9:12 AMSunday July 12, 2020
2
3
4Min TimeALLMax Time
5
6
7
8Program Delivery ActivitiesDocument times completed
9TOURNAMENT RELINING
10Record IDDispatchRentalLocationActivityGroomPrepareSignatureLights OnLights Off1/52/63/74/8Close
11
12
134.4E+07iniR2683vvvvvv9:00A8:00PCUE1RPE1RPE1WPE1WPE1RPL1
144.4E+07DRR2685vvvvvv9:00A11:00A
154.4E+07DRR2688vvvvvv9:00A8:00P
164.4E+07DRR2686vvvvvv3:00P11:00P
174.4E+07DRR2687vvvvvv6:00P8:00P
184.4E+07FRR1960vvvvvv9:30A6:00P
194.4E+07FRR1960vvvvvv9:30A6:00P
204.4E+07CRR2710vvvvvv6:30P8:00P
21ADD
22
234.4E+07Reline 10:00A-10:30AR2683vvvvvv9:00A8:00P0.416666667WPE1
244.4E+07Reline 12:00P-12:30PR2683vvvvvv9:00A8:00P0.5WPE1
25
26
27
28
29
30
31
32
33
34Facility Maintenance Activitiesdocument assigned and non-assigned maintenance activities
35
36W/OLocationActivity(Time)CompleteIncompleteInitials
37
Master


With reference with the clip above, let me relate my approach and code. Remember, this worksheet ("ws_master")and its two ranges -PDA Booking Range (in this example A12:Q21) and PDA Service Range (in this example A22:Q32) - are very dynamic and this represents test data only.

A few rules exist for these combined areas.
Row 12 , must always remain empty, and
the last row for the PDA Service range (row 32 in this case) must remain empty.
No empty rows between the PDA Booking and PDA Service ranges when data exists for the PDA services range (ie no empty row between add and the first row of data in the PDA Services range
the combined PDA Booking and PDA Service ranges must be maintained at 21 rows (12-32), even if the balance is maintained as empty cells. The PDA Service range can expand, but only after the default Service range has been filled (ie last row of data in row 31.

What I call the "PDA Booking range" is represented by range "A13:Q20". It is populated in another procedure within my project. The PDA Booking range is always followed by "ADD" in the next empty cell incolumn A, in this case 21.

The "PDA Service Range" are cells A:Q between the row after "ADD" (in this case 22). The PDA Service range is defined publically as a range and is created and set in this procedure below. It has a variable name of rng_pdaservices. The PDA range gets populated, row by row, based on data imported from user manipulated data from another worksheet. Data can be added to the range thuis expanding the PDA Service range, or deleted thuis reducing the PDA Service range. Because the PDA service range has to be maintained at a certain size, it is necessary to add and delete empty rows.

Code:
Sub rng_pdasvc()
    With ws_master
        'define pda service range
        rng_svctop = Application.Match("ADD", .Columns(1), 0) + 1
        If IsError(rng_svctop) = True Then MsgBox CLng(Split(CStr(rng_svctop), " ")(1))
           
        rng_svcbot = Application.Match("Facility Maintenance Activities", .Columns(1), 0) - 3
        If IsError(rng_svcbot) = True Then MsgBox CLng(Split(CStr(rng_svcbot), " ")(1))
       
        Set rng_pdaservices = .Range("A" & rng_svctop & ":Q" & rng_svcbot)
    End With
End Sub

The PDA range gets populated, row by row, based on data imported from user manipulated data from another worksheet. Data can be added to the range thuis expanding the PDA Service range, or deleted thuis reducing the PDA Service range. Because the PDA service range has to be maintained at a certain size, it is necessary to add and delete empty rows. The procedure below is supposed to accomplish this, and for the most part it does. (I've added green comments to explain each action of the code to help understand my approach).

Rich (BB code):
Sub trn_srv_svcrng()

   Dim DelRng As Range 'range of and deleted ranges from within PDA Service range
   Application.ScreenUpdating = False
   
   rng_pdasvc   'define the PDA service range ("ADD"+1):("Facility Maintenance Activities"-3) - Sets range variable rng_pdaservices

    With ws_master 'the worksheet in my post
        .Unprotect
        mbevents = False 'don't trigger any worksheet change events
       
        'reset the PDA services range by eliminating any/all previous data relating to that  particular RID (crid). The PDA service range could hold data from
        '     several different RID's, but this procedure is intended only to manipute the one specified RID by recreating it particular data within the shared range
        .Activate
        'the next section (in purple) deletes those ranges identified having the target RID in column A of rng_pdaservices.
        '   I don't know how it works, but thanks to Fluff, it does. (https://www.mrexcel.com/board/threads/loop-through-cells-of-a-column-of-a-dynamic-range-of-cells.1171862/#post-5696859)
        For Each cell In rng_pdaservices.Columns(1).Rows
            Debug.Print "Cell Value" & cell.Value & "  cell: " & cell.Address
            If cell.Value = crid Then
                If DelRng Is Nothing Then Set DelRng = cell Else Set DelRng = Union(DelRng, cell)
            End If
        Next cell
        If Not DelRng Is Nothing Then Intersect(DelRng.EntireRow, rng_pdaservices).Delete
       
        'begin the process of replacing the data for that RID. Data comes from another worksheet. Although we are replacing data that we just removed, 
        '   it might be easiest to do it this way as the previous data may have been changed
        'below, we determine the destination row (drow) of the data to be added to the PDA Service range. It will be determined by the next EMPTY cell in column
        '    A of the previously determined rng_pdaservices range. If nothing is found, the destination row = the start of the PDA service range (1st row after           '    "ADD"
        drow = Application.WorksheetFunction.Match("ADD", .Columns(1), 0) + 1
        On Error Resume Next
        drow = rng_pdaservices.Columns(1).Find(What:="*", SearchDirection:=xlPrevious).Address(0, 0) + 1
        On Error GoTo 0
        'MsgBox drow
   
        srvcs_no = Application.WorksheetFunction.CountA(ws_thold.Range("AK1:AK8"))  'source of data represent how many ranges of data will be added to the PDA Service range for that particular RID
        scol = 13 'destination ws_master column M (row = srow)
        srccol = 1 'source row ws_thold column AI
       
       'loop through all the services and add, and format them in the PDA services range
        For L1 = 1 To srvcs_no
            'the default PDA service range is full when data already exists in row 32, so add a row as the new desitation row
            If drow > 32 Then 
                drow = drow + 1
                MsgBox "Not enough room. Row added at " & drow + 1, , "UNTESTED"
                'insert the blank row (drow)
                .Range("A" & drow & ":R" & drow).Insert Shift:=xlDown
            End If
            'format destination row and import data
            With .Range("H" & drow & ":Q" & drow)
                .Cells.Value = ""
                .Cells.Interior.Color = RGB(166, 166, 166)
                .Cells.locked = True
            End With
            If L1 = 5 Then
                scol = scol - 4
            End If
            Set rng_cpy = ws_master.Range("A" & srow & ":G" & srow)
            rng_cpy.Copy ws_master.Range("A" & drow)
            With .Cells(drow, scol)
                .Value = ws_thold.Cells(srccol, 39)
                .Interior.ColorIndex = 0
            End With
            If ws_thold.Cells(srccol, 36) = "RLN" Then
                d1 = "Reline"
            Else
                d1 = "Change"
            End If
            dmsg = d1 & " " & ws_thold.Cells(srccol, 37) & "-" & ws_thold.Cells(srccol, 38)
            With .Cells(drow, 2)
                .Font.Size = 6
                .Font.Color = vbBlack
                .Font.Bold = True
                .Value = dmsg
                .HorizontalAlignment = xlCenter
            End With
            With .Cells(drow, 8) '.Cells(drow, 18)
                .Value = ws_thold.Cells(srccol, 43)
                .Font.Size = 6
                .Font.Color = vbBlue 'RGB(229, 242, 251)
            End With

            .Rows(drow).AutoFit
            .Rows(drow).Cells.locked = True
            .Range(.Cells(drow, 1), .Cells(drow, 17)).VerticalAlignment = xlCenter
            scol = scol + 1
            srccol = srccol + 1
            drow = drow + 1
        Next L1
        
        'in initial testing, this all worked wonderfully, however, the default PDA range wasn't being maintained. Depending on the data import process, 
        '     there were more or less empty rows needed to maintain the row 32 target. It was necessary to add or remove ranges to hit the default target.
       
        'reset the new PDA Service range after it had changed from the original
        rng_pdasvc

        ' determine destination row (strow) of either range deletion or insertion
        ' using the same successful concept as above, find the last occupied cell in column A in the newly set rng_pdasvc
        ' if nothing is found, the strow defaults to the top of the the PDA Service range
       
        strow = Application.WorksheetFunction.Match("ADD", .Columns(1), 0) + 1
        On Error Resume Next
        strow = rng_pdaservices.Columns(1).Find(What:="*", SearchDirection:=xlPrevious).Address(0, 0) + 1
        On Error GoTo 0
       
        'add an empty range of cells, or delete based on the current size of the PDA Service range
        'this could be problematic for those instances where PDA service expansion is acceptable.
        'any added or deleted rows will be under the last occupied cell in column A (strow)
        mtrow = Application.WorksheetFunction.Match("Facility Maintenance Activities", .Columns(1), 0) - 3
        If mtrow > 31 And .Range("A31") <> "" Then
            ui1 = MsgBox("Delete row at: " & strow, vbQuestion + vbYesNo, "PDA Services")
            If ui1 = vbYes Then
                .Range("A" & strow & ":R" & strow).Delete Shift:=xlUp
            End If
        End If
        If mtrow < 31 Then
            ui1 = MsgBox("Add row at: " & strow, vbQuestion + vbYesNo, "PDA Services")
            If ui1 = vbYes Then
                .Range("A" & strow & ":R" & strow).Insert Shift:=xlDown
            End If
        End If

        pda_sort rng_pdaservices
        .Protect
        mbevents = True
    End With
    Application.ScreenUpdating = True
End Sub

All of this works, but we start having issues at the point where the code in red fires. The value of strow is always 22. With reference to the worksheet attached, you will see a blank row at 22. This is what this code put there and shouldn't have. The empty range should have been put in after the last occupied cell in A (of rng_pdaservices) ... row 25. strow is being calculated as 22 when it should be 24. I don't think the red code is finding anything, so it's defaulting to the start of the PDA service range. The addition of the single row was needed to maintain the default PDA service range.
 
Upvote 0
I am Australia and it's 1am here, so I will have another look later today (Friday).
 
Upvote 0
Take a copy of your current spreadsheet first.

Then my thoughts are:
Remove your Module / Global level --> "Dim rng_pdaservices As Range"

Replace what is currently a sub with the function rng_pdasvc below.
Wherever you want to use it put this:

VBA Code:
        Set rng_pdaservices = rng_pdasvc
        If rng_pdaservices Is Nothing Then Exit Sub

Change your find statements to this:
(you needed ".row", they are currently trying to return an address and erroring out, you are after the row no)
VBA Code:
  strow = rng_pdaservices.Columns(1).Find(What:="*", SearchDirection:=xlPrevious).Row + 1

Function rng_pdasvc
Note: I have done away with -3 after finding the Facilities row and replaced is with End(xUp) to find the previous non-blank cell
VBA Code:
Function rng_pdasvc() As Range
    Dim rng_svctop As Long
   
    With ws_master
        'define pda service range
       
        On Error GoTo EH
       
        rng_svctop = Application.Match("ADD", .Columns(1), 0) + 1
        rng_svcbot = Application.Match("Facility Maintenance Activities", .Columns(1), 0) ' removed - 3
        Set rng_pdasvc = .Range("A" & rng_svctop & ":Q" & .Range("A" & rng_svcbot).End(xlUp).Row)
     
    End With
    Exit Function
   
EH:
    MsgBox "Either ADD or Facility Maintenance Activities Not Found"
     
End Function
 
Upvote 0
Solution

Forum statistics

Threads
1,214,971
Messages
6,122,525
Members
449,088
Latest member
RandomExceller01

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