Excel VBA For ......Next......

2012-10-30 9:39 pm
Example:

Rows : D E F G
Replace by : 1 1 2 2
Find : BlankblankBlankBlank

我想設兩個for next同時執行並同時改變變數,例如第一個for next去d行到g行,第二個for next,尋找d到g行的所有"blank"並replce by "1 to 2",
for z=1 to 10 step 2
for z1= 1 to 2

Cell(3+z).select
Selection.Replace What:="blank", Replacement:="&z1&",LookAt:=xlPart,_
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Cell(4+z).select
Selection.Replace What:="blank", Replacement:="&z1&",LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False

Next z
Next Z1

有冇方法可以同時改變z,z1的變數,然再重覆執行next迴圈.

唔該晒各位

回答 (3)

2012-11-05 10:40 pm
✔ 最佳答案
其實你既問題, 好易做.
我現在給你2個程式碼
1) 用你的去改
2) 用我的.

1) 用你的去改
for z=1 to 10 step 2
for z1= 1 to 2

Cells(3+z).Select 'Cell(3+z).select 'Cell有(s)

Selection.ENTIRECOLUMN.Replace What:="blank", Replacement:="&z1&",LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
'Selection.Replace What:="blank", Replacement:="&z1&",LookAt:=xlPart,_
'SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
'ReplaceFormat:=False

Cells(4+z).Select 'Cell(4+z).select 'Cell有(s)

Selection.ENTIRECOLUMN.Replace What:="blank", Replacement:="&z1&",LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False

'Selection.Replace What:="blank", Replacement:="&z2&",LookAt:=xlPart, _
'SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
'ReplaceFormat:=False

Next z1 'Next z
Next z 'Next Z1

2) 用我的.
For z = 1 To 10 Step 2
For z1 = 1 To 2
Cells(z + 3 + z1 - 1).Select
Selection.EntireColumn.Replace What:="blank", _
Replacement:="&z" & z1 & "&", _
LookAt:=xlPart, SearchOrder:=xlByRows, _
MatchCase:=False, SearchFormat:=False, _
ReplaceFormat:=False
Next z1
Next z
2012-11-01 1:03 am
唔該晒,
但如果欄係由D開始到AK,一共有62欄,每兩欄為一組尋找BLANK,REPLACE BY Z1的變數,而z1 的變數喺由1 to 31,又可以點寫?

2012-10-31 20:54:10 補充:
是的,
唔好意思比錯資料!

2012-10-31 20:59:19 補充:
全行或者由1到100都得.

2012-10-31 21:25:40 補充:
成功啦,
真的十分感謝你.
唔該晒.
2012-10-31 11:06 pm
z1應不用for next
在next z 內加一段, 大概如下:
If z Mod 2 = 1 then
z1= 1
else
z1 = 2
EndIf

2012-10-31 20:29:04 補充:
D欄至BM欄才是62欄
是否D,E欄replaced by 1, F,G欄replaced by 2.....BL,BM欄replaced by 31

2012-10-31 20:53:40 補充:
要找尋的範圍, 每欄是多少行(row)?

2012-10-31 21:01:28 補充:
For Z = 4 To 65
Columns(Z).Replace What:="blank", Replacement:=Int((Z - 2) / 2)
Next
請測試以上代碼是否可行


收錄日期: 2021-04-16 15:10:53
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20121030000051KK00230

檢視 Wayback Machine 備份