避免使用选择和选择。复制它会带来很多麻烦,只需在开始使用范围进行操作之前声明所有内容,并使用Range Class方法复制/粘贴到先前声明的另一个工作表,不需要像“人物”那样移动“表单”来复制和粘贴。让我们开始考虑作为电脑,他已经记得他需要处理的一切,所以使用它!
我建议你在开始在VBA中编写代码之前声明每个对象,这样你就可以获得该对象的属性和方法(使用intellisense,只需在对象名称和VBA之后做一点就可以显示出你需要的所有东西),例如。 Range对象具有一个“COPY”方法,其中有一个DESTINATION参数也可以用来将范围从一个点移动到另一个点。
这里是你的情况的例子:
Option Explicit
Sub test2()
'SPECIFY OPTION EXPLICIT TO DON'T MISS ANY DECLARATION
Dim ws_Master As Worksheet 'Master Worksheet
Dim rng As Range 'range to iterate
Dim cell As Range 'cell for iteration
Dim ws_1xDaily As Worksheet 'Worksheet for daily data
Dim ws_1xMonthly As Worksheet 'Worksheet for monthly data
Dim i As Integer, j As Integer 'Integer for parsing
'END DECLARATION
'Sheets and range object creation
Set ws_Master = ThisWorkbook.Sheets("Master Vitals Data")
Set rng = ws_Master.Range("D1:D" & ws_Master.Range("D" & Rows.Count).End(xlUp).Row) 'This will get the last row of the Range D:D so we can iterate until last row
Set ws_1xDaily = ThisWorkbook.Sheets("1x Daily All")
Set ws_1xMonthly = ThisWorkbook.Sheets("1x Monthly All")
'End
'That's all you have to do now is just copy a range to another range, just few line of code in a for each loop:
i = 1 'to remember the last row we used in the daily sheet
j = 1 'same as before but for the monthly sheet
For Each cell In rng
If cell.Value = "1x Daily AM" Then cell.EntireRow.Copy Destination:=ws_1xDaily.Range("A" & i): i = i + 1
If cell.Value = "1x Monthly" Then cell.EntireRow.Copy Destination:=ws_1xMonthly.Range("A" & j): j = j + 1
Next cell
'End
End Sub
如果你不会更有效率,你可以使用Range对象的.Find方法找到每一个细胞都包含您正在搜索什么,在“D:D”范围,没有指定最后一行,也没有迭代空单元格,请查看该方法!
这是日常活动,与.Find方法的例子:
Sub test2()
'SPECIFY OPTION EXPLICIT TO DON'T MISS ANY DECLARATION
Dim ws_Master As Worksheet 'Master Worksheet
Dim rng As Range 'range to iterate
Dim cell As Range 'cell for iteration
Dim ws_1xDaily As Worksheet 'Worksheet for daily data
Dim ws_1xMonthly As Worksheet 'Worksheet for monthly data
Dim firstAddress As String
Dim toCopyRng As Range
'END DECLARATION
'Sheets and range object creation
Set ws_Master = ThisWorkbook.Sheets("Master Vitals Data")
Set rng = ws_Master.Range("D:D")
Set ws_1xDaily = ThisWorkbook.Sheets("1x Daily All")
Set ws_1xMonthly = ThisWorkbook.Sheets("1x Monthly All")
i = 1 'to remember the last row we used in the daily sheet
Set toCopyRng = rng.Find("1x Daily AM", LookIn:=xlValues)
If Not toCopyRng Is Nothing Then
firstAddress = toCopyRng.Address
Do
toCopyRng.EntireRow.Copy Destination:=ws_1xDaily.Range("A" & i): i = i + 1 'copy and increment row of the daily sheet
Set toCopyRng = rng.FindNext(toCopyRng)
Loop While Not toCopyRng Is Nothing And toCopyRng.Address <> firstAddress
End If
End Sub
您使用此代码时遇到了哪些问题? – dotNET
请包括您收到的错误消息。 – z32a7ul