excel VBA可以对不同的工作表进行排序

时间:2015-08-17 18:07:04

标签: excel vba excel-vba

我想知道是否有办法让我的宏执行以下操作:

我希望它在sheet2上运行此代码:

Dim arrColOrder As Variant, ndx As Integer
Dim Found As Range, counter As Integer

'Place the column headers in the end result order you want.
arrColOrder = Array("*Item1*", "*Item2*", "*Item3*", "*Item4*")

counter = 1

Application.ScreenUpdating = False

For ndx = LBound(arrColOrder) To UBound(arrColOrder)

    Set Found = Rows("1:1").Find(arrColOrder(ndx), LookIn:=xlValues, LookAt:=xlWhole, _
                      SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:=False)

    If Not Found Is Nothing Then
        If Found.Column <> counter Then
            Found.EntireColumn.Cut
            Columns(counter).Insert Shift:=xlToRight
            Application.CutCopyMode = False
        End If
        counter = counter + 1
    End If
Next ndx

Application.ScreenUpdating = True

End Sub

然后在sheet1上运行此代码:

&#39;这将根据A列中的Item1为Item2,Item3和Item4数据点添加三列。

    Columns("P:P").Select
    Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
    Range("P1").Select
    ActiveCell.FormulaR1C1 = "Item4"
    Columns("P:P").Select
    Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
    Range("P1").Select
    ActiveCell.FormulaR1C1 = "Item3"
    Columns("P:P").Select
    Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
    Range("P1").Select
    ActiveCell.FormulaR1C1 = "Item2"
    Range("P1:R1").Select
    Range("R1").Activate
    With Selection.Interior
        .Pattern = xlSolid
        .PatternColorIndex = xlAutomatic
        .Color = 15773696
        .TintAndShade = 0
        .PatternTintAndShade = 0
    End With
    Range("P2").Select
    ActiveCell.FormulaR1C1 = "=VLOOKUP(RC[10],Sheet1!C[-15]:C[-14],2,FALSE)"
    Range("P2").Select
Selection.AutoFill Destination:=Range("P2:P" & Cells(Rows.Count, "Z").End(xlUp).Row)
    Range("Q2").Select
    ActiveCell.FormulaR1C1 = "=VLOOKUP(RC[9],Sheet1!C[-16]:C[-14],3,FALSE)"
    Range("Q2").Select
Selection.AutoFill Destination:=Range("Q2:Q" & Cells(Rows.Count, "Z").End(xlUp).Row)
    Range("R2").Select
    ActiveCell.FormulaR1C1 = "=VLOOKUP(RC[8],Sheet1!C[-17]:C[-14],4,FALSE)"
    Range("R2").Select
Selection.AutoFill Destination:=Range("R2:R" & Cells(Rows.Count, "Z").End(xlUp).Row)

End Sub

有办法吗?到目前为止它只在活动表上运行,这使得一切都搞砸了。

我想要的只是重新排序第2页上的内容,所以当我在第1页上进行V查找时,它们的顺序正确!

请帮助,谢谢!

2 个答案:

答案 0 :(得分:1)

  

到目前为止它只在活动表上运行,这使得一切都搞乱了。

啊哈,你发现使用.Activate.Select的一个陷阱。 Here's a good SO帖子概述了如何避免使用.Select

除了您的问题,如何在两张不同的纸张上运行两个代码?这不是太难 - 只需创建两个Worksheet变量,并使用With语句。

例如,这是一个代码,在Sheet1,单元格A1中放置“A”,在Sheet2中放置“A”,单元格A2:

Sub test()
Dim ws1 As Worksheet, ws2 As Worksheet

'Let's define our variables.  For worksheets, like Ranges, you need to use 'Set'
Set ws1 = Sheets("Sheet1")
Set ws2 = Sheets("Sheet2")

 'Now, we want to work with each specific worksheet. Let's choose one at a time.
With ws1
    .Cells(1, 1).Value = "A"
    ' Do other code here, to happen on ws1.  Note the use of the '.' before '.Cells', this tells excel to use
    ' ws1.cells(1,1) ...
End With

With ws2
    .Cells(2, 1).Value = "A"
    'Do other stuff here for worksheet2
