您不能.Copy
在非连续范围上使用该方法。
然而,大多数时候人们想要“复制”一些东西,他们真正关心的是传输值,这可以在没有复制/粘贴过程的情况下完成(如果您还需要复制格式/等,这可以类似地完成以下)。
把这个放到Workbook代码模块中,不是普通的代码模块,必须放到Workbook代码模块中。TransferValues
每次您Save
对工作簿执行操作时,这都会调用一个子例程。
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
Application.Run "TransferValues"
End Sub
把它放在普通的代码模块中。
修改
由于范围不连续,我不得不进行一些更改,我们需要遍历范围.Areas
,然后遍历每个单元格中的各个单元格。
Private Sub TransferValues()
Dim wsMain As Worksheet: Set wsMain = Sheets("Main Form")
Dim wsData As Worksheet: Set wsData = Sheets("Database")
Dim rngToCopy As Range: Set rngToCopy = wsMain.Range("e3:e7,h3:h7,k3:k7,i12:i16,i18:i21,i23")
Dim c As Long
Dim ar As Range
Dim cl As Range
Dim lastRow As Long
Dim rngDestination As Range
'Get the last row in Database sheet:
lastRow = Application.WorksheetFunction.CountA(wsData.Range("A:A"))
Set rngDestination = wsData.Cells(lastRow + 1, 1).Resize(1, 25).Offset(1, 0)
For Each ar In rngToCopy.Areas
For Each cl In ar
c = c + 1
'I used this next line for testing:
' rngDestination.Cells(c).Value = cl.Address
rngDestination.Cells(c).Value = cl.Value
Next
Next
End Sub