2015-02-06 205 views
0

我試圖根據單元格中的值更改字體顏色(16,3)。 由於某種原因,它無法正常工作。 16,3的現值是94%,並且呈現綠色而不是琥珀色。您的幫助將不勝感激。excel vba根據值更改文本框

Private Sub TextBox1_Change() 

    TextBox1.Value = Cells(16, 3).Text 
    Cells(16, 3).Font.Bold = True 

    If TextBox1.Value > 95 Then TextBox1.ForeColor = RGB(0, 128, 0) 'Green 

    If TextBox1.Value > 80 And TextBox1.Value < 95 Then TextBox1.ForeColor = RGB(255, 153, 0) 'Amber 

    If TextBox1.Value < 80 Then TextBox1.ForeColor = RGB(255, 0, 0) 'Red 

End Sub 
+0

嘗試在代碼行'If TextBox1.Value> 95 [...]''處添加一個斷點,然後將鼠標懸停在TextBox.Value部件上,以檢查代碼中的值視圖。我無法在代碼中看到錯誤,因此我們需要檢查文本框是否提取了正確的值。用戶窗體上還是工作表本身上的這個文本框? – Aiken 2015-02-06 08:34:33

+0

我現在檢查了。單元格中的值是百分比94%。我用了以下來達成它。 TextBox1.Value =格式(單元格(16,3),「00%」) – SKP 2015-02-06 08:42:17

+0

在定義textbox1值時,使用.value .text的insead。由此你會看到你的if語句中計算出來的真實價值。 – Dubison 2015-02-06 09:28:15

回答

2

如果單元格中的值是文本格式而不是實際值,則會得到該結果。有可能是這種情況嗎?

其他的事情要記住,雖然這不會是你存在的問題或文本將永遠是紅的原因,是94%,實際上是0.94,而不是94

編輯:(我正在對我的原始答案進行編輯以迴應評論,因爲我需要包含代碼,但這些代碼並沒有進入評論)

您還有其他一些問題。

第一個是,如果這是由單元格(16,3)中的值驅動的,我不確定您應該從Textbox1_Change事件驅動它。通過這樣做,您正在等待某人在該文本框中輸入值,並立即用該單元格中的任何值覆蓋它。最好在表單加載期間填寫條目。

很大程度上取決於你想要做什麼,而且我沒有關於這方面的信息。其次,如果您逐步瀏覽代碼,您會發現TextBox1.Value正在返回一個字符串;它有雙引號。但是你將它與一組數值相比較。

第三是你的代碼沒有處理(比方說)80%的精確匹配的情況。

第四是如果你直接從單元格中抽取值,它實際上是一個百分比值,它會出現爲0.94,而不是百分比格式。

這處理很多。

Dim rng As Excel.Range 

Set rng = ActiveSheet.Cells(16,3) 

TextBox1.Value = Format(rng.Value, "00%") 
rng.Font.Bold = True 

'You should really implement error checking here. 
'There's no point reading the value from the textbox if it's coming from a cell. 
'Just use the cell value. 
If rng.Value >= 0.95 Then 
    TextBox1.ForeColor = RGB(0, 128, 0) 'Green 
ElseIf rng.Value >= 0.8 And rng.Value < 0.95 Then 
    TextBox1.ForeColor = RGB(255, 153, 0) 'Amber 
ElseIf rng.Value < 0.8 Then 
    TextBox1.ForeColor = RGB(255, 0, 0) 'Red 
End If 

Set rng = Nothing 
+0

我甚至嘗試過0.94,但沒有奏效。私人小組TextBox1_Change() TextBox1.Value =格式(信元(16,3), 「00%」) 將細胞(16,3).Font.Bold =真 如果TextBox1.Value> 0.95然後TextBox1.ForeColor = RGB(0,128,0)'Green If TextBox1.Value> 0.8 And TextBox1.Value <0.94 Then TextBox1.ForeColor = RGB(255,153,0)'Amber If TextBox1.Value <0.8 Then TextBox1 .ForeColor = RGB(255,0,0)'紅色 End Sub – SKP 2015-02-06 09:04:12

+0

非常感謝ALAN K.您的代碼正常工作。從你學到有用的東西。 – SKP 2015-02-06 18:07:06

+0

非常歡迎。 – 2015-02-06 18:27:25

1

如果您使用的

TextBox1.Value = Cells(16, 3).Text 

TextBox1.Value = Cells(16, 3).Value 

,而不是你會看到你的if語句中使用的實際值。而結果會像下面:

如果相關的細胞的文本類型是: 「常規」

enter image description here

enter image description here

enter image description here

如果您使用相關的細胞類型爲「百分比」。你會得到下面的結果

enter image description here

enter image description here

enter image description here

所以,根據自己的喜好,你可以使用單元格的值一般也可以將其從百分比轉換的宏一般並按原樣顯示。

如果您想在您的相關工作表中繼續使用百分比,這意味着實際上它的值爲0.XX,但它會顯示爲XX%,那麼您可以簡單地將您的值乘以100,如下所示:

TextBox1.Value = Cells(16, 3).Value * 100