VBA Open Workbooks File Not Found - vba

I have some macros that were working previously like:
Sub test()
'
' test Macro
'
Windows("_Macro_Duplicate Billing Templates.xltm").Activate
Src2 = Sheets("Parameters").Range("C12").Value
Workbooks.Open Filename:=Src2
End Sub
where I indicated "D:\Users\D801878\Int'l\Billing\2017_03\Billing Template_International_2017_03.xlsx" in cell C12
This was working in 2016 till now. Now I get the error that "D:\Users\D801878\Int'l\Billing\2017_03\Billing Template_International_2017_03.xlsx is not found."
Did anything change in terms of naming the filepath and filename?

I recommend to make like this:
I'm supposed the value 03 means the number of the month witch is march or mar, so:
Put in C12 the date mar.2017 and use the following code:
Dim y As Integer
Dim m As String
Dim ws As Worksheet
Dim link As String
Set ws = ThisWorkbook.Worksheets("Parameters")
y = Format(ws.Range("C12"), "yyyy")
m = Format(ws.Range("C12"), "mm")
link = "D:\Users\D801878\Int'l\Billing\" & y & "_" & m & "\Billing_Template_International_" & y & "_" & m & ".xlsx"
Workbooks.Open link

Related

Looping through & Opening Files based on Range and Period

I have a project where I need to open all territory files associated with a district in a range of districts, looping through each district. All files for that district need to be opened in the periods (months) equal to and prior to an inputted month value. The files need to be opened one at a time with values from certain variant worksheets in that file copied and pasted into another master file. The structure of the files is Path\Year\District\Period\Territory.xlsx.
I am encountering errors with the following code which attempts to capture the month for the report and compare it to the Period variable. I am getting the Next without For error.
Sub DSMReports()
Sheets("START").Activate
Dim MM As Variant
Dim YYYY As Variant
MM = InputBox("Enter Month for reporting in MM format: 01-12")
YYYY = InputBox("Enter Year for reporting in YYYY format")
Range("C6").Value = MM
Range("C8").Value = YYYY
Dim DistrictDSM As Range
Dim DistrictsDSMList As Range
Set DistrictsDSMList = Start.Range("E11:E23")
Dim Path As String
Dim DistPeriodFile As String
Dim Total As Integer
Dim Period As Integer
For Each DistrictDSM In DistrictsDSMList.Cells
Total = 0
For Period = 1 To MM
Period = Total + 1
If Period < 10 Then Path = "\\corsrv027\Accounting\Monthend " & YYYY & "\DSM Files\" & DistrictDSM & "\P0" & Period
If Period >= 10 Then Path = "\\corsrv027\Accounting\Monthend " & YYYY & "\DSM Files\" & DistrictDSM & "\P" & Period
DistPeriodFile = Dir(Path & "\*.xlsx")
Do While DistPeriodFile <> ""
Workbooks.Open Filename:=Path & "\" & DistPeriodFile
'Do copying, pasting, and going through each worksheet one at a time here
DistPeriodFile = Dir
Next Period
Next DistrictDSM
Loop
End Sub
Fix the Next Without For error by moving the Loop of the Do While loop before the Next Period and Next DistrictDSM. Indentation visualizes and helps properly structure your loops, and would have highlighted your "interwoven" loop structure.
For Each DistrictDSM In DistrictsDSMList.Cells
' code
For Period = 1 To MM
' more code
Do While DistPeriodFile <> ""
' more code
Loop
Next Period
Next DistrictDSM

Cross workbook Vlookup

