473,399 Members | 3,038 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,399 software developers and data experts.

Date Formatting in Excel VBA

Hello: Looking for help with this code. Currently it is not working but not sure what is wrong. The purpose is to format dates for 3 different Ms. Excel Files. Each file begins with a different name...one is AT, the other PT, and the last MX. Depending on the first two characters in the name of the file, the date will be formatted differently.

For example:

When the date is like this for PT and AT:

20100710

We use this formula:

=RIGHT(B38;2)&"."&MID(B38;5;2)&"."&LEFT(B38;4)

The result is: 10.07.2010

You are not misunderstanding.

When the date is like this for MX:

'1/1/2010

We use this formula:

="0"&LEFT(B39;1)&"."&"0"&MID(B39;3;1)&"."&RIGHT(B3 9;4)

The result is:

01.01.2010

Then we use the formatting in Excel to change it to:

dd.mm.year

The sheet is called "data"and it is the only active sheet in the excel file.


The code currently does nothing, no errors, etc. It just cycles through the sheets in the folder and saves them. It changes nothing concerning the dates for "AT"or "PT".



Expand|Select|Wrap|Line Numbers
  1. Option Explicit
  2.  
  3. Public Sub FormatDates()
  4. Dim wbOpen As Workbook
  5. Dim strExtension As String
  6.  
  7. Const strPath As String = "H:\"    'Change Path to the folder you have your files in
  8.  
  9.     'Comment out the 3 lines below to debug
  10. '    Application.ScreenUpdating = False
  11. '    Application.Calculation = xlCalculationManual
  12. '    On Error Resume Next
  13.  
  14.     ChDir strPath
  15.     strExtension = Dir(strPath & "*.xls")      'change to xls if using pre 2007 excel
  16.  
  17.         Do While strExtension <> ""
  18.             Set wbOpen = Workbooks.Open(strPath & strExtension)
  19.  
  20.             With wbOpen
  21.                If Left(LCase(.Name), 2) = "pt" Or Left(LCase(.Name), 2) = "at" Then     'change to lower case and check start of name
  22.                     ChangeAllDates ("NOT MX")
  23.                     .Close SaveChanges:=True
  24.                ElseIf Left(LCase(.Name), 2) = "mx" Then
  25.                     ChangeAllDates ("MX")
  26.                     .Close SaveChanges:=True
  27.                Else
  28.                    .Close SaveChanges:=False
  29.                End If
  30.             End With
  31.  
  32.             strExtension = Dir
  33.         Loop
  34.  
  35.     Application.ScreenUpdating = True
  36.     Application.Calculation = xlCalculationAutomatic
  37.     On Error GoTo 0
  38.  
  39. End Sub
  40.  
  41. Private Function ChangeAllDates(strType As String)
  42. Dim strTemp As String
  43. Dim strCellValue As String
  44. Dim rng As Range
  45. Dim cell As Range
  46. Dim sht As Worksheet
  47.  
  48.     Set sht = ActiveSheet
  49.  
  50.     Sheets("data").Activate     'selects sheet named data
  51.  
  52.     Set rng = Range("C2:C" & GetLastPopulatedCell(2, 2, sht)) 'finds last populated cell
  53.  
  54.     On Error GoTo err_check
  55.  
  56.     For Each cell In rng
  57.  
  58.         strCellValue = CStr(cell.Value)
  59.  
  60.         If Len(strCellValue) > 2 Then   'only check cells that have more than 2 charactors in them
  61.  
  62.             If InStr(1, strCellValue, ".", vbTextCompare) = 0 Then
  63.                 If strType = "MX" Then
  64.                     strTemp = Left(strCellValue, 4) & "." & Mid(strCellValue, 5, 2) & "." & Right(strCellValue, 2)
  65.                 Else
  66.                     strTemp = Right(strCellValue, 2) & "." & Mid(strCellValue, 5, 2) & "." & Left(strCellValue, 2)
  67.                 End If
  68.  
  69.                 If InStr(1, strCellValue, "/", vbTextCompare) > 0 Then      'change data / to .
  70.                     strTemp = Replace(strCellValue, "/", ".", 1, , vbTextCompare)
  71.  
  72.                     'now check to make sure that it reads yyyy.mm.dd if not then we need to reverse it and check
  73.                     'it has 2 numbers for month and year
  74.  
  75.                     strTemp = CheckDataFormat(strTemp)
  76.  
  77.  
  78.                 End If
  79.             Else
  80.                 strTemp = strCellValue
  81.             End If
  82.  
  83.             cell.Value = strTemp        'replace the cell value with the formatted value
  84.  
  85.             strCellValue = ""
  86.             strTemp = ""
  87.  
  88.             End If
  89.  
  90.     Next cell
  91.  
  92.     On Error GoTo 0
  93.  
  94.     Exit Function
  95.  
  96. err_check:
  97.  
  98.     MsgBox Error.Name & vbCrLf & "Error happend on cell " & cell.Address
  99.  
  100. End Function
  101.  
  102. Private Function GetLastPopulatedCell(lgRow As Long, lgCol As Long, sht As Worksheet) As Long
  103. Dim i As Integer
  104. Dim s As String
  105.  
  106.     For i = 0 To 10000        'set a default number of cells to check in this case I have set it to 10,000
  107.         If sht.Cells(lgRow, lgCol).Value <> "" Then
  108.             lgRow = lgRow + 1
  109.         Else
  110.             GetLastPopulatedCell = lgRow - 1
  111.             Exit For
  112.         End If
  113.     Next i
  114.  
  115. End Function
  116.  
  117. Private Function CheckDataFormat(str As String) As String
  118.  
  119. Dim strR As String
  120. Dim i As Integer
  121. Dim vArray As Variant
  122.  
  123. 'str = "06.01.2011"
  124.  
  125.     'have to check if date is in d.m.yyyy format if so we need to change it to dd.mm.yyyy
  126.  
  127.     If Len(str) < 10 Then           'only care if less than 10 charators
  128.  
  129.         vArray = Split(str, ".")    'split into array on points
  130.         str = ""
  131.  
  132.         For i = 0 To UBound(vArray)
  133.  
  134.             If Len(vArray(i)) = 1 Then                  'if only 1 charactor long we know we are missing 0
  135.                 str = str & "0" & vArray(i) & "."       'check if 0 exists before number if not add it
  136.             Else
  137.                 str = str & vArray(i) & "."
  138.             End If
  139.         Next i
  140.  
  141.         'remove last dot on the end
  142.         If Right(str, 1) = "." Then str = Left(str, Len(str) - 1)
  143.     End If
  144.  
  145.     Debug.Print str
  146.  
  147.     'strR = Right(str, 5)
  148.  
  149.     'If Left(strR, 1) = "." Then
  150.      '   str = Right(str, 4) & "." & Left(str, (Len(str) - 5))       'move the year to the front
  151.       '  str = Left(str, 5) & Right(str, 2) & Mid(str, 5, 3)         'switch round month and day
  152.      '   Debug.Print str
  153.     'End If
  154.  
  155.     CheckDataFormat = str
  156.  
  157. End Function
