VBA, Updating link to other workbook in formula daily - excel

I am very new to VBA programming and have an issue.
I have a base file called liquidity forecast in which I fill data from other documents in. The documents I collect data from is updated every day so the date in the name changes every day.
The Name goes "(Date, "YYMMDD") & "SE_Laizy.xlsx" so an example would be, 160229SE_Laizy.xlsx
When I collect data I use Index match formula. My problem is trying to update the link within the formula by using a date value.
Currently I write it like this,
ActiveCell.Range((Cells(1, 1)), (Cells(1, 1))).FormulaR1C1 = _
"=INDEX('[" & Format(Date, "YYMMDD") & "SE_Laizy.xlsx"]Visa'!R1:R1048576,MATCH(R2C,'[" & Format(Date, "YYMMDD") & "SE_Laizy.xlsx"]Visa'!C1,0),MATCH(""Ub perioden"",'[" & Format(Date, "YYMMDD") & "SE_Laizy.xlsx"]Visa'!R2,0))"
All I get from this is a NA. Any help would be appreciated!

I've added a parent worksheet reference and broken the INDEX and
MATCH functions into the three primary sections.
With Worksheets("Sheet2")
.Cells(1, 1).FormulaR1C1 = _
"=INDEX('[" & Format(Date, "YYMMDD") & "SE_Laizy.xlsx]Visa'!C1:C16384, " & _
"MATCH(R2C,'[" & Format(Date, "YYMMDD") & "SE_Laizy.xlsx]Visa'!C1, 0), " & _
"MATCH(""Ub perioden"", '[" & Format(Date, "YYMMDD") & "SE_Laizy.xlsx]Visa'!R2, 0))"
End With
As noted, there were some misplaced quotes in the external workbook name. I'm not sure what to do with your Range object definition. For all intents and purposes, the one supplied simply resolves down to [A1].

Related

VBA Data pasting in wrong cells sometimes

I am attempting to write a macro that:
Iterates over a list of employee IDs, identifies whether it needs a report generated or not then, filters a large dataset to include only that employee, grab several different columns, and paste them into a formatted sheet. It will then copy that sheet and save it into a file directory as a binary file.
The code works as expected sometimes, but other times, it seems to be pasting the all the data in a different row (it varies, but is usually between rows 8800 and 9200). I want it to paste in Row 2. The only clue that I have found to indicate the cause is that column S, where Gross Margin is stored, seems to have a couple hundred rows of data above where the table starts (only in some cases though). All data is still lining up in the correct rows.
Sub SplitFile()
Application.DisplayAlerts = False
Set wb = Application.ActiveWorkbook
Set pivots = wb.Sheets("Pivots")
Set repository = wb.Sheets("Repository")
Set listing = wb.Sheets("Customer Listing")
For Each rep In pivots.Range("A4:A" & pivots.Range("A3").End(xlDown).Row)
If rep.Offset(0, 1) <> "" Then
Debug.Print rep
lastRow = repository.Range("A1").End(xlDown).Row
repName = rep.Offset(0, 1).Value
repDistrict = rep.Offset(0, 2).Value
folderPath = pivots.Range("B1").Value & "\" & repDistrict
repository.Range("A1:AU" & lastRow).AutoFilter Field:=33, Criteria1:=rep
'EEID and Name
repository.Range("AG2:AH" & lastRow).SpecialCells(xlCellTypeVisible).Copy listing.Range("A2")
'Source
repository.Range("F2:F" & lastRow).SpecialCells(xlCellTypeVisible).Copy listing.Range("C2")
'Cust ID
repository.Range("H2:H" & lastRow).SpecialCells(xlCellTypeVisible).Copy listing.Range("D2")
'Cust Name
repository.Range("K2:K" & lastRow).SpecialCells(xlCellTypeVisible).Copy listing.Range("E2")
'Address Details
repository.Range("S2:U" & lastRow).SpecialCells(xlCellTypeVisible).Copy listing.Range("F2")
'Predominant Trade, Active/Inactive, Start Date
repository.Range("W2:Y" & lastRow).SpecialCells(xlCellTypeVisible).Copy listing.Range("I2")
'Region & District
repository.Range("AA2:AB" & lastRow).SpecialCells(xlCellTypeVisible).Copy listing.Range("L2")
'Pay Terms
repository.Range("AQ2:AQ" & lastRow).SpecialCells(xlCellTypeVisible).Copy listing.Range("N2")
'Revenue and Margin
repository.Range("L2:M" & lastRow).SpecialCells(xlCellTypeVisible).Copy listing.Range("O2")
repository.Range("N2:N" & lastRow).SpecialCells(xlCellTypeVisible).Copy listing.Range("R2")
repository.Range("O2:O" & lastRow).SpecialCells(xlCellTypeVisible).Copy listing.Range("S2") 'my guess is this is about where the problem is.
'Sort Data
listing.Columns("A:W").Sort key1:=listing.Range("P1"), order1:=xlDescending, Header:=xlYes
'Formulas
lastListingRow = listing.Cells(1000000, 1).End(xlUp).Row
listing.Range("Q2:Q" & lastListingRow).Formula = "=IFERROR(P2/O2,"""")"
listing.Range("T2:T" & lastListingRow).Formula = "=IFERROR(S2/R2,"""")"
listing.Range("U2:V" & lastListingRow).Formula = "=IFERROR(O2-R2,"""")"
listing.Range("W2:W" & lastListingRow).Formula = "=IFERROR(ROUND((Q2-T2)*10000,0),"""")"
'Paste formulas
'lastListingRow = listing.Cells(1000000, 1).End(xlUp).Row
'listing.Range("Q2").Copy listing.Range("Q3:Q" & listingLastRow)
'listing.Range("Q2").Copy listing.Range("T3:T" & listingLastRow)
'listing.Range("U2").Copy listing.Range("U3:V" & listingLastRow)
'listing.Range("W2").Copy listing.Range("W3:W" & listingLastRow)
If Dir(folderPath, vbDirectory) = "" Then
MkDir (folderPath)
End If
listing.Copy
Set newWb = Application.ActiveWorkbook
newWb.SaveAs folderPath & "\" & repDistrict & "-" & rep & "-" & repName & "-" & pivots.Range("H1"), FileFormat:=50
newWb.Close
listing.Range("A2:R9000").Value = ""
repository.ShowAllData
End If
Next
End Sub
I am not using option explicit as I tend to code mostly in python and have grown used to "duck typing".
I'd appreciate any help, and can clarify if you need it. I've never run into this problem before, but I've written several programs like it.
I don't know why this occurred, but I fixed it by replacing listing.Range("A2:R9000").Value = "" with listing.Rows("2:100000").delete.

