使用VBA在不同的工作表上运行宏

时间:2014-06-05 15:17:36

标签: excel vba excel-vba

我无法尝试运行宏,我在“按钮”表单上的“当前”表单上录制了这个宏。这是2个单独的工作表,我想在“按钮”工作表上运行宏。这是我到目前为止的代码:

Sub FormatCurrentSheet()

Range(Selection, Selection.End(xlToRight)).Select
Selection.Font.Bold = True
Range("A1").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
ActiveWindow.SmallScroll Down:=6
With Selection.Font
    .Name = "Calibri"
    .Size = 9
    .Strikethrough = False
    .Superscript = False
    .Subscript = False
    .OutlineFont = False
    .Shadow = False
    .Underline = xlUnderlineStyleNone
    .ThemeColor = xlThemeColorLight1
    .TintAndShade = 0
    .ThemeFont = xlThemeFontMinor
End With
Range("A1").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Rows.AutoFit
Range("A1").Select
Range(Selection, Selection.End(xlToRight)).Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Columns.AutoFit
Columns("H:H").Select
Selection.AutoFilter
ActiveWorkbook.Worksheets("Current").AutoFilter.Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Current").AutoFilter.Sort.SortFields.Add Key:= _
    Range("H1:H800"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption _
    :=xlSortNormal
With ActiveWorkbook.Worksheets("Current").AutoFilter.Sort
    .Header = xlYes
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With
End Sub

当我单击分配了此宏的按钮时,如何更改此设置以使其在“按钮”表上工作。我有一种感觉,我可能不得不使用ActiveSheet。感谢您的帮助,随时提出问题。

2 个答案:

答案 0 :(得分:3)

您需要在使用Range时指定工作表:

Worksheets("SheetName").Range("A1").Select

更优雅的解决方案是使用With,您可以这样使用:

With Worksheets("SheetName")
    .Range("A1").Select
    .Range("A2").Select
End With

答案 1 :(得分:-1)

你可以通过说明表(“按钮”)来开始你的命令。选择

稍后在您的代码中,它表示您正在使用工作表“current”。 将“当前”更改为“按钮”,它应该可以正常工作!

相关问题