2015-10-12 23 views
1

我想通过构建一个宏来对用户进行排序和求和。宏需要找到最后一行,然后进行排序,然后再进行小计和总计。它也应该使用当前的活动工作表。举例来说,我应该把第一个电子表格到第二:对不同大小的电子表格进行排序和求和

Pre and Post Spreadsheet

我能够与宏的一个简单的记录做此数据集。

Sub Macro1() 
' 
' Macro1 Macro 
' 
' Keyboard Shortcut: Ctrl+Shift+B 
' 
    ActiveWorkbook.Worksheets("Oct 2015").Sort.SortFields.Clear 
    ActiveWorkbook.Worksheets("Oct 2015").Sort.SortFields.Add Key:=Range("A2:A24" _ 
     ), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal 
    ActiveWorkbook.Worksheets("Oct 2015").Sort.SortFields.Add Key:=Range("B2:B24" _ 
     ), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal 
    With ActiveWorkbook.Worksheets("Oct 2015").Sort 
     .SetRange Range("A1:C24") 
     .Header = xlYes 
     .MatchCase = False 
     .Orientation = xlTopToBottom 
     .SortMethod = xlPinYin 
     .Apply 
    End With 
    Selection.Subtotal GroupBy:=1, Function:=xlSum, TotalList:=Array(3), _ 
     Replace:=True, PageBreaks:=False, SummaryBelowData:=True 
    Selection.Subtotal GroupBy:=2, Function:=xlSum, TotalList:=Array(3), _ 
     Replace:=False, PageBreaks:=False, SummaryBelowData:=True 
    Range("A1:C45").Select 
End Sub 

我有下面的代码位找到了最后一排,但不知道如何将它集成到上面来代替硬编码的“范围”值。

Sub GetLastRow(strSheet, strColum) 
Dim MyRange As Range 
Dim lngLastRow As Long 

    Set MyRange = Worksheets(strSheet).Range(strColum & "1") 

    lngLastRow = Cells(sheetvar.Rows.Count, MyRange.Column).End(xlUp).Row 
End Sub 

我还需要将活动工作表值更改为当前打开的工作表,因为此值将更改。

列名称和列顺序应该一致。我还需要将这个脚本放在远程用户的PC上,并确保它们在打开Excel时可用。

如果可能,我还想遮蔽小区域,但这是次要要求。

回答

-1

你已经走了一半。 首先您声明当前工作表的变量,范围和最后一行和一列。 然后您将它们全部实施到您刚录制的宏中。

Sub Macro1() 
    ' 
    ' Macro1 Macro 
    ' 
    ' Keyboard Shortcut: Ctrl+Shift+B 


    Dim sht As Worksheet 
     Dim lRow As Long, lCol As Long 
     Dim rng As Range 
Set sht = ActiveWorkbook.ActiveSheet 
    With sht 

      lRow = .Range("A" & .Rows.Count).End(xlUp).Row 
      lCol = .Cells(1, .Columns.Count).End(xlToLeft).Column 
     Set rng = .Range(.Cells(lRow, 1), .Cells(lRow, lCol)) 
    End With 

     sht.Sort.SortFields.Clear 
     sht.Sort.SortFields.Add Key:=rng, SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal 
     sht.Sort.SortFields.Add Key:=rng, SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal 
     With sht.Sort 
      .SetRange rng 
      .Header = xlYes 
      .MatchCase = False 
      .Orientation = xlTopToBottom 
      .SortMethod = xlPinYin 
      .Apply 
     End With 
     Selection.Subtotal GroupBy:=1, Function:=xlSum, TotalList:=Array(3), _ 
      Replace:=True, PageBreaks:=False, SummaryBelowData:=True 
     Selection.Subtotal GroupBy:=2, Function:=xlSum, TotalList:=Array(3), _ 
      Replace:=False, PageBreaks:=False, SummaryBelowData:=True 

    End Sub 
+1

很好的工作与此,OP确实要求它是活动工作表,而不是只有一张,所以他可以使用它不止一个。也许可以改变对activexheet的sht引用。 –

+1

感谢Scott,编辑了我的答案。 – Balinti

+0

谢谢。当执行时,我得到了“运行时错误'1004':排序参考无效... – jabs

相关问题