简体   繁体   中英

Excel macro causes strange behaviour

Hi there quite new to Excel macros im working on one here that sorts using the autofilter. It works fine and does what I want just when I try to resort the data it shows it within the wrong sheet. Anyway here is my macro

Sub Hide_Unassigned()
Worksheets("Resource View (2)").Activate
Dim LastRow As Long, c As Range
Application.EnableEvents = False
LastRow = Cells(Cells.Rows.Count, "D").End(xlUp).Row

ActiveWorkbook.Worksheets("Master Data").AutoFilter.Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Master Data").AutoFilter.Sort. _
    SortFields.Add Key:=Range("Z1:Z200"), SortOn:=xlSortOnValues, Order:= _
    xlDescending, DataOption:=xlSortNormal
        With ActiveWorkbook.Worksheets("Master Data").AutoFilter.Sort
    .Header = xlYes
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With
On Error Resume Next
For Each c In Range("D1:D" & LastRow)
If c.Value = "Unassigned" Then
    c.EntireRow.Hidden = True
Else
    c.EntireRow.Hidden = False
End If

Next
    ActiveWorkbook.Worksheets("Master Data").AutoFilter.Sort.SortFields.Clear
    ActiveWorkbook.Worksheets("Master Data").AutoFilter.Sort. _
    SortFields.Add Key:=Range("D1:D200"), SortOn:=xlSortOnValues, Order:= _
    xlAscending, DataOption:=xlSortNormal
        With ActiveWorkbook.Worksheets("Master Data").AutoFilter.Sort
    .Header = xlYes
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With
On Error GoTo 0
Application.EnableEvents = True
End Sub

As i said everything works fine except when I attempt to re-sort the data in master data it shows up in the resource view (2) sheet. It can then be removed by simply dragging over it but I dont think thats sufficient.

Thanks in advance for any suggestions or help

遇到了麻烦,当我访问主数据表本身时,通过简单地移动要调用的宏的最后部分,就设法对自己进行了排序。

Don't use Active(anything) . This is what will happen when you do.

Add:

Dim MstrDataWS as Worksheet
Dim ResWS as Worksheet
Set ResWS = Worksheets("Resource View (2)")
Set MstrDataWS = ActiveWorkbook.Worksheets("Master Data")

Then, every time you want to reference one worksheet or the other, use MstrDataWS or ResWS , as appropriate. That will ensure you're referencing the correct sheet. It also allows you to eliminate all references to .Activate and .Select .

Also, Cells() and Range() refer to whatever the active sheet is, so you can get lost there. Adjust those commands to use ResWS.Cells() or MstrDataWS.Cells() as appropriate.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM