用表格复制数据
在这里有2张,Sheet1和Sheet2。 Sheet1包含10列和5行,数据包括空白。
要求是从工作表1中复制数据并放入另一个工作表Sheet 2中,其中只填充非空白的单元格。
我得到运行时错误1004 – 应用程序或对象定义的错误。
代码片段是: –
Set wsht1 = ThisWorkbook.Worksheets("Sheet1") Set wsht2 = Sheets("Sheet2") finalrow = wsht1.Cells(wsht1.Rows.Count, 1).End(xlUp).Row For i = 1 To finalrow If wsht1.Cells(i, 1).Value <> " " Then Range(Cells(i, 2), Cells(i, 2)).Copy Worksheets("Sheet2").Select wsht2.Range(Cells(1, i)).PasteSpecial Paste:=xlPasteFormats End If Next i
你能帮我整理一下吗?
你不能像这样定义一个范围:
wsht2.Range(Cells(1, i))
你可以使用:
wsht2.Cells(1, i).PasteSpecial Paste:=xlPasteFormats
顺便说一句:用这个代码,你不会find空单元格:
If wsht1.Cells(i, 1).Value <> " " Then
你应该使用:
If wsht1.Cells(i, 1).Value <> "" Then
(区别在于引号之间缺less空格)
如果您只想复制这些值并使其成为一个循环,我会执行以下操作:
Sub copying() Set wsht1 = ThisWorkbook.Worksheets("Sheet1") Set wsht2 = Sheets("Sheet2") finalrow = wsht1.Cells(wsht1.Rows.Count, 1).End(xlUp).Row For i = 1 To finalrow If wsht1.Cells(i, 1).Value <> "" Then For j = 1 To 5 wsht2.Cells(i, j).Value = wsht1.Cells(i, j).Value Next j End If Next i End Sub
如果在工作表1中只有5个单元格的数据,并且只希望将这5个工作表复制到工作表2中,请使用以下内容,与上面的Shai的答案类似,对工作表2中的行使用额外的计数器。
Sub copying() Set wsht1 = ThisWorkbook.Worksheets("Sheet1") Set wsht2 = Sheets("Sheet2") finalrow = wsht1.Cells(wsht1.Rows.Count, 1).End(xlUp).Row k = 1 For i = 1 To finalrow If wsht1.Cells(i, 1).Value <> "" Then For j = 1 To 5 wsht2.Cells(k, j).Value = wsht1.Cells(i, j).Value Next j k = k + 1 End If Next i End Sub
编辑
根据你的评论,如果你想dynamic改变j
replaceFor j = 1 To 5
For j = 1 To wsht1.Cells(i, Columns.Count).End(xlToLeft).Column
下面的代码将只复制从Sheet 1到Sheet2列A(非空单元格)中的值:
Dim j As Long Set wsht1 = ThisWorkbook.Worksheets("Sheet1") Set wsht2 = Sheets("Sheet2") finalrow = wsht1.Cells(wsht1.Rows.Count, 1).End(xlUp).Row j = 1 For i = 1 To finalrow With wsht1 ' if you compare to empty string, you need to remove the space inside the quotes If .Cells(i, 1).Value <> "" And .Cells(i, 1).Value <> " " Then .Cells(i, 1).Copy ' since you are copying a single cell, there's no need to use a Range wsht2.Range("A" & j).PasteSpecial Paste:=xlPasteValues, Paste:=xlPasteFormats j = j + 1 End If End With Next i