Retain formatting on a used value - excel

There are two sheets, one containing columns with date ranges ("Test" sheet), the other containing payment amounts with specific dates ("Payment information" sheet).
I wrote code, that goes line by line in the second sheet and checks if the date falls between a date range in the first based on supplier values existing in both sheets.
Where I am stuck:
Payment amounts contain formatting for currencies e.g. €, $ or different. If I use something like the code below - it retains the formatting, however: the same cell in "Test" sheet, might have to have the sum of multiple lines from "Payment information" and copy pasting replaces the values.
ThisWorkbook.Sheets("Payment information").Cells(i, "F").Copy
ThisWorkbook.Sheets("Test").Cells(last_row, j).PasteSpecial xlPasteValuesAndNumberFormats
If alternatively I use the code below - the formatting drops off:
payment_amount = ThisWorkbook.Sheets("Payment information").Cells(i, "F")
ThisWorkbook.Sheets("Test").Cells(last_row, j).value = ThisWorkbook.Sheets("Test").Cells(last_row, j).value + payment_amount

From what I understand, you can do a PasteSpecial xlformats to just copy those.
So going from
Range("A1").Copy
Range("A2").PasteSpecial xlFormats
On your example:
ThisWorkbook.Sheets("Payment information").Cells(i, "F").Copy
ThisWorkbook.Sheets("Test").Cells(last_row, j).PasteSpecial xlFormats
Adding from your comment below, you should use a variable that adds value when it meets conditions.
For example
Dim payment as Integer
Select case Range("A2").Value
Case #1/1/2022# To #12/31/2022#
payment = payment + Range("A2")
Case else
payment = Range("A2").Value
So the code goes like this: If it happens to be in 2022, it adds the value to your variable.
If it's not in 2022, it copies the value
You then can paste/show the value in your desired range, like:
Range("A2").Value = payment
Combining it with an iteration to check dates and it should work.
Hope it helps!

Related

VBA Copy/Paste a Range in Next Available Column Then Add a Single Day to One of the Newly Pasted Cells Repeatedly

I'm trying to create a button with an attached macro that will copy a range with formulas and data, then paste it to the next available column, and finally add one day to one specific cell. The problem I'm having is that I want to do it over and over, with the each new pasted cell adding one date from the previously pasted one. The idea is that I click the button, it pastes the orginal range plus one day added to that specific cell, then I can add data to that new pasted block, then click the button and get a new pasted block with the next specific cell having one day added to it.
So far I have this:
Sub PasteToNextEmptyColumn()
Application.ScreenUpdating = False
Range("A4:C14").Copy
ActiveSheet.Cells(4, Columns.Count).End(xlToLeft).Offset(0, 1).PasteSpecial xlPasteColumnWidths
ActiveSheet.Cells(4, Columns.Count).End(xlToLeft).Offset(0, 1).PasteSpecial xlPasteAll
Range("E9").Value = DateAdd("d", 1, (Range("E9")))
Application.CutCopyMode = False
Application.ScreenUpdating = True
End Sub
I'm a little unsure on what you're trying to accomplish, but if this helps.
With a date you can treat it like a value and just put:
Range("E9") = Range("E9") + 1 ' this will input the date in the same cell E9
Maybe ensure the date is inn DD/MM/YYYY or another recognised format.
It seems as though the pasting is correct, if you wanted the date to be input alongside the new data added that is a little different using the last column formula you've already used.

Getting Excel to Copy Data From One Cell to Another Depending on Date