Hey guys im trying to perform vlookup through cross-workbook. Im trying to write it this way.. but it seems not working using "x" and "x2"..
Folder = ActiveWorkbook.Path + "\"
Dim OptioneeManWb As Workbook
Dim TransOutWb As Workbook
Dim TransOutWs As Worksheet
Dim TermWb As Workbook
Dim TermWs As Worksheet
Set OptioneeManWb = Workbooks("optionee statement manual.xlsx")
Set TransOutWb = Workbooks.Open(Folder & "employee transfer out.xlsx")
Set x = TransOutWb.Worksheets("out").Range("A:C")
Set TermWb = Workbooks.Open(Folder & "employee terminated listing.xlsx")
Set x2 = TermWb.Worksheets("terminated").Range("A:C")
OptioneeManWb.Sheets("manual optionee stmt").Range("C6:C" & lastrow2).Formula = "=VLOOKUP(B:B,x,3,0)"
OptioneeManWb.Sheets("manual optionee stmt").Range("D6:D" & lastrow2).Formula = "=VLOOKUP(B:B,x2,3,0)"
OptioneeManWb.Sheets("manual optionee stmt").Range("C6:C" & lastrow2, "D6:D" & lastrow2).NumberFormat = "m/d/yyyy"
OptioneeManWb.Sheets("manual optionee stmt").Range("C:F").Copy
OptioneeManWb.Sheets("manual optionee stmt").Range("C:F").PasteSpecial xlPasteValues
TransOutWb.Close
TermWb.Close
VLOOKUP awaits an address of a range as second parameter.
.Formula = "=VLOOKUP(B:B," & x.Address(External:=True) & ",3,0)"
In your case "=VLOOKUP(B:B,x,3,0)" the x is not recognized as variable because it is within a string. Also you need to fill in the address in here (in external format so that the different workbook gets recognized too). Also see Range.Address Property (Excel) for info.
Also declare the variables to make sure the are of type range: Dim x As Range, x2 As Range at the top of your procedure.
OptioneeManWb.Sheets("manual optionee stmt").Range("C6:C" & lastrow2).Formula = "=VLOOKUP(B:B," & x.Address(External:=True) & ",3,0)"
OptioneeManWb.Sheets("manual optionee stmt").Range("D6:D" & lastrow2).Formula = "=VLOOKUP(B:B," & x2.Address(External:=True) & ",3,0)"
First You have to declare the variables x and x2 like this way :
Dim x as range
Dim x2 as range

Excel VBA - Import from a file in the same folder with an arbitrary name but a specific number at the end

I want to be able to import data from a file in the same folder, but it doesn't matter what it's called, but the number at the end does. Currently i have
Sub Import_Data()
Dim rng As Range
Dim WB2 As Workbook
Dim FName As String
Dim c1 As Worksheet
Set c1 = Sheets("c")
FName = Application.ActiveWorkbook.Path + "_w" & Format((WorksheetFunction.WeekNum(Now) - 1), "00")
Set WB2 = Workbooks.Open(Filename:=FName)
c1.Range("L2:O6").Value = WB2.Worksheets(3).Range("M2:P6").Value
c1.Range("L14:O18").Value = WB2.Worksheets(3).Range("M14:P18").Value
WB2.Close
End Sub
I want to change the following line from
FName = Application.ActiveWorkbook.Path + "_w" & Format((WorksheetFunction.WeekNum(Now) - 1), "00")
To something like
FName = Application.ActiveWorkbook.Path + *Any Name before the last 2 digits* & Format((WorksheetFunction.WeekNum(Now) - 1), "00")
So it will basically not look at the name of the sheet but will look at the 2 digits at the end.
The week numbers will always be unique in the folder but the names might be different. E.g
Folder may contain the following files:
Worksheet 1 w21
Different Name w22
Alternate w23
If we are in w24, i'd like it to import from "Alternate w23"
I hope this makes sense. Thanks
EDIT - Alternative
If this isn't possible, It would also work if the previous weeks file had the same name as the current file. So if the active workbook was called "Workbook w23" Then it would find "Workbook w22" in the same folder. But it would need to be possible to generalise the name of the sheet. So instead of the original suggestion of Any Name before the last 2 digits it would be The same name as the active workbook with 2 different digits at the end
If I'm interpreting your question right, you just need a wildcard:
FName = Dir(Application.ActiveWorkbook.Path & "\*w" & Format((WorksheetFunction.WeekNum(Now) - 1), "00") & ".xlsm")

