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
是的,停止使用'Select'和'* .Active ...'屬性。它們本質上不可靠,也很慢。 – RBarryYoung
@RBarryYoung我應該用什麼來代替? – stupidgal
您應該使用直接範圍並使用'SET'將變量保存到變量中。 – RBarryYoung