Apologies in advance as this is my first time posting something on this site and am not the best at explain issues.
I have a spread sheet, this has production data such as meters daily, meters monthly etc. These values are updated by adding TAGS from a PLC using Rockwell VantagePoint Excel add-in (if your unfamiliar with this it shouldn't matter this part is not what I am struggling with)
I need I way to copy data from one cell to another cell on the same sheet at month end. Basically the Meters monthly field needs to copied into another cell at the end of the month to record meters run for that month. The monthly meters run resets back to 0 at the end of the month.
Basically I need to copy the value in J7 into the corresponding month in W column at the end of that month. If it could ignore the year that would be advantageous as I don't need it to keep the old values and would mean I just need one column.
I have some experience at MS-Excel, also VBA but mainly in MS-Access never in MS-Excel. If answers could be explained as simply and hands on as possible it would be appreciated.
After Googling the issue I came across this formula and changed the ranges to fit my sheet but Excel doesn't like it saying it contains an error
=QUERY( A1:B6; "select B where A =date """&TEXT(TODAY();"yyyy-mm-dd")&""" "; 0
Sorry again if I haven't explained myself properly.
If your workbook isn't guaranteed to be open at the end of each month I would update the value every time it gets opened, like(Should be placed in ThisWorkbook):
'Runs when you open the workbook
Private Sub Workbook_Open()
'Loops through U3 to the last used cell in that column
For Each c In Range(Cells(3, 21), Cells(Rows.Count, 21).End(xlUp))
'Applies the J7 value to the current month and exits the sub
If Month(c) = Month(Now) Then c.Offset(, 2).Value = [J7]: Exit Sub
Next c
End Sub
Also, not that it matters but, I would apply the following formula in U3:U14 to always get the correct dates:
=EOMONTH(DATE(YEAR(TODAY()),ROW()-2,15),0)
Okay, I'm still not super sure what the question is and I know more Access VBA than Excel VBA, but here's something that might help to find a solution.
You can make a check date function that returns a Boolean value:
Public Function EoMonthCheck() As Boolean
Dim eo_month As Date, today As Date
eo_month = Format(WorksheetFunction.EoMonth(Now(), 0), "yyyy-MM-dd")
today = Format(Now(), "yyyy-MM-dd")
If today = eo_month Then
EoMonthCheck = True
Else
EoMonthCheck = False
End If
End Function
And the,, to add a value to the "W" column, we might use something like this:
Public Function AppendValue(Optional target_cell As String = "J7")
''' This could be a subroutine, too, I guess, since we're not returning anything.
Dim i As Integer
''' Activate whatever sheet you want to work with
Worksheets("Sheet1").Activate
If EoMonthCheck() = True Then
''' Look up the bottom of the 'W' column and find the first non-empty cell
''' Add 1 to that cell to get you to the next cell (the first empty one).
i = Cells(Rows.Count, "W").End(xlUp).Row + 1
''' Set the value of that empty cell in the 'W' column to the value of 'J7'
''' which will happen after we evaluate whether it is the end of the month.
Cells(i, "W").Value = Range(target_cell).Value
End If
Then, you could maybe trigger that each time the workbook opens.

How to resolve #NAME? error in VBA when attempting to set a cell value using a variable in the function

I am building a simple macro named Update for a form control button in excel. When the button is pressed, I want a vlookup to execute in the button's sheet (named "Checker"), against the $B$7:$E$1048576 range in another sheet named "All Account Log" within the same workbook.
This vlookup formula should populate in rows 5-105 in column 5 ("E") of Checker, and for each respective row should take an input from column B to check against All Account Log's range. Here is the code I have so far:
Sub Update()
Dim Month As String
Dim i As Integer
Month = Cells(2, 2).Value
For i = 5 To 105
Cells(i, 5).Value = "=IFERROR(VLOOKUP($B" & i & ",'All Account Log'!$B$7:$E$1048576,4,0)," & Month & ")"
Next i
End Sub
If the vlookup is successful, the formula in each row of column E should pull back the respective column's data. If the vlookup does not find a match, the formula should copy the value from Cell(2,2), which is a string input by the user - a month's name. When I run the macro, the vlookup does what I want, however, when it does not find a match, the resulting formulae read "#NAME?". What can I do to fix this? I have a feeling there is some syntactical issue with how my formula references the Month variable (the value of Cell(2,2)), but I cannot figure out what the error is.
After running the macro and clicking on one of the cells with the #NAME? result, the formula in the formula bar reads:
=IFERROR(VLOOKUP($B5,'All Account Log'!$B$7:$E$1048576,4,0),Jan)
Here I have the input "Jan" as the Month name, so I expect the result to be "Jan" rather than "#NAME?" Your thoughts are appreciated!
You really want:
=IFERROR(VLOOKUP($B5,'All Account Log'!$B$7:$E$1048576,4,0),"Jan")
instead of:
=IFERROR(VLOOKUP($B5,'All Account Log'!$B$7:$E$1048576,4,0),Jan)
so use:
Month = """" & Cells(2, 2).Value & """"
in the VBA code.

Excel: Working around sorting tables by date, with empty rows in the range

I am working on a model that requires me to sort data in a range by date, before copying the data into a different template on another sheet. Every row has a formula that pulls data from Bloomberg, so even if the cell looks empty, excel recognizes that there is content in the cell. Sorting the date column as it is does not work, as excel wont recognize the data that Bloomberg pulls as a date, so it would be sorted from A to Z, which scrambles the dates instead.
To work around this, I inserted and adjacent column with the formula (using cell A1 as an example) "=(A1+0)" that then allows the column to be sorted from new to old. The problem here is that if cell A1 does not display a date (in other words, it appears empty yet the cell contains a formula that leaves the cell looking empty if no date is pulled) it returns a #VALUE! error and sorting new to old would put the errors at the top (Thank you Excel for this fantastic feature, btw).
To work around this new issue, I replaced the above formula in the cell with "=IFERROR(A1+0,1)" which gives me the date 1/1/1900. Fine, now the data is sorted in the manner I want it, but I have a bunch of ancient dates that just make my end product look ugly.
I have two questions, first; how can I use VBA to delete the data in the cells where the date equals 1 (which shows the date 1/1/1900), and only those cells? Or, alternatively, only copying the rows above the cell that contains 1/1/1900. This is a relatively small amount of cells that would be affected by this, 40 at most.
Second; is there a different way of sorting the data using VBA that I am missing, that might be more efficient?
Try this macro, I tried to test it with as many anomalies as possible.
Sub SortByDateColumnH()
Dim r As Range: Set r = Sheet1.Range("B3:P40")
Dim cel As Range
For Each cel In r.Columns(7).Cells
If IsError(cel.Value) Then
cel.Value = 0
ElseIf Not IsDate(cel.Value) Then
cel.Value = 0
Else
cel.Value = CLng(cel.Value)
End If
Next
r.Columns(7).NumberFormat = "0"
r.Sort Key1:=r.Cells(1, 7), Order1:=xlDescending, Header:=xlNo
For Each cel In r.Columns(7).Cells
If cel.Value < 100 Then cel.ClearContents
Next
r.Columns(7).NumberFormat = "m/d/yyyy" '<-- set the format to your preference
'r.Copy Destination:=someDestination ' you can copy the range by code if needed
End Sub

VBA User Form - Need it to copy formula from column F, 1 row above

I have a form I made for users to enter data. The data get's inserted into the next available row. That works well, but now I need the formula from the cell above in Column F to be copied into the new cell. Is there a code I could use this to work along with the copying of the input values to the sheet?
Any help with this would be greatly appreciated.
Edit: Method 2 is probably better suited for your purpose as it will adapt the cell references in the previous line to the next line.
Method 1: To set the formula of a cell, use
Sheets("sheet name").cells(row, column).Formula = ....
Row and column must be specified as integer values, I.e. For column F it would be 6. Assuming you have the number of the next free line in a variable called NextFreeLine:
Sheets("sheet name").cells(NextFreeLine, 6).Formula = Sheets("sheet name").cells(NextFreeLine-1, 6).Formula
Method 2: If you insist on literally copying the formula from somewhere else, try this (this will adapt the cell references of the formula for the previous line to the next one-- just like copy/pasting it using Ctrl-C, Ctrl-V):
Sheets("sheet name").cells(NextFreeLine-1, 6).Copy
Sheets("sheet name").cells(NextFreeLine, 6).PasteSpecial Paste:=xlPasteFormulas
The method you are using to put into 'the next available row' would have been nice to see but perhaps you can translate this for your own purposes.
'put the newval into the next available cell in column A
cells(rows.count, 1).end(xlup).offset(1, 0) = newval
'copy the formula in column F to the new row
cells(rows.count, 1).end(xlup).offset(-1, 5).resize(2, 1).filldown
Your value goes into the next available row based on column A. The same column is used in much the same manner but offset up a row and resized to two rows in height before executing the fill down command.

Resources