2017-09-27 70 views
1

我有下面的代碼,我實際上想重新命名基於I16的值的工作表。但是,如果目標地址爲空白/我不希望退出該子項。 (這部分代碼不起作用)。工作表更改事件

如果有人可以建議我如何解決這個問題,將不勝感激。

Private Sub Worksheet_Change(ByVal Target As Range) 

Dim KeyCells As Range 
Set KeyCells = Range("I16") 
Dim WSname As String 
WSname = Range("I16").Value 

If KeyCells Is Nothing Then Exit Sub 

Sheet23.Name = "BISSB" 
Sheet25.Name = "RMIB" 
Sheet26.Name = "MORIB" 
Worksheets(WSname).Name = "Stage 3 V1" 

End Sub 

回答

1

代替

If KeyCells Is Nothing Then Exit Sub 

使用

If IsEmpty(KeyCells) Then Exit Sub 

的IsEmpty函數可用於檢查空白單元格。如果單元格爲空白,則返回TRUE,否則返回FALSE

+0

感謝此工作完美! –

+0

@SeanBailey - 不客氣! – Mrig

2

替換:

If KeyCells Is Nothing Then Exit Sub 

有了:

If Trim(WSname) = "" Then Exit Sub 

說明:你已經在你的代碼中使用Set KeyCells = Range("I16"),所以您將KeyCells範圍,因此它永遠不會Nothing 。 您想要檢查KeyCells範圍的值,並且您有WSname字符串變量。

+0

感謝這個工作! –

+1

@SeanBailey我會小心使用'IsEmpty'函數,小心「隱藏」空間。該函數不會將空格視爲「Empty」,「Trim」選項將排除所有空格 –

0

您已經聲明並將KeyCells設置爲「I16」。這就是爲什麼條件不起作用 - 因爲KeyCells已經包含單元格。詢問是否WSname =「」或者檢查是否包含值或否。

0

我認爲使用Change Event代碼的正確方法是告訴代碼何時自動觸發並執行一些操作。

現在,每當單張上的任何單元格發生更改時,都會觸發代碼並執行代碼中定義的操作。

我假設你想要觸發更改事件代碼,並且只在單元格I16發生變化時執行一些預定義操作,然後根據代碼重命名錶單。對?

如果是這樣,您可以嘗試這樣的事情...

Private Sub Worksheet_Change(ByVal Target As Range) 
If Target.CountLarge > 1 Then Exit Sub 
Dim KeyCells As Range 
Set KeyCells = Range("I16") 
Dim WSname As String 
WSname = Range("I16").Value 

If Not Intersect(Target, KeyCells) Is Nothing Then 
    If Target <> "" Then 
     Sheet23.Name = "BISSB" 
     Sheet25.Name = "RMIB" 
     Sheet26.Name = "MORIB" 
     Worksheets(WSname).Name = "Stage 3 V1" 
    End If 
End If 
End Sub