选择另一个工作表VBA后,变量出错了

时间:2016-05-13 12:43:22

标签: excel vba excel-vba excel-2010

以下是我一直在处理的代码。但是,当我从同一工作簿中选择另一个工作表时,我意识到出了问题。

变量ShiftName在通过以下代码中的Sheets("Cash").Select时似乎会发生变化。

我认为ShiftName的列已从" B"工作表" ShiftRoster"到" C" "现金"这导致ShiftName的输出错误。

我想检查是否有办法解决这个问题?

Sub Testing()
    Sheets("Shift Roster").Select

    Range("A1").Select
    Cells.Find("LEAVE").Activate
    r1 = ActiveCell.Row

    Dim ShiftRowName As Integer
    Dim ShiftColName As String: ShiftColName = "B"
    Dim ShiftColLeave As String: ShiftColLeave = "E"
    Dim ShiftName As String
    Dim ShiftReason As String

    Dim CashRowName As Integer
    Dim CashColName As String: CashColName = "C"
    Dim CashColLeave As String: CashColLeave = "H"
    Dim CashName As String
    Dim CashLeave As String

    ShiftRowName = r1 + 1

    Do While Cells(ShiftRowName, 1) <> ""
        ShiftName = Cells(ShiftRowName, ShiftColName)
        ShiftReason = Cells(ShiftRowName, ShiftColLeave)

        If ShiftName = "" Or IsEmpty(ShiftName) Then
            Exit Do
        Else
            'SOMETHING WENT WRONG FROM HERE ONWARDS
            Sheets("Cash").Select

            Range("C1").Select
            Cells.Find("Name").Activate
            r2 = ActiveCell.Row

            CashRowName = r2 + 1

            Do While Cells(CashRowName, 1) <> ""
                CashName = Cells(CashRowName, CashColName).Value

                If CashName = "" Or IsEmpty(CashName) Then
                    Exit Do
                Else
                    MsgBox ShiftName
                    End If
                CashRowName = CashRowName + 1
            Loop

            End If
        ShiftRowName = ShiftRowName + 1
    Loop

End Sub

1 个答案:

答案 0 :(得分:4)

限定您的范围/单元格方法:

而不是

ShiftReason = Cells(ShiftRowName, ShiftColLeave)

使用

ShiftReason = Sheets("Shift Roster").Cells(ShiftRowName, ShiftColLeave)

所以你的代码知道完全你指的是哪张表。如果不对您的范围进行限定,则会假定您指的是ActiveSheet对象。