Prior Workday Dynamic Reference Within VLookUp Formula - VBA

I am somewhat of a noob when it comes to VBA programming. I am running a macro script daily on each day's distinct tab title MM-DD-YY. I want to do a vlookup on today's date using the lookup range from the prior business day. For instance, if today is 07/31/20 I want the vlookup to be VLOOKUP(Q7, '07-30-20'!$P$1:$Q$29, 2, FALSE). How do you code this to automatically populate the vlookup using the prior business day? Below is the noob code I have at this point.
Range("Q2").Select
ActiveCell.FormulaR1C1 = "=VLOOKUP(Q7, '07-29-20'!$P$1:$Q$29, 2, FALSE)"
Selection.AutoFill Destination:=Range("Q2:Q" & Range("E" & Rows.Count).End(xlUp).Row)
Try:
ActiveCell.FormulaR1C1 = "=VLOOKUP(Q7,'" & Right("0" & Month(Date), 2) & "-" & Right("0" & Day(Date), 2) - 1 & "-" & Right(Year(Date), 2) & "'!$P$1:$Q$29, 2, FALSE)"
You could do something like:
Dim dprevDate As Date, sprevDate As String
dprevDate = WorksheetFunction.WorkDay(Date, -1)
sprevDate = Format(dprevDate, "mm-dd-yy")
ActiveCell.Formula = "=VLOOKUP(Q7, '" & sprevDate & "'!$P$1:$Q$29, 2, FALSE)"

vba Sumif with variables and R1C1

I'm trying to run the below code and it gives me
Run-Time Error "1004"
Application-defined or Object-defined error
Every Single Time!!
Attached is a snippet of the code, any suggestions what's wrong? (The numbers in the Range(Cells( * ) sections are actually mostly variables in my overall macro, it's pretty complex but I've taken them out for simplicity here)
Code:
'Declare variables
Dim CriteriaRng As String
Dim SumRng As String
Dim Criteria As String
'Set a variable for each of the 3 parts of the SUMIF Formula
CriteriaRng = "'" & Sheets(1).Name & "'!" & Range(Cells(2, 4), Cells(88, 4)).Address
SumRng = "'" & Sheets(1).Name & "'!" & Range(Cells(2, 3), Cells(88, 3)).Address
Criteria = Chr(34) & "=" & Chr(34) & " & RC[-1]"
'Here goes the SUMIF Formula
With Sheets(2).Range(Cells(4, 13), Cells(9, 13))
Debug.Print "So the Whole Formula Should be:" & Chr(13) & "= SUMIF(" & CriteriaRng & ", " & Criteria & ", " & SumRng & ")"
'That was a vain attempt to find out what was wrong with the formula; didn't work though.
.FormulaR1C1 = "= SUMIF(" & CriteriaRng & ", " & Criteria & "," & SumRng & ")"
'Then adds NumberFormat and stuff here, but that isn't relevant to this question.
End With
The error always hits on the line where it's putting in the .FormulaR1C1 = .
Yes, I know I could get the same result using a nested loop, but that would return just the value without the SUMIF formula - I need that formula so the sheet updates when edited (without needing a macro - I'm sending the sheet on to other people who won't have or want any macros, but might need to edit the data).
Can anyone point out to me what is wrong? I'm prepared for it to be something pretty basic - only last week I spent 2 hours figuring out a problem from misspelling 'Columns' !!!
Any and all advice welcome - Many Thanks in advance.