How to solve mixed date formats

I'm trying to write VBA code in Excel 2010 to make some time calculations. Everything is working as I want BUT for the cell date format. The Excel Sheets were created by merging several .xlsx files generated by different PCs and a Hardware Data-logger. The problem is that some sheets had the date as mm/dd/yy hh:mm:ss AM/PM and others dd/mm/yy hh:mm:ss AM/PM, with both mixed in one file.
I tried to change everything to Selection.NumberFormat = "dd/mm/yy hh:mm;#" but some cells just don't change. I also tried this function:
Function Arreglar_Fecha()
Dim temp As String
temp = ""
Do While ActiveCell.Value <> ""
temp = ActiveCell.Value
ActiveCell.Value = Day(temp) & "/" & Month(temp) & "/" & Year(temp) & " " & Hour(temp) & ":" & Minute(temp)
ActiveCell.Offset(1, 0).Select
Loop
End Function
But still, some cells changed, some did not. And what is worse, some get the day and month mixed!
I have access to some of the original .xlsx files and in there also wasn't able to change all the date formats.
Anyone have any idea how I can fix this?
EDIT Here I got permission for put an original Excel file Excel Data.
You will have to trace back to your source data. There is no way Excel itself knows whether 1/2/2014 for example should be the first of February or the second of January, only that it is either 41671 or 41641.
Edit In your second example, clearly 28/9/2013 17:59 is September 28. If 10/01/13 12:11:00 PM had the same formatting (perhaps came from the same file) then it is January 10. But if the formatting was different then it could be October 1. If you are seeing AMs and PMs with formatting as dd/mm/yy hh:mm;# then some of your data is text and there is no reliable 'automatic' way to switch this to a date/time serial number without knowing the text convention (ie whether DMY or MDY), hence the need to revert to source.
Obviously 'day' values greater than 12 are actually months but that does not help much when for less than 13 it depends upon the formatting.
In addition, given your various sources, there is a risk that both the 1900 and the 1904 conventions might have been used and even possibly others also (your data logger might be on UNIX time, which starts in 1970).
ActiveCell.Value = Day(temp) & "/" & Month(temp) & "/" & Year(temp) & " " & Hour(temp) & ":" & Minute(temp)
Maybe the code is reading it as text? Try this (UNTESTED)
Sub Arreglar_Fecha()
Dim temp As String, Tmp As String
Dim D As String, M As String, Y As String
Dim H As String, Mn As String
Do While ActiveCell.Value <> ""
temp = Trim(ActiveCell.Value)
D = Trim(Split(temp, "/")(0))
M = Trim(Split(temp, "/")(1))
Tmp = Trim(Split(temp, "/")(2))
Y = Trim(Split(Tmp, " ")(0))
Tmp = Trim(Split(Tmp, " ")(1))
H = Trim(Split(Tmp, ":")(0))
Mn = Trim(Split(Tmp, ":")(1))
ActiveCell.Value = Format(DateSerial(Val(Y), Val(M), Val(D)) & _
" " & TimeSerial(Val(H), Val(Mn), 0), _
"dd/mm/yy hh:mm;#")
ActiveCell.Offset(1, 0).Select
Loop
End Sub
Trying it with a single test scenario works. The below gives you 13/08/13 05:31
Sub Test()
Dim temp As String, Tmp As String
Dim D As String, M As String, Y As String
Dim H As String, Mn As String
temp = "13/8/2013 5:31"
D = Trim(Split(temp, "/")(0))
M = Trim(Split(temp, "/")(1))
Tmp = Trim(Split(temp, "/")(2))
Y = Trim(Split(Tmp, " ")(0))
Tmp = Trim(Split(Tmp, " ")(1))
H = Trim(Split(Tmp, ":")(0))
Mn = Trim(Split(Tmp, ":")(1))
Debug.Print Format(DateSerial(Val(Y), Val(M), Val(D)) & _
" " & TimeSerial(Val(H), Val(Mn), 0), _
"dd/mm/yy hh:mm;#")
End Sub

