DIM AS problem

Damo71

Board Regular
Joined
Aug 17, 2010
Messages
88
Hi at the top of my code I have the line:
Code:
Dim nws As Worksheet
Then there are several lines of code as the macro works on the current sheet.
The macro creates (and selects) a new sheet, then i have the following line:
Code:
Set nws = ActiveSheet

when I run the macro, it breaks at this line:
Code:
ActiveWorkbook.Worksheets(nws).AutoFilter.Sort.SortFields.Clear
What am I doing wrong?

Thanks
 

Excel Facts

Copy PDF to Excel
Select data in PDF. Paste to Microsoft Word. Copy from Word and paste to Excel.
Rich (BB code):
ActiveWorkbook.nws.AutoFilter.Sort.SortFields.clear

nws is already a worksheet object.
Worksheets(nws) would work if nws was a string.
 
Upvote 0
All you need is

nws.AutoFilter.Sort.SortFields.Clear


When using worksheet objects, there is no need to specify the workbook
Because the active workbook is implied in this line

Set nws = ActiveSheet

Basically, the Active Workbook is assumed unless you specify otherwise...
So the nws object variable is already tied to whatever book was active at the time that code ran.


to specify a specific workbook for a worksheet object, do it in the SET line.

Set wsn = Workbooks("bookname.xls").Sheets("Sheetname")
If the blue part is omitted, then the current active book is assumed.



Hope that helps.
 
Upvote 0
While the other methods mentioned are a lot cleaner and I'd suggest going with those, below is an alternative that i believe represents what you were trying to do when you were setting up your code.

Code:
Dim nws As String
nws = ActiveSheet.Name

Then the below syntax would work:
Code:
ActiveWorkbook.Worksheets(nws).AutoFilter.Sort.SortFields.Clear
 
Upvote 0

Forum statistics

Threads
1,224,517
Messages
6,179,233
Members
452,898
Latest member
Capolavoro009

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