Sub Hinnan_korotus_välilehti_makro()
Dim tulostusrivi As Integer
Dim lukurivi As Integer
Dim lukurivi_tausta As Integer
Dim uusihinta As Double
Sheets("Nimikkeitä").Select
For lukurivi = 75 To 400
If Range("F" & lukurivi) = "Hawle" Then
nimike = Range("A" & lukurivi)
Sheets("Taul1").Select
For tulostusrivi = 2 To 400
If Range("A" & tulostusrivi) = nimike Then
uusihinta = Range("F" & tulostusrivi)
Sheets("Nimikkeitä").Select
Range("E" & lukurivi) = uusihinta
End If
Next tulostusrivi
End If
Next lukurivi
End Sub
嗨,我对“ for”和“ next”功能有疑问。.最后几行宏将“ uusihinta”放置在“ E”和lukurivi范围内。我想在“如果结束”之后返回到“ lukurivi”和下一行,即76。但是它一直循环播放“ tulostusrivi”,并且从不转到“ Next lukurivi”。 谢谢!
答案 0 :(得分:0)
IAmNerd2000和Eleshar的注释中已经给出了简短的答案:您缺少Exit For
行。下面是代码的优化,注释过多的版本,您可能会觉得很有启发。
HinnanKorotusVälilehti
,HinKorVäl
或
HKV
而不是Hinnan_korotus_välilehti。和较短的标题是
首选(标题中确实不需要Makro
。Option Explicit
来查找变量
未声明(nimike
)。lukuRivi
或tulostusRivi
。lukurivi_tausta
)。A = B: C = A
,而是C = B
(uusihinta
。Select
或Activate
,因为它们会变慢
记下您的代码。ws
)来利用Intellisense。With
语句划分不同对象的代码(此处不做演示)。400
)将
总是必须改变。因此最好计算一下
每次使用End
属性或Find
方法。Option Explicit
Sub HinnanKorotusVälilehti()
Dim ws As Worksheet ' Worksheet Variable for worksheet "Taul1"
Dim lukuRivi As Long ' Worksheet "Nimikkeitä" Row Counter
Dim tulostusRivi As Long ' Worksheet "Taul1" Row Counter
Dim nimike As String ' Product Title
' Create a reference to worksheet "Taul1" (Everything starting with
' "ws." is referring to workhsheet "Taul1").
Set ws = ThisWorkbook.Worksheets("Taul1")
' In Worksheet "Nimikkeitä" (Everything starting with a "." is referring
' to worksheet "Nimikkeitä".)
With ThisWorkbook.Worksheets("Nimikkeitä")
' Loop through rows of worksheet "Nimikkeitä".
For lukuRivi = 75 To 400
' Check if the cell at the intersection of the current row
' and column "F" contains "Hawle".
If .Range("F" & lukuRivi) = "Hawle" Then ' IS "Hawle"
' Assign the value of the cell at the intersection of the
' current row and column "A" to variable "nimike".
nimike = .Range("A" & lukuRivi)
' (In Worksheet Taul1) Loop through rows of Worksheet Taul1.
For tulostusRivi = 2 To 400
' Check if the cell at the intersection of the current row
' and column "A" contains (the value of) "nimike".
If ws.Range("A" & tulostusRivi) = nimike Then ' IS "nimike".
' Write the value of the cell at the intersection of
' the current row (tulostusRivi) and the "F" column
' in worksheet "Taul1" to the cell at the intersection
' of the current row (lukuRivi) and the "E" column in
' worksheet "Nimikkeitä".
.Range("E" & lukuRivi) = ws.Range("F" & tulostusRivi)
' Since the value has been found, stop searching and
' go to next row in worksheet "Nimikkeitä".
Exit For
'Else ' NOT "nimike".
End If
Next ' Next row in worksheet "Taul1" (tulostusRivi).
'Else ' NOT "Hawle".
End If
Next ' Next row in worksheet "Nimikkeitä" (lukuRivi).
End With
End Sub