我对 VBA 很陌生,并且正在尝试自动化一个工作过程,我需要从 6 个工作表的数组中提取选定的单元格并将它们合并到另一个工作表中。我的代码可以工作,但有点“笨拙”——我正在使用 excel 复制和粘贴功能,但似乎找不到远离复制和粘贴功能的好解决方案。当我尝试添加粘贴特殊功能时,出现 1004 错误。希望有关于优化这个的建议!
对于要复制的每张工作表,单元格在第一列中标记为“1”、“0”或留空 - 如果单元格为“1”或“0”,我将行中的其他单元格复制到合并工作表中. 行之间有一些间隙,所以我选择使用 For-Loop 而不是 Do-While 语句。
我附上代码如下:
Sub TEST()
Dim i As Integer 'copying row counter for each sheet to be copied
Dim j As Integer 'pasting row counter in consolidated sheet
Dim cal(1 To 6) As String 'copied sheetname
cal(1) = "Picks"
cal(2) = "Eats"
cal(3) = "Night Out"
cal(4) = "Active"
cal(5) = "Family"
cal(6) = "Arts"
Dim x As Integer
Dim y As Integer 'column for date
Dim z As Integer 'max row to run till
y = 1 'column checked in each sheet where condition for copying is met
z = 300 'number of rows to check in each sheet
j = 1
For x = 1 To 6
For i = 1 To z
If Sheets(cal(x)).Cells(i, y) = "0" Or Sheets(cal(x)).Cells(i, y) = "1" Then
Sheets(cal(x)).Select
Range(Sheets(cal(x)).Cells(i, 2), Sheets(cal(x)).Cells(i, 10)).Select
Selection.Copy
Application.Goto ActiveWorkbook.Sheets(Consolidated).Cells(j, 1)
ActiveSheet.Paste
Else
j = j - 1
End If
j = j + 1
Next i
Next x
End Sub
同样,我很想优化这段代码,使用另一种方法而不是复制粘贴。我也试过:
Application.Goto ActiveWorkbook.Sheets(Consolidated).Cells(j, 1)
ActiveSheet.PasteSpecial Operation:=xlPasteValues
这导致了 1004 错误。很想知道出了什么问题。