2016-05-13 48 views
2

以下是我一直在處理的代碼。但是,當我從同一個工作簿中選擇另一個工作表時,我意識到出了問題。選擇其他工作表後變量出錯VBA

變量ShiftName在下面的代碼中通過Sheets("Cash").Select時似乎發生了變化。

我認爲ShiftName的列從工作表「ShiftRoster」的「B」更改爲「Cash」的「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 
+0

是的,停止使用'Select'和'* .Active ...'屬性。它們本質上不可靠,也很慢。 – RBarryYoung

+0

@RBarryYoung我應該用什麼來代替? – stupidgal

+0

您應該使用直接範圍並使用'SET'將變量保存到變量中。 – RBarryYoung

回答

4

資格的範圍/細胞的方法:的

代替

ShiftReason = Cells(ShiftRowName, ShiftColLeave) 

使用

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

所以你的代碼知道確切你指哪片。如果不符合您的範圍,則會假定您指的是ActiveSheet對象。