This question already has an answer here:
Format current date and time in VBScript
(1 answer)
Closed 2 months ago.
I use this code to change the date format for BGInfo but I get error code on line 3
Mismatch error 'Format" 800A000D
Dim dt, strDate
dt = Date
strDate = Format(dt, "yyyy-mm-dd")
BGInfo.BGI.Date = strDate
Research I've done doesn't seen to find a solution
I've tried this:
Dim strDate As String
strDate = Format(Now(), "yyyy/mm/dd")
BGInfo.BGI.Date = strDate
but that didn't work
BGInfo uses VBScript in it's Custom field VB Script file option. It does not support VBA, so VBA functions, such as Format cannot be used.
The Following code can be placed in the Custom field to provide a new field, that can be placed on screen, to display the date in yyyy-mm-dd format:
Echo Year(Now()) & "-" & Right("0" & Month(Now()),2) & "-" & Right("0" & Day(Now()),2)
However, this will not change the format of the existing fields, such as Boot Time.
There is no bginfo object, so the code BGInfo.BGI.Date = strDate will not work. The only way to change the date format for bginfo's built-in fields is to change the user's date format.
You can work around the issue by temporarily changing the user's date format to yyyy-mm-dd, running bginfo, and then change the date format back. Here's the code (save this to a separate file, such as RunBGInfo.vbs):
Set oWSH = CreateObject("Wscript.Shell")
sDateReg = "HKCU\Control Panel\International\sShortDate"
UserDateFormat = oWSH.RegRead(sDateReg)
oWSH.RegWrite(sDateReg),"yyyy-MM-dd"
oWSH.Run "bginfo.exe bginfo.bgi /timer:0 ",1,True
oWSH.RegWrite(sDateReg),UserDateFormat
You may also want to look at a bginfo alternative written in PowerShell (such as this one) that you can then modify and extend to meet your requirements.
Related
I am in need of some AppleScript code that will go to a website (https://www.time.gov/) and return the date. I have virtually no experience writing AppleScript code, and have had a very tough time figuring out how to do it.
A little context: the AppleScript code will be used inside an Excel workbook, inside VBA code. The AppleScript code is assigned to a String variable and then executed. Here’s a simple example of how that works.
Function FileExistsOnMac(Filestr As String) As Boolean
Dim ScriptToCheckFile As String
ScriptToCheckFile = "tell application " & Chr(34) & "System Events" & Chr(34) & _
" to return (exists disk item " & Chr(34) & Filestr & Chr(34) & ") and class of disk item " & _
Chr(34) & Filestr & Chr(34) & " = file "
FileExistsOnMac = MacScript(ScriptToCheckFile)
End Function
In my case, I would have the Function be of type String (or perhaps Date) and it would return the date that the AppleScript code returned from the website. If anyone could show me what the AppleScript code needs to be, it would be most appreciated.
Scraping (i.e. by reading from the text or source code of a website) is not an ideal method to obtain date and time information, and the website you picked is particularly bad because it displays the live time through JavaScript that continuously writes and updates the contents of the page, so the actual source code for the page doesn't actually contain any readable date or time information.
The more conventional method of retrieving a time from the internet is to do from a timeserver. time.gov have one at nist.time.gov, and you can request the date and time using the following bash shell command:
cat </dev/tcp/time.nist.gov/13
which returns something like this:
58641 19-06-07 06:19:14 50 0 0 800.5 UTC(NIST) *
The second and third fields are the ones you want, representing date and time, respectively. We can clean that up a little bit with the use of awk:
cat </dev/tcp/time.nist.gov/13 | awk 'length($0)>0 {print 20$2,$3}'
which returns:
2019-06-07 06:19:14
Since you specifically requested an AppleScript to do this, this will return to you the date and time as above:
do shell script "cat </dev/tcp/time.nist.gov/13 | awk 'length($0)>0 {print 20$2,$3}'"
and this will return to you just the date:
do shell script "cat </dev/tcp/time.nist.gov/13 | awk 'length($0)>0 {print 20$2}'"
I've never used VB(A) before, so forgive me if this is a trivial question.
I am trying to run the code outlined here on Excel 2016 on a Mac.
Sub simpleXlsMerger()
Dim bookList As Workbook
Dim mergeObj As Object, dirObj As Object, filesObj As Object, everyObj As Object
Application.ScreenUpdating = False
Set mergeObj = CreateObject("Scripting.FileSystemObject")
'change folder path of excel files here
Set dirObj = mergeObj.Getfolder("/...filepath")
Set filesObj = dirObj.Files
For Each everyObj In filesObj
Set bookList = Workbooks.Open(everyObj)
'change "A2" with cell reference of start point for every files here
'for example "B3:IV" to merge all files start from columns B and rows 3
'If you're files using more than IV column, change it to the latest column
'Also change "A" column on "A65536" to the same column as start point
Range("A2:IV" & Range("A65536").End(xlUp).Row).Copy
ThisWorkbook.Worksheets(1).Activate
'Do not change the following column. It's not the same column as above
Range("A65536").End(xlUp).Offset(1, 0).PasteSpecial
Application.CutCopyMode = False
bookList.Close
Next
End Sub
However, I get the error, that goes off without specifying a line:
Any thoughts on how I can modify this code for Mac?
Try this, based on the other (unaccepted) answer to similar question.
Is there an alternative to Scripting.FileSystemObject in Excel 2011 VBA for the mac?
The problem is that Scripting.Runtime library is not available on Mac OS, so you can't do CreateObject("Scripting.FileSystemObject"). This uses the VBA Dir function to build a Collection of files.
Also revised for more efficient "copy" that doesn't use the Copy method.
(untested, so bear with me in case of typos/etc.)
Sub simpleXlsMerger()
Dim bookList As Workbook, vals as Variant
Dim filesObj As Object, everyObj As Object
Application.ScreenUpdating = False
Set mergeObj = CreateObject("Scripting.FileSystemObject")
'change folder path of excel files here
Set filesObj = GetFileList("/...filepath")
For Each everyObj In filesObj
Set bookList = Workbooks.Open(everyObj)
'change "A2" with cell reference of start point for every files here
'for example "B3:IV" to merge all files start from columns B and rows 3
'If you're files using more than IV column, change it to the latest column
'Also change "A" column on "A65536" to the same column as start point
vals = Range("A2:IV" & Range("A" & Rows.Count).End(xlUp).Row).Value2
With ThisWorkbook.Worksheets(1)
'Do not change the following column. It's not the same column as above
.Range("A" & .Rows.Count).End(xlUp).Offset(1, 0).Resize(UBound(vals, 1), UBound(vals, 2)).Value = vals
End With
bookList.Close
Next
End Sub
Function GetFileList(folderPath As String) As Collection
'mac vba does not support wildcards in DIR function
Dim file As String
Dim returnCollection As New Collection
If Right$(folderPath, 1) <> "\" Then
folderPath = folderPath & "\"
End If
file = Dir$(folderPath) 'setup initial file
Do While Len(file)
returnCollection.Add folderPath & file
file = Dir$
Loop
Set GetFileList = returnCollection
End Function
In the VBA window, click tools then add reference. Make sure Microsoft Office Object Library (14 or 16) is checked. You will need this for the automation.
An alternative idea would be to create a loop and save each excel file as a csv then run a batch script.
Example:
copy *.csv merged.csv
For the CSV loop use:
Converting XLS/XLSX files in a folder to CSV
I have datetime stamp (MMDDYYYYHHMMSS) extracted from a file Name as
Filedate = "10212015140108"
How can I convert it into datetime format mm/dd/yyyy hh:mm:ss.
Can someone help to get it resolved?
From what I can gather from the question it looks as though the Filedate value is just a string representation of date (mmddyyyyhhnnss), with that in mind did a quick test to see if I could parse it into the format required.
There are other ways of approaching this like using a RegExp object to build up a list of matches then use those to build the output.
Worth noting that this example will only work if the structured string is always in the same order and the same number of characters.
Function ParseTimeStamp(ts)
Dim df(5), bk, ds, i
'Holds the map to show how the string breaks down, each element
'is the length of the given part of the timestamp.
bk = Array(2,2,4,2,2,2)
pos = 1
For i = 0 To UBound(bk)
df(i) = Mid(ts, pos, bk(i))
pos = pos + bk(i)
Next
'Once we have all the parts stitch them back together.
'Use the mm/dd/yyyy hh:nn:ss format
ds = df(0) & "/" & df(1) & "/" & df(2) & " " & df(3) & ":" & df(4) & ":" & df(5)
ParseTimeStamp = ds
End Function
Dim Filedate, parsedDate
Filedate = "10212015140108"
parsedDate = ParseTimeStamp(FileDate)
WScript.Echo parsedDate
Output:
10/21/2015 14:01:08
Function CurrMonthName(dateval)
Dim tmp : tmp = DateAdd("m", 0, dateval)
CurrMonthName = MonthName(Month(tmp))
CurrMonthName = replace(CurrMonthName , "%M",CurrMonthName)
i am trying to format the month name so that it displays first 3 letters. On searching found %M can be used. I tried using it in above code and results are not coming as expected. It is still displaying full month
In VBScript, the way to get an abreviated Monthname is MonthName.
>> WScript.Echo MonthName(Month(Date()), True)
>>
Jul
>>
See this answer for a more flexible way to format dates (and other kind of data).
Use the function "Left" to cut the first off: Left("February",3) gives you "Feb"
I'll try to keep it short and precise.
I really hope you can help me.
I am facing the following problem:
Background:
Workbook with a lot of formulas -> Calculation set to manual
Recalculation takes 5-10 minutes each time
What I want to do:
Generate ranges of data individually for multiple people
then select those ranges, and paste them into the body of an e-mail
send those e-mails one by one
What is the problem?
If I use the "Envelope" method to prepare the e-mails everything is fine until I press send. However, every time I press send excel automatically recalculates the entire Workbook. Obviously I do not want to wait 5-10 minutes to send out each e-mail (always between 10 and 20)
Since I thought it might have to do with the "Envelope" method I decided to switch to creating an e-mail directly via Outlook (outlook object). It worked fine as far as opening the e-mail and sending it without recalculation. However, after the e-mail is opened by Outlook, all(!) formulas in the entire Workbook are set to #Value. This obviously also forces me to recalculate as I cannot create the table for the next person's e-mail.
Does anyone know what is causing the recalculation/error values and what I can do to stop it? I'd be really glad about any suggested solutions.
I am also attaching my code, though I doubt it will help in clearing up the issue
`'DESCRIPTION:
'This routine prepares an e-mail for requesting the progress estimates from the deliverable owners
'1. set all the values based on named ranges in PI and Config sheets
'2. Concatenate all relevant strings to full e-mail text
'3. select PI table
'4. Create e-mail and display
Sub PrepareEmail()
Dim s_EmailAddress As String, s_FirstName As String
Dim s_Email_Greeting As String, s_Email_MainText1 As String, s_Email_MainText2 As String, s_Email_DeadlineRequest As String
Dim s_Email_Deadline As String, s_Email_Subject As String, s_Email_ClosingStatement As String, s_Email_SenderName As String, s_Email_CC As String
Dim s_Email_Full As String
Dim rng_PI_TableValues As Range, rng_PI_TableFull As Range
Dim s_Email_FullText As String
Dim obj_OutApp As Object
Dim obj_OutMail As Object
s_EmailAddress = [ptr_PI_Email]
s_FirstName = [ptr_PI_FirstName]
s_Email_Subject = [ptr_Config_PIEmail_Subject]
s_Email_Greeting = [ptr_Config_PIEmail_Greeting]
s_Email_MainText1 = [ptr_Config_PIEmail_MainText1]
s_Email_MainText2 = [ptr_Config_PIEmail_MainText2]
s_Email_DeadlineRequest = [ptr_Config_PIEmail_DeadlineRequest]
s_Email_Deadline = [ptr_Config_PIEmail_Deadline]
s_Email_ClosingStatement = [ptr_Config_PIEmail_ClosingStatement]
s_Email_SenderName = [ptr_Config_PIEmail_SenderName]
s_Email_CC = [ptr_Config_PIEmail_CC]
'Concatenate full e-mail (using HTML):
s_Email_Full = _
"<basefont face=""Calibri"">" _
& s_Email_Greeting & " " _
& s_FirstName & ", " & "<br> <br>" _
& s_Email_MainText1 & "<br>" _
& s_Email_MainText2 & "<br> <br>" _
& "<b>" & s_Email_DeadlineRequest & " " _
& s_Email_Deadline & "</b>" & "<br> <br>" _
& s_Email_ClosingStatement & "," & "<br>" _
& s_Email_SenderName _
& "<br><br><br>"
'-------------------------------------------------------
Set rng_PI_TableValues = Range("tbl_PI_ProgressInput")
Set rng_PI_TableFull = Union(rng_PI_TableValues, Range("tbl_PI_ProgressInput[#Headers]"))
Application.EnableEvents = False
Application.ScreenUpdating = False
Set obj_OutApp = CreateObject("Outlook.Application")
Set obj_OutMail = obj_OutApp.CreateItem(0)
With obj_OutMail
.To = s_EmailAddress
.CC = s_Email_CC
.Subject = s_Email_Subject
.HTMLBody = s_Email_Full & RangetoHTML(rng_PI_TableFull)
.Display
End With
Application.EnableEvents = True
Application.ScreenUpdating = True
Call update_Status
End Sub
`
If you're using RangeToHTML from Ron de Bruin's website, that's what's causing your problem. That utility is fine if you need perfect fidelity and have a heavily formatted bu otherwise fairly simple range. But if your range has a bunch of dependencies, you'll have problems. It's putting the range into its own workbook, so any formulas that refer to data outside the range get funky.
If you need perfect fidelity, then you're stuck because the only way it will be perfect is by saving the range as HTML and reading that back. But if you don't have a bunch of heavy formatting or you just need a nice looking table, then I suggest you write your own RangeToHTML function that produces the HTML strings.
David McRitchie has some functions that do a pretty good job if you don't want to roll your own. http://dmcritchie.mvps.org/excel/xl2html.htm
Also, I don't know what update_Status does, but if it's causing a recalc, then you have two problems. If that's the case, figure out how to store up all the stuff that update_status does and do it once at the end rather than in the loop.