Complex FOR Statement

mharper90

Board Regular
Joined
May 28, 2013
Messages
117
Office Version
  1. 365
Platform
  1. MacOS
I can't seem to get this code to work. Any ideas? This is my first time using a FOR statement in VBA.

Code:
Sub Sort()

Dim x       As Long
Dim ws   As Worksheet

For x = 1 To 8

Set ws = ThisWorkbook.Sheets("P" & x & " Figure 2-2")

Lr = ws.Range("A" & Rows.Count).End(xlUp).Row

If Lr > 3 Then
     ws.Range("A3:O" & Lr).Sort Key1:=[C3], Order1:=xlAscending
     ws.Range("A3:O" & Lr).Sort Key1:=[A3], Order1:=xlAscending
End If

Next x

End Sub
 

Excel Facts

Highlight Duplicates
Home, Conditional Formatting, Highlight Cells, Duplicate records, OK to add pink formatting to any duplicates in selected range.
What part of it doesn't work ??
Have you stepped through line by line using F8 to see where it fails ??
 
Last edited:
Upvote 0
It would help if you described what you want the code to do. What is the difference between what it does and what you want it to do?

What your code actually does is cycle through 8 different worksheets, setting sort keys (but not actually performing a sort). The worksheets are named

P1 Figure 2-2
P2 Figure 2-2
P3 Figure 2-2
etc.

The code that sets the sort key won't work because you are setting Key1 using [brackets] which will refer to a range in the active sheet. You need this:

Code:
     ws.Range("A3:O" & Lr).Sort Key1:=ws.Range("C3"), Order1:=xlAscending

However, I am not at all sure that is the only problem.
 
Upvote 0

Forum statistics

Threads
1,224,823
Messages
6,181,181
Members
453,022
Latest member
Mohamed Magdi Tawfiq Emam

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