Using VLookup in a macro

I'm new to VBA but I'm hooked! I've created a workbook that tracks overtime in 2 week blocks with one 2-week block per worksheet. The macro I'm trying to debug is designed to carry any changes made in a worksheet over to following worksheets. The trick is that the data in one row may be in a different row in following worksheets so I trying to use VLookup in a macro to keep it accurate.
Sub CarryForward()
Dim Answer As String
Answer = MsgBox("This should only be used for a PERMANENT crew change." & vbNewLine & "If you are adding a new person to the list," & vbNewLine & "please use the Re-Sort function." & vbNewLine & "Do you want to continue?", vbExclamation + vbYesNo, "Caution!")
If Answer = vbNo Then
Exit Sub
End If
Application.ScreenUpdating = False
Dim ActiveWorksheet As String
ActiveWorksheet = ActiveSheet.Name
For i = (ActiveSheet.Index + 1) To Sheets("DATA").Index - 1
For x = 5 To 25
Dim a As String
Dim b As String
a = "B" & x
b = "C" & x
ActiveSheet.Range(b).Value = Application.WorksheetFunction.VLookup(a, Sheets(ActiveWorksheet).Range("B5:C25"), 2, False)
Next x
Range("A3").Select
Next i
Sheets(ActiveWorksheet).Select
Application.CutCopyMode = False
Range("A3").Select
Application.ScreenUpdating = True
End Sub
I'm pretty sure it's just a syntax error in the VLookup line of code. A lot of the help posted comes close to what I'm looking for, it just doesn't get me over the finish line.
Any help would be appreciated!
It is a little unclear what you are trying to do, but reading between the lines I think
you want to lookup the value contained in cell named by a?
and put the result on sheet index i?
Also, there is a lot of opportunity to improve your code: see imbedded comments below
Sub CarryForward()
Dim Answer As VbMsgBoxResult ' <-- Correct Datatype
Answer = MsgBox("This should only be used for a PERMANENT crew change." & vbNewLine & _
"If you are adding a new person to the list," & vbNewLine & _
"please use the Re-Sort function." & vbNewLine & _
"Do you want to continue?", _
vbExclamation + vbYesNo, "Caution!")
If Answer = vbNo Then
Exit Sub
End If
Application.ScreenUpdating = False
' Dim ActiveWorksheet As String <-- Don't need this
'ActiveWorksheet = ActiveSheet.Name <-- use object variables
Dim wbActive As Workbook ' <-- don't select, use variables for sheet objects
Dim shActive As Worksheet
Set wbActive = ActiveWorkbook
Set shActive = ActiveSheet
'Dim a As String ' <-- no point in putting these inside the loop in VBA. And don't need these anyway
'Dim b As String
Dim SearchRange As Range
Set SearchRange = shActive.Range("B5:C25") ' <-- Use variable to hold range
Dim shDest As Worksheet
Dim i As Long, x As Long '<-- dim all your variables
For i = (shActive.Index + 1) To wbActive.Worksheets("DATA").Index - 1 ' <-- qualify references
Set shDest = wbActive.Sheets(i)
For x = 5 To 25
'a = "B" & x <-- no need to create cell names
'b = "C" & x
' I think you want to lookup the value contained in cell named by a?
' and put the result on sheet index i?
' Note: if value is not found, this will return N/A. Add an error handler
wbActive.Sheets(i).Cells(x, 3).Value = Application.VLookup(shActive.Cells(x, 2).Value, SearchRange, 2, False)
Next x
'Range("A3").Select
Next i
'Sheets(ActiveWorksheet).Select ,-- don't need these
'Application.CutCopyMode = False
'Range("A3").Select
Application.ScreenUpdating = True
End Sub
I suspect you would want to replace the vlookup statement to be something like
Application.WorksheetFunction.VLookup(ActiveWorksheet.Range(a).value, ActiveWorksheet.Range("B5:C25"), 2, False)
at the moment it looks like you're just doing a vlookup against some strings B5, B6, B7 etc instead of values in those cells