Changing Day and Month to DD and MM format in VBA - vba

To give some context here, I have a dat file that I am trying to save as an xlsx on my Q drive. I know that the majority of the code works (I've tested it), so I don't want to completely change it, but the formatting as I explain below is what I need help with. The following code is in workbook1 and it is referencing workbook2. Cell D3 in workbook one is a date formula but unfortunately, the FileDay and FileMonth code will only pull in a single "d" or "m" when what I want is it to pull in days and months in the "dd" and "mm" format. Since the code below is trying to find a file in this format: "yyyy_mm_dd" but FileDay and FileMonth are only pulling in "d" and "m", it will only work during part of the year. What is the piece of code that I am missing to pull in the correct formatting from cell D3?
Dim FName As String, FPath As String
Dim wkb1 As Workbook, wkb2 As Workbook
Set wkb1 = ThisWorkbook
FileDay = Day(Range("D3"))
FileMonth = Month(Range("D3"))
FileYear = Year(Range("D3"))
FPath = "Q:\MyFolder"
FName = "MyFile_" & FileYear & "_" & FileMonth & "_" & FileDay & ".xlsx"
Set wkb2 = Workbooks("MyFile_" & FileYear & "_" & FileMonth & "_" & FileDay
& ".dat")
With wkb2
.SaveAs Filename:=FPath & "\" & FName
.Close True
End With
End Sub

Assuming these variables are Strings, use the Format$ function.
FileDay = Format$(Day(Range("D3")), "00")
FileMonth = Format$(Month(Range("D3")), "00")
FileYear = Format$(Year(Range("D3")), "0000")
Alternatively, do it all at once:
= Format$(Range("D3"), "YYYY_MM_DD")

Related

VBA lookup refer to first sheet in workbook not "Sheet1"

How would I change the below lookup to refer to the first sheet in the workbook and not 'Sheet 1'?
.Range("I15:I" & lastRow).FormulaR1C1 = _
"=IF(VLOOKUP(RC[-8],[" & combinedWorkbook.Name & "]Sheet1!C1:C2,1,TRUE)=RC[-8],VLOOKUP(RC[-8],[" & combinedWorkbook.Name & "]Sheet1!C1:C2,2,TRUE),NA())"
Thanks
You are concatenating already the workbook name into the formula. The same way you could concatenating the name of the first worksheet too. The first worksheet is the first sheet in workbook's Worksheets collection.
So combinedWorkbook.Worksheets(1).Name would be the name of the first worksheet in workbook combinedWorkbook.
But names could containing spaces like "My Worksheet Name". Then the reference itself must be within single quotes like 'My Worksheet Name'!A1.
So all together:
.Range("I15:I" & lastRow).FormulaR1C1 = _
"=IF(VLOOKUP(RC[-8],'[" & combinedWorkbook.Name & "]" & combinedWorkbook.Worksheets(1).Name & "'!C1:C2,1,TRUE)=RC[-8],VLOOKUP(RC[-8],'[" & combinedWorkbook.Name & "]" & combinedWorkbook.Worksheets(1).Name & "'!C1:C2,2,TRUE),NA())"
if you are going to re-use it then I would declare:
Dim first_sheet As String
first_sheet = combinedWorkbook.Sheets(1).Name
And then use it in your code like this:
.Range("I15:I" & lastRow).FormulaR1C1 = _
"=IF(VLOOKUP(RC[-8],[" & combinedWorkbook.Name & "] & first_sheet & !C1:C2,1,TRUE)=RC[-8],VLOOKUP(RC[-8],[" & combinedWorkbook.Name & "] & first_sheet & !C1:C2,2,TRUE),NA())"
This is really a small example how to refer to the first worksheet.
Take the name of the first worksheet and save it as a variable, using the .Name property.
Concatenate the variable in the formula:
Public Sub TestMe()
Dim wks1 As String
wks1 = Worksheets(1).Name
'worksheets should not contains spaces! :) left and right
Worksheets(1).Name = Trim(wks1)
Range("I15:I20").FormulaR1C1 = "=" & wks1 & "!R1C1"
End Sub

How to get the sheet name using GetOpenFilename in VLOOKUP

I am using this code down below to use a VLOOKUP in another file that you select using the GetOpenFilename. I want shtName to be the name of the sheet in the file that you select, but whenever I step through it, it is always the name of the sheet that I am working in and putting the VLOOKUP in.
I have shtName in my VLOOKUP and it doesn't show anything when I step through it. X shows the filename and path, but shtName right after shows nothing. But my VLOOKUP ends up working anyway and it puts the sheet in the formula.
Why is that? I want to be able to do it myself and so I know I get the sheet name from the file you are selecting.
Dim iRet As Integer
Dim strPrompt As String
Dim strTitle As String
' Promt
strPrompt = "Please select the last Kronos Full File before the dates of this HCM Report." & vbCrLf & _
"This will be used to find the Old Position, Org Unit, and Old Cost Center." & vbCrLf & _
"For example, if the date of this report is 7-28-17 thru 8-25-17, the closest Kronos Full File you would want to use is 7-27-17."
' Dialog's Title
strTitle = "Last Kronos Full File for Old Positions"
'Display MessageBox
iRet = MsgBox(strPrompt, vbOK, strTitle)
Dim LR As Long
Dim X As String
Dim lNewBracketLocation As Long
X = Application.GetOpenFilename( _
FileFilter:="Excel Files (*.xls*),*.xls*", _
Title:="Choose the Kronos Full File.", MultiSelect:=False)
MsgBox "You selected " & X
'Find the last instance in the string of the path separator "\"
lNewBracketLocation = InStrRev(X, Application.PathSeparator)
'Edit the string to suit the VLOOKUP formula - insert "["
X = Left$(X, lNewBracketLocation) & "[" & Right$(X, Len(X) - lNewBracketLocation)
shtName = ActiveWorkbook.Worksheets(1).name
LR = Range("E" & Rows.Count).End(xlUp).Row
Range("T2").Formula = "=VLOOKUP($E2,'" & X & "]shtName'!$B$1:$AP$99999,15,0)"
Stop
Range("T2").AutoFill Destination:=Range("T2:T" & Range("E" & Rows.Count).End(xlUp).Row)
Stop
Range("T2:T" & Range("E" & Rows.Count).End(xlUp).Row).Select
Stop
Range("U2").Formula = "=VLOOKUP($E2,'" & X & "]shtName'!$B$1:$AP$99999,41,0)"
Range("U2").AutoFill Destination:=Range("U2:U" & Range("E" & Rows.Count).End(xlUp).Row)
Range("U2:U" & Range("E" & Rows.Count).End(xlUp).Row).Select
Range("V2").Formula = "=VLOOKUP($E2,'" & X & "]shtName'!$B$1:$AP$99999,18,0)"
Range("V2").AutoFill Destination:=Range("V2:V" & Range("E" & Rows.Count).End(xlUp).Row)
Range("V2:V" & Range("E" & Rows.Count).End(xlUp).Row).Select
Cells.Select
Cells.EntireColumn.AutoFit
Something like the following should give you the worksheets name out of a file
Dim wbk As Workbook
Set wbk = Workbooks.Open(Filename:="YOUR_FILE_PATH", ReadOnly:=True)
Dim shtName As String
shtName = wbk.Worksheets(1).Name
wbk.Close
Note: We can open the workbook in read only mode if we don't plan to change anything.
Additionally I recommend (for a good code following good practices):
Always specify a worksheet.
Eg for every Range("") like Worksheets("YourSheetName").Range("")
Or use With statements:
With Worksheets("YourSheetName")
.Range("A1").Value = 5 'recognize the starting full stop referring to the with statement
End With
Same for every Rows, Columns, Cells, etc.
Avoid using .Select, .Activate and Selection. at all.
(there are many tutorials out there in the Internet how to avoid them).
Use Option Explicit and declare all your variables before use.
(avoids many issues, especially typos).

Using .formula using vba excel

I'm trying link to workbooks. Then Remove the link. The formula is working fine when the Full path is given but fails the moment a string is passed. In the below vba i'm trying to give the name of the location of the files from a cell value in Sheet1.
'Location of Template and Country
Cntryloc = """" & Sheet1.Range("B5") & """"
Debug.Print Cntryloc
TempLoc = "" & Sheet1.Range("B11") & ""
Finaltemplloc = Sheet1.Range("B17")
i=2
'Getting the name of excel Sheet
CntryExcel = Sheet1.Range("C5")
TempLoc = "" & Sheet1.Range("B11") & ""
Workbooks.Open TempLoc & "\" & "Bank" & ".xlsx", True, False
Workbooks("" & FName & ".xlsx").Activate
ActiveWorkbook.Unprotect Password:="Tall.Trees"
Worksheets("Template").Unprotect Password:="Tall.Trees"
Worksheets("Template").Range("D14").Formula = "='&"["&CntryExcel&"]Dump"&"'"&"!"&"$A$" & i""
ActiveWorkbook.BreakLink Name:=Cntryloc, Type:=xlExcelLinks
Worksheets("Template").Protect Password:="Tall.Trees"
ActiveWorkbook.Protect Password:="Tall.Trees"
'Location for Final Output
ActiveWorkbook.SaveAs Filename:=Finaltemplloc & "\" & Bank.xlsx
ActiveWorkbook.Close
try with this
Worksheets("Template").Range("D14").Value = "='[" & CntryExcel & "]Dump'!" & "$A$" & i & ActiveWorkbook.BreakLink & "Name:=" & Cntryloc & ", Type:=" & xlExcelLink
try this
Worksheets("Template").Range("D14").Formula = "='[" & CntryExcel & "]Dump!$A$" & "i"
that should fix the formula input
but check for CntryExcel to hold a workbook name and not a sheet name as per your comment preceeding its initialization ('Getting the name of excel Sheet)

Correct Excel Macro to Save A Copy Excel File as TXT or CSV

So I have this home-made Excel Macro Template.
The task of the macro code that I inserted in my xlsm file is to Save a copy in the same folder with a different format. That format is .txt (see image below)
The expected result of the macro (after saving) should be the same with the excel file (visually) but this time it is in a .txt format.
Unfortunately, that didn't happened. It generates a different txt file and it contains unreadable alpha numeric characters, here's an example of the generated txt file.
¬TËNÃ0 ¼#ñ ‘¯(vဠjÚ # °µ· ©c[^SÚ¿g“–
P ö '±wfvìq 8o\1ÃD6øJœËž(Ðë`¬ŸTâõå¾¼ eð \ðX‰ ’ NOú/‹ˆTpµ§JÔ9Çk¥H×Ø É ÑóÌ8¤ 2 ¦‰Š §0AuÑë]* |FŸËÜbˆAÿ Çðîrq7çßK%#ëEq³\×RU btVCf¡jæ l¨ã±Õ(g#xJá
u j#XBG{Ð~J.Wr%WvŒTÛHgÜÓ †vf»ÜUÝ#ûœ¬Áâ R~€†›Rs§>BšŽB˜ÊÝ «žq®ÑIª ³l#§pçaä ý ë¿ î`ê*IuÃù ( ³´Ü ýÞð JŠ Át` “m'Ýû ™ ªîy¸„ f !å…C:r·KÐ}Ì5$4Ï9q Ž.à;ö. ¼] H ¼„ÿwá+mu S¶¸ŽÃ¦Ã¶fäÔ l;¶×‚A³ [u×Ðà ÿÿ PK ! µU0#ô L _rels/.rels ¢ (
Here's my macro code:
Sub SaveMe()
Dim FName As Range
Dim firstDate As String
Dim firstTime As String
Dim answer As Integer
firstDate = Format(Date, "mmddyyyy")
firstTime = Format(Now, "hhmmssAM/PM")
Set FName = Range("H5")
ActiveWorkbook.SaveCopyAs FileName:=ActiveWorkbook.Path & "\" & "QB JE " & FName & " " & firstDate & " " & firstTime & ".txt", FileFormat:=xlText, CreateBackup:=False
End Sub
I was wondering if anyone could take a look at my code and help to point out whats wrong.
It looks like you want the SaveAs Not the SaveCopyAs.
Fileformat xlText or xlTextMSDOS
You can two step the process. Save a copy, then open it, and save it as a text file.
ActiveWorkbook.SaveCopyAs FileName:=ActiveWorkbook.Path & "\" & "QB JE " & FName & " " & firstDate & " " & firstTime & ".xlsx"
Workbooks.Open (ActiveWorkbook.Path & "\" & "QB JE " & FName & " " & firstDate & " " & firstTime & ".xlsx")
ActiveWorkbook.SaveAs FileName:=ActiveWorkbook.Path & "\" & "QB JE " & FName & " " & firstDate & " " & firstTime & ".txt", FileFormat:=xlText, CreateBackup:=False
https://msdn.microsoft.com/en-us/library/office/ff841185.aspx
https://msdn.microsoft.com/en-us/library/office/ff198017.aspx
See from my post here. Excel VBA Export To Text File with Fixed Column Width + Specified Row and Columns Only + Transpose
Loop all rows and all cells. Send each value to a padspace function. Build the string from for each cells value with spaces padded after the cell value.
You will have to add a reference to you workbook. In the VBA IDE go to the tools pull down menu and select references. Then scroll down and select "Microsoft Scripting Runtime". Then hit OK.
Adjust the pad space function call argument to a number that fits the data that you have in your spreadsheet. So you will change the 20 in the line with the padspace call. PadSpace(20, len(cellValue))
This will do all rows and columns.
Public Sub MyMacro()
Dim lRow As Long
Dim lCol As Long
Dim strRow As String
Dim ws As Excel.Worksheet
Dim ts As TextStream
Dim fs As FileSystemObject
'Create the text file to write to
Set fs = New FileSystemObject
Set ts = fs.CreateTextFile("C:\Temp\test.txt", True, False)
Set ws = Application.ActiveSheet
'Loop through all the rows.
lRow = 1
Do While lRow <= ws.UsedRange.Rows.count
'Clear the string we are building
strRow = ""
'Loop through all the columns for the current row.
lCol = 1
Do While lCol <= ws.UsedRange.Columns.count
'Build a string to write out.
strRow = strRow & ws.Cells(lRow, lCol) & PadSpace(20, Len(ws.Cells(lRow, lCol)))
lCol = lCol + 1
Loop
'Write the line to the text file
ts.WriteLine strRow
lRow = lRow + 1
ws.Range("A" & lRow).Activate
Loop
ts.Close: Set ts = Nothing
Set fs = Nothing
End Sub
'This function will take the max number of spaces you want and the length of the string in the cell and return you the string of spaces to pad.
Public Function PadSpace(nMaxSpace As Integer, nNumSpace As Integer) As String
If nMaxSpace < nNumSpace Then
PadSpace = ""
Else
PadSpace = Space(nMaxSpace - nNumSpace)
End If
End Function

How can I SaveAs a new workbook to original workbook directory with Excel VBA?

Basically, I'd like to save some worksheets into separate new workbooks in the same system location as original notebook I am deriving from.
I recognize that the default path is to save something new is to the location of the current notebook, but perhaps since I am opening a new workbook the default reverts to the user's Document's folder, which is where they are saving right now.
I "learned" VBA over the last couple of days, so advice on other things you notice is cool too, but the saveas is what's bothering me.
Dim ws As Worksheet
Dim wb As Workbook
Dim dept_array As Variant
Dim dept As Variant
' Add or remove a department name spelled exactly as it is in the filter
dept_array = Array("HR", "IT", "Marketing", "Product Marketing", "Sales", "Channels", "Presales", "Direct", "Sales Ops", "R&D", "Support", "G&A")
Application.ScreenUpdating = False
For Each ws In Workbooks("Weekly Department Transaction Report.xlsm").Worksheets
For Each dept In dept_array
If Application.Proper(ws.Name) = Application.Proper(dept) _
Then
Set wb = Workbooks.Add
ThisWorkbook.Sheets(dept).Copy Before:=wb.Sheets(1)
wb.Saveas dept & "_" & Format(Now, "yyyymmdd") & ".xlsx"
Workbooks("Weekly Department Transaction Report.xlsm").Sheets("Codes").Copy After:=Workbooks(dept & "_" & Format(Now, "yyyymmdd") & ".xlsx").Sheets(dept)
Workbooks("Weekly Department Transaction Report.xlsm").Sheets("How").Copy Before:=Workbooks(dept & "_" & Format(Now, "yyyymmdd") & ".xlsx").Sheets(dept)
Workbooks(dept & "_" & Format(Now, "yyyymmdd") & ".xlsx").Save
End If
Next dept
Next ws
Application.ScreenUpdating = True
End Sub
Please let me know if I am not following the correct stackoverflow format.
Longtime user first time asker :)
Edit this line in your code:
wb.SaveAs FileName:= ThisWorkbook.Path & "\" & dept & "_" & Format(Now, "yyyymmdd") & ".xlsx"