我想从一个工作簿复制/粘贴一些列(总是相同的)到另一个。我不能让我的代码在工作簿之间执行此操作。 还有一件小事我希望将值粘贴到目标表的第4行,而我自己可以做的就是将其粘贴到第二行:/
类似这样的代码但是这个代码只能在同一个xls文件中粘贴从一个工作表到另一个工作表的值:
编辑:我尝试在xls文件之间复制/粘贴的代码。我做错了什么,因为它不起作用。background-image: url('/assets/images/lo/example2.svg');
答案 0 :(得分:0)
使用有意义的变量名称 - 尤其是在您学习时:
Sub Example()
Dim wbSource As Workbook
Dim wbDestination As Workbook
Dim wsSource As Worksheet
Dim wsDestination As Worksheet
Dim rSource As Range
Dim rDestination As Range
Set wbSource = Workbooks("Pres.xls")
Set wsSource = wbSource.Worksheets("Paste_tab")
Set wbDestination = Workbooks("Bench.xlsm")
Set wsDestination = wbDestination.Worksheets("Test-Sheet")
Set rSource = wsSource.Range("b2:b" & wsSource.Range("b" & wsSource.Rows.Count).End(xlUp).Row)
For Each rDestination In wsDestination.Range("B4:W4")
If InStr("BCDEHIMOQSVW", Left(rDestination.AddressLocal(False, False), 1)) > 0 Then
' rSource.Copy rDestination
'=============if only values wanted ===========
rsource.copy
rdestination.pastespecial xlpastevalues
'==================
End If
Next rDestination
End Sub
答案 1 :(得分:0)
最后,我做了类似的事情并且工作正常。感谢@Harassed Dad - 我已经使用了一些代码。我认为它可能更普遍,但对我来说现在还可以。
Sub PasteToTemplate()
Dim xD As Workbook
Dim xS As Workbook
Dim wsSource As Worksheet
Dim x As Worksheet
Dim tempN As Worksheet
Dim tN As String
Dim sN As String
With Sheets("Source_sample_size")
sN = .Range("PresName").Value
End With
Set xS = Workbooks(sN)
Set wsSource = xS.Worksheets("Paste_tab")
Set tempN = xS.Worksheets("Source_sample_size")
With tempN
tN = .Range("tempName").Value
End With
Set xD = Workbooks.Open(tN)
Set x = xD.Worksheets("Test-Sheet")
wsSource.Range("A2:F" & wsSource.Range("A" & wsSource.Rows.Count).End(xlUp).Row).Copy
x.Range("B4").PasteSpecial (xlPasteValues)
wsSource.Range("H2:I" & wsSource.Range("A" & wsSource.Rows.Count).End(xlUp).Row).Copy
x.Range("H4").PasteSpecial (xlPasteValues)
wsSource.Range("J2:J" & wsSource.Range("A" & wsSource.Rows.Count).End(xlUp).Row).Copy
x.Range("M4").PasteSpecial (xlPasteValues)
wsSource.Range("K2:K" & wsSource.Range("A" & wsSource.Rows.Count).End(xlUp).Row).Copy
x.Range("O4").PasteSpecial (xlPasteValues)
wsSource.Range("L2:L" & wsSource.Range("A" & wsSource.Rows.Count).End(xlUp).Row).Copy
x.Range("AI4").PasteSpecial (xlPasteValues)
wsSource.Range("M2:M" & wsSource.Range("A" & wsSource.Rows.Count).End(xlUp).Row).Copy
x.Range("AK4").PasteSpecial (xlPasteValues)
wsSource.Range("P2:P" & wsSource.Range("A" & wsSource.Rows.Count).End(xlUp).Row).Copy
x.Range("AM4").PasteSpecial (xlPasteValues)
End Sub