我正在尝试运行一个在多个工作表上执行函数的宏。假设我在工作表4上分配了宏按钮。我已经列出了我希望它逐步执行的功能:
1)选择工作表4中的某些单元格并复制到工作表4中的相邻单元格
2)删除工作表3中的单元格范围。
3)工作表2中的CUT范围的细胞然后将该范围的细胞粘贴到工作表3中
4)从单独的工作簿中获取单元格范围并复制到工作表2中。(我知道这是一个完全不同的问题,因为工作簿会自动发布,我将不得不找到一种方法来链接这两个。)
5)更新位于工作表4和工作表3中的数据透视表。
我很乐意帮助解决这个问题的前3个功能。我已粘贴下面的当前代码。
Sub START()
Dim sh1 As Worksheet
Dim sh2 As Worksheet
Dim sh3 As Worksheet
Dim sh4 As Worksheet
Set sh1 = ActiveWorkbook.Sheets("Brand")
Set sh2 = ActiveWorkbook.Sheets("CurrentWeek")
Set sh3 = ActiveWorkbook.Sheets("PriorWeek")
Set sh4 = ActiveWorkbook.Sheets("Pivot")
sh4.Range("B29:B30").Select
Selection.Copy
sh4.Range("C29").Select
ActiveSheet.Paste
sh3.Range("A4:AC1000").Select
Selection.Delete
sh2.Range("A4:AC1000").Select
Selection.Copy
sh3.Range("A4").Select
ActiveSheet.Paste
End Sub
它有效......但只有当我在正确的工作表中才能执行特定功能时才能正常工作。
答案 0 :(得分:14)
通过删除select
,selection
和activesheet
,您可以将此表格与此无关
Sub START()
Dim sh1 As Worksheet
Dim sh2 As Worksheet
Dim sh3 As Worksheet
Dim sh4 As Worksheet
Set sh1 = ActiveWorkbook.Sheets("Brand")
Set sh2 = ActiveWorkbook.Sheets("CurrentWeek")
Set sh3 = ActiveWorkbook.Sheets("PriorWeek")
Set sh4 = ActiveWorkbook.Sheets("Pivot")
sh4.Range("B29:B30").Copy sh4.Range("C29")
sh3.Range("A4:AC1000").Delete
sh2.Range("A4:AC1000").Copy sh3.Range("A4")
End Sub
答案 1 :(得分:5)
你有一个良好的开端。只需要更多的改进,你就会拥有它。
基本上,至少在这种情况下,不需要.Select
你的范围(工作表,工作簿等)。您可以直接与他们合作,并使用Copy
提供他们将被复制的目的地。
见下面的代码:
Sub START()
Dim sh1 As Worksheet
Dim sh2 As Worksheet
Dim sh3 As Worksheet
Dim sh4 As Worksheet
Dim wkb As Workbook
Set wkb = Workbooks("wkbName") '-> best to call workbooks by name, as opposed to "ActiveWorkbook", also best to set it to object
With wkb '-> now we can work with this object directly and succinctly
Set sh1 = .Sheets("Brand")
Set sh2 = .Sheets("CurrentWeek")
Set sh3 = .Sheets("PriorWeek")
Set sh4 = .Sheets("Pivot")
sh4.Range("B29:B30").Copy sh4.Range("C29")
'sh3.Range("A4:AC1000").Delete -> you don't need this if you are overwritting it
sh2.Range("A4:AC1000").Copy sh3.Range("A4")
End With
End Sub
答案 2 :(得分:0)
张(“name1”)。range(“B29:B30”)。复制目的地:=张(“name2”)。range(“C29”)
假设工作表名称为name1和name2
,将从一个工作表复制到另一个工作表答案 3 :(得分:-2)
Sub START()
Sheet("Pivot").Range("B29:B30").Copy Sheet("Pivot").Range("C29")
Sheet("CurrentWeek").Range("A4:AC1000").Copy Sheet("PriorWeek").Range("A4")
End Sub