我有一段代码,它会转到一行的末尾,然后添加另一张工作表的指定单元格中的文本。这工作得很好,但现在我想修改它,以复制文本和格式。
我原以为更改If IsEmpty(cell) = True Then cell.Value = Sheets("Text").Range("A2").Copy Destination: Exit For
会起作用,但这给了我一个错误。
我还尝试将我想要复制的单元格设置为一个范围,并引用它,但这也只给了我值,而不是格式。
我还尝试了If IsEmpty(cell) = True Then cell.Value = Sheets("Text").Range("A2").Copy: Exit For
,结果输入为True。
有没有一个简单的方法我应该这样做?
Sub AddText()
Dim ws As Worksheet
Set ws = ActiveSheet
'Set ws = Sheets("Selection")
For Each cell In ws.Columns(1).Cells
If IsEmpty(cell) = True Then cell.Value = Sheets("Text").Range("A2").Value: Exit For
Next cell
End Sub
你混淆了两种不同的东西
a( 指定值
cell.Value = Sheets("Text").Range("A2").value
cell = Sheets("Text").Range("A2") ' Basically the same, you will see this very often
这将把一个单元格的内容(并且只复制内容(复制到另一个单元格。
b( 复制&粘贴
Sheets("Text").Range("A2").Copy cell
Sheets("Text").Range("A2").Copy Destination:=cell ' Synonym
这将把源信元("A2"(的全部信息复制到目的地。它与Excel 中按Ctrl+C和Ctrl+V基本相同
c( 只需完成:您也可以使用PasteSpecial
只复制某些部分(格式、公式、值、数字格式…(。这需要用两行完成:
Sheets("Text").Range("A2").Copy
cell.PasteSpecial xlPasteAll
这方面有很多选择,(请参阅https://learn.microsoft.com/de-de/office/vba/api/excel.range.pastespecial)您知道Excel中PasteSpecial
中的命令。
所以你可能想要的是
For Each cell In ws.Columns(1).Cells
If IsEmpty(cell) Then
Sheets("Text").Range("A2").Copy cell
Exit For
End If
Next cell