Excel VBA从A1处的图纸1中选择标题到表格末尾,并将其粘贴到其他图纸
这是Excel VBA从A1处的图纸1中选择标题到表格末尾,并将其粘贴到其他图纸,excel,vba,Excel,Vba,这是Sheet1,我已将其重命名为s1 然后,我创建了两张新的工作表,分别命名为s2和s3。它起作用了 Sub test() ' 1. Create 2 new sheets, name it as "s2" and "s3" Sheets.Add After:=ActiveSheet Sheets("Sheet1").Name = "s2" Sheets.Add After:
Sheet1
,我已将其重命名为s1
然后,我创建了两张新的工作表,分别命名为s2
和s3
。它起作用了
Sub test()
' 1. Create 2 new sheets, name it as "s2" and "s3"
Sheets.Add After:=ActiveSheet
Sheets("Sheet1").Name = "s2"
Sheets.Add After:=ActiveSheet
Sheets("Sheet2").Name = "s3"
下一步是从s1
复制A1:C1
,并将其粘贴到s2
和s3
的A1:C1
' 2. Attempt to copy and paste doesn't work yet
Range(Range("A1"), Range("A1").End(xlToRight)).Copy
Sheets("s2").Paste
Sheets("s3").Paste
End Sub
不幸的是,它不起作用。与其从s1
粘贴A1:C1
的内容,它只是从A1
中选择,直到页面s2
和s3
的末尾
s2
和s3
试试这个:
Sub test()
'Declarations.
Dim WksOldSheet As Worksheet
Dim WksNewSheet As Worksheet
Dim BytCounter As Byte
'Setting WksOldSheet as the active sheet. This way we can refer to it _
even if another sheet is activated.
Set WksOldSheet = ActiveSheet
'Since we have to basically do the same thing twice, we start a For-Next _
cycle. Note that it will start with BytCounter equal to 2 and will end with _
BytCounter equal to 3. Therefore it will be repeated 2 times.
For BytCounter = 2 To 3
'While creating a new sheet, we set it as WksNewSheet. This way we can _
easily refer to it.
Set WksNewSheet = Sheets.Add(After:=ActiveSheet)
'Setting the name of WksNewSheet. We use an hardcoded s and BytCounter.
WksNewSheet.Name = "s" & BytCounter
'With a With statement we can avoid repeating WksOldsheet.
With WksOldSheet
'Copying the header in the new sheet.
.Range(.Range("A1"), .Range("A1").End(xlToRight)).Copy WksNewSheet.Range("A1")
'If we were not to use the With statement, the previous line would have looked like this:
'WksOldSheet.Range(WksOldSheet.Range("A1"), WksOldSheet.Range("A1").End(xlToRight)).Copy WksNewSheet.Range("A1")
End With
Next
End Sub
您需要在
范围(范围(“A1”)、范围(“A1”).End(xlToRight))中指定工作表。复制。您正在隐式地使用ActiveSheet
,它不是s1
@BigBenSheets(“s1”).Range(Range(“A1”)、Range(“A1”).End(xlToRight)).Copy
?必须限定Range
的每个实例,包括内部实例。一个With
语句在这里可能很有用:With Sheets(“s1”)
,.Range(.Range(“A1”),…
。谢谢@Evil Blue Monkey,它可以工作。我注意到您使用的是WksNewSheet.Name=“s”&BytCounter
因为工作表名称是s2
和s3
。如果工作表名称是随机的,假设是Task 123
和Group X
,而不是s2
和s3
,如果它们是“随机的”,您可能需要对它们进行硬编码,或者至少从源代码中选取它们。它可能是通过代码创建的范围或变量,也可能是通过输入框创建的变量。谢谢您的帮助。请您看看这个?