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

我想创build一个具有不同macrosbutton的工作表这个工作表被命名为button 。 此表中的macrosbutton链接到应在不同的工作表上运行的macros。 我尝试为表单1制作一个macrosbutton。Stock&Demand

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 

现在我有一个问题。 每次我做一个macrosbutton,让它运行它只做他的工作在工作表button,而不是在工作表我希望它的工作。

我不得不说,我不是很擅长编码,所以请给我解释一下,像我五;-)。

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

  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 

一些小事 – 在你的陈述中,你是错误的编码。 注意“。”。 通过错位/省略它,结果将导致错误的选项卡。

例如

 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