很难让你达到你想要的目标,因为我有点不清楚那是什么,但是下面的代码可以作为你的代码的辅助和可能的解决方案。
首先,我会建议你总是打开Option Explicit
特别是如果呼吁Stack Overflow寻求帮助。
Option Explicit
强制你声明所有的变量,在这种情况下,它会帮助你,因为你cell
作为一个变量,可能会出现模糊。当它未被声明时,它作为一个变体开始它的生命,并且在第一次使用时被定义为特定格式,在这种情况下,编译器将cell
声明为Range
。
它还有助于鼓励更好的编码,并更好地理解代码中发生了什么。要打开它,请在代码窗格的最顶部键入Option Explicit
(在任何过程或变量声明之前),同时在VBE(Visual Basic编辑器)中单击'工具'>'选项'并确保'需要变量声明'为勾选。
下面是您拥有的代码中的一些注释,它们应该有助于您理解所面临的问题。
Dim rng As Range
Dim PTRange As Range
Dim count As Long
count = 1
'If the range is nothing then it can not be used, it must be started as
'something
Set PTRange = Nothing
Set rng = Range("E2:E20")
'This is where declaring 'cell' would help understanding, it will become a
'Range at the VBE discretion\decision based on what you are trying to do
'with it. Even when looking at a single cell, you do so through a Range,
'it is a reference to one or more cells in a worksheet
For Each cell In rng '
If cell.Value = ("Desired Value") Then
'This will not work for a number of reasons
'O- As BrakNicku stated, there needs to be 'Set' at the front
'O- This is not remembering the values into the 'PTRange' but
' adding a reference to where those values are. I.e. You are
' not taking note of everybody in the house, but just remembering
' their house address
'O- You do not need to put 'Range()' around 'PTRange' as it is
' already a range
'O- 'Rows(count)' is not valid syntax and does not pass a range into
' the union
'O- 'Union' will put together 2 or more references to ranges, it
' will not put their values in any specific place on a worksheet
PTRange = Application.Union(Range(PTRange), Range(Rows(count)))
End If
count = count + 1
Next cell
希望以上已经知识性和下面是一个例子,一个潜在的解决方案: - 显式的选项
Public Sub Sample()
Dim LngRow As Long
Dim Rng As Excel.Range
Dim Rng_Cl As Excel.Range
Dim Rng_PT As Excel.Range
LngRow = 21
'Initialise my Range
Set Rng_PT = Range("E21") '" & LngRow)
'Get the search range
Set Rng = Range("E2:E20")
'Loop through all the cells
For Each Rng_Cl In Rng
If Rng_Cl.Value = ("Duck") Then
'Adds just 5 column and not the whole row
Range(Rng_Cl.Address, ActiveSheet.Cells(Rng_Cl.Row, Rng_Cl.Column + 5).Address).Copy Range("E" & LngRow)
LngRow = LngRow + 1
End If
Next
'It is good practice to remove references once you are done with them
'This can help with memory consumption/speed and also more serious
'memory leaks (and actual stack overflows!) on larger macros
Set Rng = Nothing
Set Rng_PT = Nothing
End Sub
它显示什么样的错误?尝试用联盟(PTRange)替换联盟(范围(PTRange)(PTRange),... –
范围(PTRange)如果这只是PTRange,联盟(rng1,rng2 ....其中rng1&2是范围,PTrange也不会存在于1号通过,所以你必须在第一次设置PTRange = ..... –
'Then'后面缺少'Set' – BrakNicku