简体   繁体   English

自动将条形添加到日期单元格

[英]Automatically add bars to date cells

I need a VBA code that inserts bars automatically in cells with date format. 我需要一个VBA代码,该代码会自动在日期格式的单元格中插入条形图。

I mean, you type 010101 in a cell and, after moving to the next, the cell converts 010101 to 01/01/2001 automatically. 我的意思是,您在一个单元格中键入010101,移动到下一个单元格后,该单元格将010101自动转换为01/01/2001。

I already have a code that insert bars, but it only works in cells with text format. 我已经有插入杆的代码,但是它仅适用于文本格式的单元格。

The code I have is as follows: 我的代码如下:

Private Sub Worksheet_Change(ByVal Target As Range)
 Set MyIntersect = Intersect(Target, Cells)
 If (Not (MyIntersect Is Nothing)) And (Not IsEmpty(MyIntersect)) Then
  Dim UserData As String: UserData = MyIntersect.Value
  If Right(UserData, 2) <= Mid(CStr(Year(Date)), 3, 2) Then
   UserData = Left(UserData, 4) & "20" & Right(UserData, 2)
  Else
   UserData = Left(UserData, 4) & "19" & Right(UserData, 2)
  End If
  UserData = Left(UserData, 2) & "/" & Mid(UserData, 3, 2) & "/" & _ 
  Right(UserData, 4)
  Application.EnableEvents = False
  MyIntersect.Value = UserData
  Application.EnableEvents = True
 End If
End Sub

I found the answer. 我找到了答案。 The trick was to convert the intersection.value first to long and then to string, and add a zero to the string if its lenght is equal to five. 诀窍是先将intersection.value转换为long,然后转换为字符串,如果字符串的长度等于5,则将其添加零。 The user must insert date as DDMMYY only, otherwise the code will not work, except if improved later. 用户必须仅将日期插入为DDMMYY,否则该代码将不起作用,除非稍后进行了改进。

The code is as follows: 代码如下:

Private Sub Worksheet_Change(ByVal Target As Range)
Set MyIntersect = Intersect(Target, Cells)
 If (Not (MyIntersect Is Nothing)) And (Not IsEmpty(MyIntersect)) Then
  Dim UserData As String: UserData = CStr(CLng(MyIntersect.Value))
  If Len(UserData) = 5 Then UserData = "0" & UserData
  If Right(UserData, 2) <= Mid(CStr(Year(Date)), 3, 2) Then
   UserData = Left(UserData, 4) & "20" & Right(UserData, 2)
  Else
   UserData = Left(UserData, 4) & "19" & Right(UserData, 2)
  End If
  UserData = Left(UserData, 2) & "/" & Mid(UserData, 3, 2) & "/" & _
  Right(UserData, 4)
  Application.EnableEvents = False
  MyIntersect.Value = UserData
  Application.EnableEvents = True
 End If
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM