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

时间:2016-05-04 06:21:53

标签: excel vba excel-vba ms-office

我想制作一张具有不同宏按钮的工作表此工作表名为按钮。此工作表中的宏按钮链接到应在不同工作表上运行的宏。我试图为表格 1制作一个宏按钮。股票&需求

Sub NeuerTag()

'Abfrage ob der Tag eingefügt werden soll, No = QUIT'
If MsgBox("Möchtest du die Tabelle vorbereiten?", vbYesNo) = vbNo Then Exit Sub

'Copies the last three coloumns of the Worksheet 1. Stock & Demand'
With Sheets("1. Stock & Demand")
Lastcol = .Cells(1, Columns.Count).End(xlToLeft).Column
Columns(Lastcol - 1).Resize(, 1).Select
Selection.Copy

'Selects the first empty cell in 1. Stock & Demand and pastes'
Sheets("1. Stock & Demand").Range("F3:ZZ3").End(xlToRight).Offset(-2, 1).Paste

'Pastes the Today()'
Sheets("1. Stock & Demand").Range("F3:ZZ3").End(xlToRight).Offset(-1, 0).Select
Selection.Value = Date

'Paste Special - Values'
With Sheets("1. Stock & Demand")
Lastcol = .Cells(1, Columns.Count).End(xlToLeft).Column
Columns(Lastcol - 3).Resize(, 1).PasteSpecial Paste:=xlPasteValues

End With
End With

End Sub

现在我遇到了问题。每当我创建一个宏按钮并让它运行时,它只会在工作表按钮中完成,而不是在我希望它工作的工作表中。

我不得不说我不擅长编码,所以请像我五岁那样向我解释一下; - )。

2 个答案:

答案 0 :(得分:1)

您必须为宏指定工作表名称。例如,你可以试试这个:

 Workbooks("Your_worksheet_name_here").Sheets("1. Stock & Demand").Range("F3:ZZ3").End(xlToRight).Offset(-2, 1).Paste

通常情况下,为了保持清醒,我会做这样的事情:

 Set targetSheet = Workbooks("Your_worksheet_name_here").Sheets("1. Stock & Demand")
 targetSheet.Range("F3:ZZ3").End(xlToRight).Offset(-2, 1).Paste

答案 1 :(得分:1)

小事 - 在你的With陈述中,你是错误编码的。注意“。”。通过错放/省略它,您将在错误的选项卡中得到结果。

例如

With Sheets("1. Stock & Demand")
    Lastcol = .Cells(1, Columns.Count).End(xlToLeft).Column
    Columns(Lastcol - 3).Resize(, 1).PasteSpecial Paste:=xlPasteValues
End With

应该是

With Sheets("1. Stock & Demand")
    Lastcol = .Cells(1, .Columns.Count).End(xlToLeft).Column
    .Columns(Lastcol - 3).Resize(, 1).PasteSpecial Paste:=xlPasteValues
End With

这......

With Sheets("1. Stock & Demand")
    Lastcol = .Cells(1, Columns.Count).End(xlToLeft).Column
    Columns(Lastcol - 1).Resize(, 1).Select
    Selection.Copy

'Selects the first empty cell in 1. Stock & Demand and pastes'
    Sheets("1. Stock & Demand").Range("F3:ZZ3").End(xlToRight).Offset(-2, 1).Paste

'Pastes the Today()'
    Sheets("1. Stock & Demand").Range("F3:ZZ3").End(xlToRight).Offset(-1, 0).Select
    Selection.Value = Date

应该是......

With Sheets("1. Stock & Demand")
    Lastcol = .Cells(1, .Columns.Count).End(xlToLeft).Column
    .Columns(Lastcol - 1).Resize(, 1).Copy

'Selects the first empty cell in 1. Stock & Demand and pastes'
    .Range("F3:ZZ3").End(xlToRight).Offset(-2, 1).Paste

'Pastes the Today()'
    .Range("F3:ZZ3").End(xlToRight).Offset(-1, 0).Value = Date
相关问题