Jun 27 '11 #1
2 2426
NeoPa
32,556 Expert Mod 16PB
CASpears:
You are not misunderstanding.
Oh, I think we probably are. Big time.

Let's start off with a few basics and see if we can make our way to some sort of clear understanding of what's going on and what's required :
  1. Firstly, this is an Excel question. This is perfectly acceptable, but it would make sense to indicate so in the title as the name of the forum is Access / VBA. I will update that for you.
  2. This is neither British nor American locale for dates and numbers. Please indicate what country the code is for and what the formatting required is (standard short date and number formats would be helpful to see).
  3. I'm sure your explanation of the formats of the data that is to be expected in each file type has been confused in the translation, but it would help to include some examples of each type (which don't include day numbers below 13) so we can determine what data to expect coming in.
  4. In your example data, please include what you are hoping to convert the data to. This will help us to understand better what you are after.
If you can provide all this information then I expect we can help you. If there is any you're confused about, please ask. Without the requested information the question is likely to be stalled.
Jun 28 '11 #2
NeoPa:

I resolved the issue elsewhere. Thanks anyway...
Jun 29 '11 #3

Sign in to post your reply or Sign up for a free account.

Similar topics

2
by: Micah | last post by:
Hi, I've written a few schemas for an XML-based application interface. I'll be writing the backend of my side of the interface, but I'd like to mock-up the other side of the interface. One...
4
by: David | last post by:
Hi, Quick question: Using ASP, If I have a text box on a form, how can I auto populate it when the form loads with the date of the current Friday, i.e. dd/mm/yyyy Thanks for your help
1
by: poohnie08 | last post by:
i have a excel spreadsheet showing staff name, date,work hour, ot hour, slot1, slot2, slot3, slot4 and others). The "()" will keep repeating from day 1 until end of month. eg in excel spreadsheet,...
9
by: trint | last post by:
Instead of just sending one document at a time, I need to send multiple documents as a print job because our laserprinter will only stack and staple one printjob it receives at a time. I need to...
3
by: sham | last post by:
Hi to all, I am using XALAN processor and xslt 2.0 and I have managed to take an XML file and split it into multiple documents. This is done via the Oxygen editor. I now need to write a C#...
1
Virtualmedia
by: Virtualmedia | last post by:
Hi I am writing a dynamic contact form for my website http://www.virtualmedia.co.nz (contactus.asp) everything works okay except that I want to insert an auto date function to record the date and...
2
by: S.Dickson | last post by:
I have a mysql table, with a field called DATE, how do i get it to automatilly put the date on it every time a new recored it put on the table Date and time would be good, Tahnks
1
by: kashib | last post by:
What I am looking for is a C# example that can send multiple documents of different formats (eg pdf, doc, docx, jpeg etc)to the printer as one print job, I am not sure of the best approach. Can you...
7
Breeves22
by: Breeves22 | last post by:
Hi I am fairly new to access and only just beginning to work with creating my own database. I have three fields, the referral date, the visit date and the joint visit date. I am trying to...
0
by: dowlingm815 | last post by:
I currently importing a csv file with an import specification declaring the field values. one field is a date/time field. when the csv file is imported, it clears the date field with null values....
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.