輸入到單元格完全相同的文字,我應該說,我知道沒有VBA如何讓用戶在Excel
我在Excel中輸入大量的時間值的開始。因爲它確實減慢了我在輸入時輸入冒號的速度,所以我想我會寫一個宏,讓我輸入一個像「18.10」這樣的字符串並將其轉換爲「18:10」。 (然後我可以使用數字鍵盤並快速輸入時間)。
我把拼湊起來的函數轉換成任何給定的(分隔)字符串的時間 - 這很容易。但是現在我遇到了我的事件處理程序問題,因爲我無法獲取我輸入的確切文本,因爲Excel似乎將其視爲數字並修剪尾部0。
例如18.10被轉換爲18.1 - 被轉換爲18:01(而不是我想要的18:10)。
這裏是我的變化處理代碼(從interweb複製)
Private Sub Worksheet_Change(ByVal Target As Excel.Range)
Dim TimeStr As String
' This code copied from Chip Pearson
'http://www.cpearson.com/excel/DateTimeEntry.htm
If Application.Intersect(Target, Range("C6:F1000")) Is Nothing Then
Exit Sub
End If
If Target.Cells.Count > 1 Then
Exit Sub
End If
If Target.Value = "" Then
Exit Sub
End If
Application.EnableEvents = False
With Target
TimeStr = .Text ' What should I use here????
If .HasFormula = False Then
.Value = ConvertToTime(TimeStr)
End If
End With
Application.EnableEvents = True
Exit Sub
EndMacro: MSGBOX 「你沒有輸入一個有效的時間」 Application.EnableEvents =真 結束小組
由於你可以看到我目前正在使用Text
- 我在調試器中查看了Target
上的所有屬性,並且找不到任何看起來像是原始輸入文本的屬性。有沒有辦法獲得價值?
任何幫助非常感謝。
謝謝Issun和Craig。 Issun是正確的 - 我使它變得過於複雜(w.r.t.轉換爲時間)。這是我想出來的,工作得很好。
' This requires the format of the cells to ce "0.00" to prevent trailing 0s being trimmed
Private Sub Worksheet_Change(ByVal Target As Excel.Range)
On Error GoTo ErrHandler:
Dim TimeStr As String
Dim TimeVal
' I am only entering times in this range
If Application.Intersect(Target, Range("C6:F1000")) Is Nothing Then
Exit Sub
End If
If Target.Cells.Count > 1 Then
Exit Sub
End If
If Target.Value = "" Then
Exit Sub
End If
TimeStr = Replace(Target.Text, ".", ":")
TimeVal = TimeValue(TimeStr)
Application.EnableEvents = False
Target.Value = TimeVal
Target.NumberFormat = "h:mm"
Application.EnableEvents = True
Exit Sub
ErrHandler:
Exit Sub
End Sub
Sub SetTimeFormat()
Selection.NumberFormat = "h:mm"
End Sub
Sub SetNumFormat()
Selection.NumberFormat = "0.00"
End Sub
正如評論所說,我發現改變單元格格式 「0.00」 效果很好。輸入爲「18.1」的時間被轉換爲「18:10」(而不是18:01),但實際上這對我來說是可以的。
我分配給兩個熱鍵的最後2個宏,這樣如果我犯了一個錯誤,我可以將單元格的格式快速轉換回數字並再次結束該值。
你上面的功能是過於複雜。你是否需要所有的錯誤檢查(例如,如果它在C6:F1000等範圍內?)至於第二部分,你正在使用ConvertToTime,但我認爲你應該使用NumberFormat來代替。 。:) – aevanko
範圍檢查很有用,因爲我只在這些單元格中輸入時間值 - 我不希望將實際數值轉換爲時間 –
很高興看到您找到可行的解決方案(並感謝發佈它)和克雷格得到了接受。如果你發現我的回答很有幫助,不過會讚賞upvote! ^^ – aevanko