select另一个工作表VBA后variables出错

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

variablesShiftName似乎在通过Sheets("Cash").Select在下面的代码中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 

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

代替

 ShiftReason = Cells(ShiftRowName, ShiftColLeave) 

使用

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

所以你的代码确切知道你指的哪个表。 没有限定你的范围,它会假定你指的是ActiveSheet对象。