2015-11-06 253 views
0

多個單元格引用單元格R1以間接查找其他四個表格之一。這些工作表被命名爲week1,week2,week3和week4。 我正在尋找的是當我點擊按鈕X時,我的參考單元從第1周變爲第2周。每次點擊它應該提前到第4週迴到第1周的程度。excel vba單元格值循環步驟

我目前的斷碼讀取:

'Change the week number in cell R1 
week = Range("R1") 
If week = week1 Then 
    Range("R1").Value = week2 
Else 
    If week = week2 Then 
     Range("R1").Value = week3 
    Else 
     If week = week3 Then 
      Range("R1").Value = week4 
     Else 
      If week = week4 Then 
       Range("R1").Value = week1 
      End If 
     End If 
    End If 
End If 
Application.ScreenUpdating = True 'Turns viewing function back on so the spreadsheet is usable. 
End Sub 
+0

輸入錯誤我前僱主代碼Dim week1作爲Sting week1 =「week1」等等 – GeoHoward

+0

你的代碼很好,只要用引號括起'week1'等。 '「week1」'),但是對於更高效的代碼,請參閱Jeeped簡短回答。 – EEM

回答

0
Select Case week 
    Case Is = week1: vValue = week2 
    Case Is = week2: vValue = week3 
    Case Is = week3: vValue = week4 
    Case Is = week4: vValue = week1 
End Select 

Range("R1").Value = vValue 
Application.ScreenUpdating = True 
+1

解釋是好答案和次優答案之間的區別... –

0

你應該能夠做到這一點在一個單一的代碼行。

Range("R1") = Format(InStr(1, "4123", Right(Range("R1").Value, 1)), "\W\e\ek0") 

通過Week1,Week2,譯員更加,Week4,Week1,...這將循環。我省略了R1的父級工作表引用,但包含它的絕不是一個壞主意。

+1

您是否測試了此...某種程度上它不適合我;它返回'Xeek0',其中X是數字1到4.建議將其更改爲:'Range(「R1」)=「week」&InStr(1,「4123」,Right(Range(「R1」)。 ,1))或 'Range(「R1」)=「week」&Choose(Right(Range(「R1」)。Value,1),2,3,4,1)' – EEM

+0

是的,我測試了在Worksheet_BeforeDoubleClick中,所以我可以在R1上雙擊並觀察週期。也許R1必須在1到4之間的數字中「接種」,然後才能開始......? – Jeeped

+1

嘗試使用'1'和任何期望值(即'week1'等)進行種子播種並仍然返回'Xeek0'它將數字格式化爲'W' ... – EEM

0

有一個簡單的方法來解決這個問題:

Range("R1") = Left(Range("R1"), 4) & Right(Range("R1"), 1) Mod 4 + 1 
'number after Mod = max week 

Mod x只是將計爲0,如果是在其最大(在+ 1套它,然後以1再次) 但是,你可以使用這個子,以避免奇怪的行爲:

Sub NewWeekMax() 
    Dim str As String, i As Byte 
    str = "Week1" 
    For i = 2 To 4 'last num = max weeks 
    str = str & ",week" & i 
    Next 
    With Range("R4").Validation 
    .Delete 
    .Add 3, 1, 1, str 
    .InCellDropdown = True 
    .ShowInput = True 
    .ShowError = True 
    End With 
End Sub 

此子簡單地設置一個數據驗證,以禁用R1