excel vba cell value step loop

时间:2015-11-06 06:48:43

标签: excel excel-vba vba

多个单元格引用单元格R1,以间接查找其他四个工作表中的一个。工作表名为week1,week2,week3和week4。 我要做的是,当我点击按钮X时,我的参考单元从第1周变为第2周。每次我点击它都应该推进到第4周导致第1周的程度。

我目前损坏的代码是:

  '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

3 个答案:

答案 0 :(得分:0)

bind()

答案 1 :(得分:0)

您应该可以在一个代码行中执行此操作。

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

这将循环 Week1,Week2,Week3,Week4,Week1,... 。我省略了R1的父工作表引用,但包含它是绝对不错的。

答案 2 :(得分: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

中的错误输入