Application-defined or object-defined error when using .formula

I've been struggling to get a formula typed into a cell on a sheet. it's my activesheet (definitely).
Source is a file with full path. the sheet name is ... and lta_col_letter is the column letter I'm typing the formula into.
ActiveSheet.Range(lta_col_letter & 2).Formula = "=IFERROR(INDEX('[" & Source & "]...'!$G:$G,MATCH(" & versionref_col_letter & "2,'[" & Source & "]...'!$B:$B,0))," & Chr(34) & Chr(34) & ")"
I'm not sure why I'm getting this error. Help please!
EDIT:
Works when I added the missing [ brackets, but when it goes into the cell it adds the file name again after the sheet name and before the cell reference.It looks fine in a msgbox.
Looks like you are missing some opening square brackets around source.
ActiveSheet.Range(lta_col_letter & 2).Formula = "=IFERROR(INDEX('[" & source & "]...'!$G:$G,MATCH(" & versionref_col_letter & "2,'[" & source & "]...'!$B:$B,0)), text(,))"
To examine these types of errors, put a ' before the opening = and run the procedure to put the formula into the cell as a string. Go to the worksheet and perform a visual examination and try to remove the '. Make corrections until you have a working formula then transfer the corrections to the VBA formula string.
Since it seems that you have used an open workbook to retrieve the workbook name into source, you might consider using the Range.Address Property with External:=True to retrieve a fully punctuated external address.
dim sourceG as string, sourceB as string
sourceG = workbooks(source).worksheets("...").range("G:G").address(external:=true)
sourceB = workbooks(source).worksheets("...").range("B:B").address(external:=true)
ActiveSheet.Range(lta_col_letter & 2).Formula = _
"=IFERROR(INDEX(" & sourceG & ", MATCH(" & versionref_col_letter & "2, " & sourceB
& ",0)), text(,))"

Assigning cell value from another workbook to my code

Basically what I want to achieve is assigning the cell value from the other workbook into my code.
Customers send in a spreadsheet of goods they want to order and this spreadsheet is used for more than one purpose so it has many columns which are not needed for my purpose.
So I created the macro to look up and give me the value from certain columns and spit out a CSV file.
I then created a spreadsheet of my own with the column values all mapped out, I am trying to get the coding to lookup the cell value in my spreadsheet and knows which columns to be looking up on the customer spreadsheet.
I want it so I can just go in and change the values in the cells on
my spreadsheet instead of having to go into the coding and change the
columns value in my code.
ShipToSiteID = Application.WorksheetFunction.Trim(Range("Q" & counter))
AltShipTo1 = Application.WorksheetFunction.Trim(Range("G" & counter))
AltShipTo2 = Application.WorksheetFunction.Trim(Range("H" & counter))
AltShipToCity = Application.WorksheetFunction.Trim(Range("I" & counter))
'AltShipToState = Application.WorksheetFunction.Trim(Range("I" & counter))
AltShipToZip = Application.WorksheetFunction.Trim(Range("J" & counter))
AltShipToCountry = "UNITED KINGDOM"
RefNumber = counter - 1
UserId = LCase(Environ("username"))
ShipToSiteID = Replace(ShipToSiteID + AltShipToZip, " ", "")
Sheets(2).Select
Range("A" & counter - 1) = LineType & comma & RefNumber & comma & QName & comma & BlanketID _
& comma & BillToSiteID & comma & ShipToSiteID & comma & ContractID _
& comma & PONumber & comma & CaseID & comma & ShipVia & comma & RequiredDate _
& comma & Comments & comma & Priority & comma & TerminalID & comma _
& AltContactFirst & comma & AltContactLast & comma & AltPhone & comma _
& AltShipTo1 & comma & AltShipTo2 & comma & AltShipToCity & comma _
& AltShipToState & comma & AltShipToZip & comma & AltShipToCountry _
& comma & UserId & comma
A few suggestions...
To reference a value in workbook2 on workbook1, the easiest way to do this would be to copy the worksheet from workbook2 to workbook1. Then you can reference the value by typing "=" in the cell, and clicking on the cell that you want to reference.
Referencing in VBA code gives you some more flexibility. I'd suggest checking this good SO question and this one for more info. This may be more along the lines of what you want.
Unfortunately, if you reference a value from workbook2 on workbook1, there is no easy way to change the value of workbook2 from workbook1.

Resources