End With

End Sub

对于您的代码的“快速而肮脏”修复,就在您要在Sheet2上使用的行之前,输入行Sheets("Sheet2").Activate

修改:关于使用ws1ws2

的更多说明
With ws1
 .cells(1,1).Value = "A"
End with

ws1.cells(1,1).Value = "A"相同的。您使用With因为您可以将所有代码放在那里,即使用Worksheet1运行。在您的代码中,如果您创建了ws1ws2变量,并将这些变量设置为正确的工作表,则只需将ws1.放在要在该工作表中选择的所有范围之前,和ws2.第二个工作表。这有意义吗?

如果要在工作表1中选择范围“A1:B10”,然后删除范围,则可以

With ws1
 .Range("A1:B10").Delete
End with
' is same as ws1.range("A1:B10").Delete

With ws1
 .Range(.Cells(1,1),.Cells(10,2)).Delete
End with
' is same as ws1.Range(ws1.Cells(1,1),ws1.CElls(10,2)).Delete

注意.之前的Cells。这是因为您希望此范围引用sheet1的范围,而不是任何其他工作表。如果在宏期间另一个工作表变为活动状态,则忽略.可能会导致问题。

EDIT2:

完成上述所有操作后,我编辑了您的OP代码以避免使用.Select。你应该能够研究这个并思考,看看我做了什么:

Sub test()
Dim ws1 As Worksheet, ws2 As Worksheet
Set ws1 = Sheets("Sheet1")
Set ws2 = Sheets("Sheet2")

''' RUN THE BELOW ON SHEET 2
Dim arrColOrder As Variant, ndx As Integer
Dim Found As Range, counter As Integer

'Place the column headers in the end result order you want.
arrColOrder = Array("*Item1*", "*Item2*", "*Item3*", "*Item4*")

counter = 1

Application.ScreenUpdating = False

For ndx = LBound(arrColOrder) To UBound(arrColOrder)

    Set Found = ws2.Rows("1:1").Find(arrColOrder(ndx), LookIn:=xlValues, LookAt:=xlWhole, _
                      SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:=False)

    If Not Found Is Nothing Then
        If Found.Column <> counter Then
            Found.EntireColumn.Cut
            ws2.Columns(counter).Insert Shift:=xlToRight
            Application.CutCopyMode = False
        End If
        counter = counter + 1
    End If
Next ndx

Application.ScreenUpdating = True

''' RUN THE BELOW ON SHEET1
With ws1
    .Columns("P:P").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
    .Range("P1").FormulaR1C1 = "Item4"
    .Columns("P:P").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
    .Range("P1").FormulaR1C1 = "Item3"
    .Columns("P:P").Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
    .Range("P1").FormulaR1C1 = "Item2"
   ' .Range("P1:R1").Select 'Don't need this, since you don't do anything with it.
    With .Range("R1").Interior
        .Pattern = xlSolid
        .PatternColorIndex = xlAutomatic
        .Color = 15773696
        .TintAndShade = 0
        .PatternTintAndShade = 0
    End With
    .Range("P2").FormulaR1C1 = "=VLOOKUP(RC[10],Sheet1!C[-15]:C[-14],2,FALSE)"
    .Range("P2").AutoFill Destination:=Range("P2:P" & Cells(Rows.Count, "Z").End(xlUp).Row)
    .Range("Q2").FormulaR1C1 = "=VLOOKUP(RC[9],Sheet1!C[-16]:C[-14],3,FALSE)"
    .Range("Q2").AutoFill Destination:=Range("Q2:Q" & Cells(Rows.Count, "Z").End(xlUp).Row)
    .Range("R2").FormulaR1C1 = "=VLOOKUP(RC[8],Sheet1!C[-17]:C[-14],4,FALSE)"
    .Range("R2").AutoFill Destination:=Range("R2:R" & Cells(Rows.Count, "Z").End(xlUp).Row)
End Sub

答案 1 :(得分:0)

创建一个excel工作表对象。你可以对它进行排序。

Dim ws As Excel.Worksheet
Set ws = Worksheets("Sheet2")

'Then you do a sort on ws.Range("A:A").Sort