很難讓你達到你想要的目標,因爲我有點不清楚那是什麼,但是下面的代碼可以作爲你的代碼的輔助和可能的解決方案。
首先,我會建議你總是打開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