我正在编写一段代码,该代码应找到最后使用的行并复制并粘贴最后两行,以便添加“新行”而不删除边框。这是我为此编写的(有效)代码
Dim ExcelApp As New Interop.Excel.Application()
Dim c = ExcelApp.Workbooks.Open("\\xxx.xxx.xxx.xxx\some_files.xlsm")
Dim f = c.Sheets("SomeSheet")
Dim lRow As Integer = f.UsedRange.Rows.Count
f.Range("A" & lRow - 1 & ":BG" & lRow).Copy
f.Range("A" & lRow & ":BG" & lRow + 1).Select
f.Paste
现在您可以看到我使用了Range.Select方法,然后使用.Paste。 问题是,我知道这是一个不好的举动,但我似乎找不到不先选择即可粘贴到特定单元格的方法。
答案 0 :(得分:1)
您为什么需要复制并粘贴它们?这不是以编程方式实际“复制”数据的标准过程。如果您需要将内容放入剪贴板(供用户重复使用),则可以使用.Copy
。但是也许您想避免循环等。
如果您需要复制数据和/或格式,通常会使用如下代码:
ColIndex = 4
ColCount = 5 ' number of columns to copy
For ic = ColIndex To ColIndex + ColCount
' Copy values
ThisWorkbook.Worksheets("List1").Cells(8, ic).Value = ThisWorkbook.Worksheets("List1").Cells(4, ic).Value
' Copy particular properties
ThisWorkbook.Worksheets("List1").Cells(13, ic).NumberFormat = ThisWorkbook.Worksheets("List1").Cells(4, ic).NumberFormat
ThisWorkbook.Worksheets("List1").Cells(14, ic).Font.Bold = ThisWorkbook.Worksheets("List1").Cells(4, ic).Font.Bold
ThisWorkbook.Worksheets("List1").Cells(14, ic).Interior.Color = ThisWorkbook.Worksheets("List1").Cells(4, ic).Interior.Color
ThisWorkbook.Worksheets("List1").Cells(14, ic).Borders.Color = ThisWorkbook.Worksheets("List1").Cells(4, ic).Borders.Color
' Copy all formatting at once (like with Format Painter)
ThisWorkbook.Worksheets("List1").Cells(16, ic).Style = ThisWorkbook.Worksheets("List1").Cells(4, ic).Style
Next
在此示例中,它将值从D4:I4
复制到D8:I8
。
不幸的是,您不能使用以下代码:
ThisWorkbook.Worksheets("List1").Range("D8:I8") = ThisWorkbook.Worksheets("List1").Range("D4:I4") ' WRONG!!
出于好奇和自我教育,我尝试了另一种复制格式的方法,它也可以工作:
Dim CopyRng As Range, PasteRng As Range
Set CopyRng = ThisWorkbook.Worksheets("List1").Range("D4:I4")
Set PasteRng = ThisWorkbook.Worksheets("List1").Range("D28:I28")
CopyRng.Copy
PasteRng.Parent.Activate
PasteRng.PasteSpecial xlPasteFormats
Application.CutCopyMode = False
它确实可以激活,不需要选择单元格。