Quantcast
Channel: Active questions tagged excel - Stack Overflow
Viewing all 88206 articles
Browse latest View live

Excel VBA - paste text from clipboard (error 1004)

$
0
0

can someone help me with this code?

Sub TEST()
Dim Val As Variant
Sheets("Sheet 3").Select
Val = Range("A2").Value
Sheets("Sheet 1").Select
Range("AY"& Val).Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
    :=False, Transpose:=False
Sheets("Sheet 3").Select
Application.CutCopyMode = False
End Sub

I have to transfer simple number from web to excel. I need to copy number from web into a clipboard, then go to excel and run Macro. This macro should go to "sheet 3" set "Val" based on A2 value, go to sheet 1, select range in AY & "Val" and paste to this cell data (the number) from clipboard.

But when macro reach line 7 (Selection.PasteSpecial) Im getting Error:

Run-time error '1004': PasteSpecial method of Range class failed

Where I have the bug, please :)


Export specific column values in excel to datagrid using VB.Net

$
0
0

How to export particular column values which does not have header to datagrid

...

dta = New OleDbDataAdapter("Select * from [linexcel$])

...

How can I specify the column(column B and D) instead of '*'. It does not have constant header.

...

'DocumentFormat.OpenXml.Spreadsheet.WorksheetExtensionList' from assembly 'DocumentFormat.OpenXml

$
0
0

i have a got the this error

'DocumentFormat.OpenXml.Spreadsheet.WorksheetExtensionList' from assembly 'DocumentFormat.OpenXml, Version=2.5.4728.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'.

i have used this code in below

private void button1_Click(object sender, EventArgs e)
    {
        XLWorkbook workbook = new XLWorkbook();
        IXLWorksheet worksheet = workbook.Worksheets.Add("Sample Sheet");
        worksheet.Cell("A1").Value = "Hello World!";
        string folderPath = "C:\\User\\test\\Desktop\\";
        if (!Directory.Exists(folderPath))
        {
            Directory.CreateDirectory(folderPath);
        }
        workbook.SaveAs(folderPath + "sanjay.xlsx");

    }

i have simple create the test project and i am using the ClosedXml and simple project will run then button click then open excel file just simple any body help me

Advance thank you
Mr.Malakiya

Reading from an Excel (xlsx) file using Apache POI library throws NullPointerException

$
0
0

I 'm building a JSP web application using Eclipse IDE. The web application loads without issue on tomcat server ver 7. We got a new requirement to read from xls and xlsx file. So we have used Apache POI library (4.1.2) to implement this as follows: I have taken out other codes as they are not relevant for this post

FileInputStream file = new FileInputStream(new File(args[0]));

        //Create Workbook instance holding reference to .xlsx file
        XSSFWorkbook workbook = new XSSFWorkbook(file); //<- This is where the exception occurs

        //Get first/desired sheet from the workbook
        XSSFSheet sheet = workbook.getSheetAt(0);

        //Iterate through each rows one by one
        Iterator<Row> rowIterator = sheet.iterator();

But when executing we are getting the below exception. I have tried googling but didn't find relevant help. Can you please assist?

SEVERE: Servlet.service() for servlet [UploadEstimates] in context with path [/AD] threw exception [Servlet execution threw an exception] with root cause
java.lang.NullPointerException
at org.apache.xmlbeans.impl.schema.ClassLoaderResourceLoader.getResourceAsStream(ClassLoaderResourceLoader.java:33)
at org.apache.xmlbeans.impl.schema.SchemaTypeSystemImpl$XsbReader.getLoaderStream(SchemaTypeSystemImpl.java:2249)
at org.apache.xmlbeans.impl.schema.SchemaTypeSystemImpl$XsbReader.<init>(SchemaTypeSystemImpl.java:1522)
at org.apache.xmlbeans.impl.schema.SchemaTypeSystemImpl.initFromHeader(SchemaTypeSystemImpl.java:273)
at org.apache.xmlbeans.impl.schema.SchemaTypeSystemImpl.<init>(SchemaTypeSystemImpl.java:185)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)
at java.lang.reflect.Constructor.newInstance(Unknown Source)
at schemaorg_apache_xmlbeans.system.sD023D6490046BA0250A839A9AD24C443.TypeSystemHolder.loadTypeSystem(Unknown Source)
at schemaorg_apache_xmlbeans.system.sD023D6490046BA0250A839A9AD24C443.TypeSystemHolder.<clinit>(Unknown Source)
at sun.misc.Unsafe.ensureClassInitialized(Native Method)
at sun.reflect.UnsafeFieldAccessorFactory.newFieldAccessor(Unknown Source)
at sun.reflect.ReflectionFactory.newFieldAccessor(Unknown Source)
at java.lang.reflect.Field.acquireFieldAccessor(Unknown Source)
at java.lang.reflect.Field.getFieldAccessor(Unknown Source)
at java.lang.reflect.Field.get(Unknown Source)
at org.apache.xmlbeans.XmlBeans.typeSystemForClassLoader(XmlBeans.java:775)
at org.openxmlformats.schemas.drawingml.x2006.main.ThemeDocument.<clinit>(Unknown Source)
at org.openxmlformats.schemas.drawingml.x2006.main.ThemeDocument$Factory.parse(Unknown Source)
at org.apache.poi.xssf.model.ThemesTable.<init>(ThemesTable.java:86)
at org.apache.poi.ooxml.POIXMLFactory.createDocumentPart(POIXMLFactory.java:61)
at org.apache.poi.ooxml.POIXMLDocumentPart.read(POIXMLDocumentPart.java:684)
at org.apache.poi.ooxml.POIXMLDocument.load(POIXMLDocument.java:180)
at org.apache.poi.xssf.usermodel.XSSFWorkbook.<init>(XSSFWorkbook.java:288)
at org.apache.poi.xssf.usermodel.XSSFWorkbook.<init>(XSSFWorkbook.java:342)
at com.MyClient.AD.util.UploadEstimateUT.start(UploadEstimateUT.java:85)
at com.MyClient.AD.util.UploadEstimates.doPost(UploadEstimates.java:107)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:754)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:847)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:219)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:110)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:492)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:165)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:104)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:1025)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:452)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1195)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:654)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:319)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)

This is how I referenced the POI files: MyProject -> Right Click -> Build Path -> Configure Built Path -> Libraries tab and added the following jars

enter image description here

And this is how I execute the application Run -> Run Configuration... -> Classpath tab -> Making sure all jar files are referenced here including Apache POI's -> Apply and/or Run.

enter image description here


Update 1 (28-Feb-2020)

I tried the same code (that reads from excel using POI library) as java application and it worked as expected.

Another thing I noted when debugging the JSP web application is that the control is transferred directly to the finally block instead of the general Exception block. Not sure why.


Update 2 (03-Mar-2020)

I configured the project in my colleagues system who also has Eclipse IDE but with Tomcat server version 9.0.31 and it worked in his machine.

Then I installed Tomcat server version 9.0.31 and configured the project from a separate workspace but when executing I face the same exception. I'm not able to understand what could the difference.

We both are using Eclipse IDE for Enterprise Java Developers. Version: 2019-09 R (4.13.0) Build id: 20190917-1200

Remove #NULL! using Excel Macro

$
0
0

I'm generating excel file by using SPSS and the excel contains character as #NULL! and as it is huge file it's difficult to remove with find & replace command how to do it by using macro

Thank you

Formula to determine if growth is increasing/decreasing, smooth, lumpy, etc

$
0
0

I have some results data in around 10 columns (sample in CSV below) that I would like to run a formula over per row to determine if the trend is reasonably steady/predictable, or lumpy, and if it is trending upwards or downwards. AS the sample shows below, some rows do not have all the data, but still need a determination of the general trend and consistency of the results.

I've tried a few formulas such as trend, growth, stddev, avedev, but I suspect I might have to use them in combination, which is currently beyond me. I feel like using the percentage difference between neighboring cells will help normalise the results to a degree, rather than the value of each cell. If the percentages are all positive then the trend is upward, but that's the best I've been able to come up with that I'm happy gives a clear answer.

I'm using google sheets, but might be able to convert an Excel formula. Any suggestions?

11.65,11.79,11.96,12.26,12.71,12.6,12.7,13.6,14.1,14.7
0.57,0.65,0.73,0.89,1.03,1.24,2.05,2.59,3,3.11
1.85,1.88,1.84,1.92,2.07,2.24,2.56,2.74,2.85,2.92
,,,0.66,0.72,0.78,1.33,1.43,1.47,1.52
,,,,0.64,0.6,0.56,0.55,0.3,
,8.97,8.54,10.46,11.44,8.06,7.42,7.86,7.66,7.8
2.67,1.53,1.84,2.43,2.94,3.43,4.04,7.46,8.25,9.09

VBA - How to choose right number of decimals, based on chart dataseries?

$
0
0

I am working on a macro for formatting charts. I got stuck at choosing a number of decimals (0 or 1) for data labels and y-axis -> if the chart line is "flat" (low volatility) I want to see one decimal point. I've tried to base the calculations on variance, average etc. but nothing seems to work at all.

'$'

' --- DECIMALS DISPLAYED --- 'mn/mx - minimum/maximum in dataseries kustomFormat = IIf(Abs(mn) / (Abs(mx) + 0.0001) > 0.6, "0.0", "0") ActiveChart.Axes(xlValue).TickLabels.NumberFormat = kustomFormat On Error Resume Next For i = 1 To ActiveChart.SeriesCollection.Count ActiveChart.FullSeriesCollection(i).DataLabels.NumberFormat = kustomFormat Next i

'$'

Creation of simple formula with decimal and multiplication by other cell (by VBA)

$
0
0

I have problem like in subject.
How can I create formula in A1 e.g. = 3.14 * A2

this code doesn't work and returns error in final version myVal will be delivered by other function

Public Sub DecimalInFormulaTest()
   Dim myVal As Double
   myVal = 3.14
   ActiveSheet.Cells(1, 1).FormulaR1C1 = "="& myVal & "*R1C2"
End Sub

VBA: runtime error '424' Object required when searching for Shape

$
0
0

I created a VBA script to transfer data from Excel to PowerPoint (both Version 2016) and want to check if there exists a specific Shape on Slide x and then copy it to Slide y.

The common solution which is also mentioned in (Existence of shapes in Powerpoint) does produce

"runtime error '424': Object required"

in line 3 of the function at For Each oSh in myPresentation.Slides(4).Shape

Function ShapeExists(ByVal ShapeName as String) as Boolean

Dim oSh as Shape

For Each oSh in myPresentation.Slides(4).Shapes
     If oSh.Name = ShapeName Then
        ShapeExists = True
        Exit Function
     End If
Next
End Function

The code where "ShapeExists" is called:

Set PowerPointApp = GetObject(class:="PowerPoint.Application")
Set myPresentation = PowerPointApp.Presentations.Add

 If ShapeExists("MSDreieck2") Then
    myPresentation.Slides(4).Shapes("MSDreieck2").Copy
    mySlide5.Shapes.PasteSpecial DataType:=0
 Else
    GoTo NACHZEITSTRAHLCOPY:
 End If

I already added the Object Library for Powerpoint 2016 under references and several others. When typing dim oSh as Shape it suggests two different "Shape" items in the list (one for Excel, one for PP) but it doesn't make a difference for the error which one I use.

As far as I'm concerned there is no other way to check if a specific Shape exists as the Shape index gets newly assigned at every run and as the number of Shapes on Slide x is not always the same in my case.

I would be very grateful for every suggestion. Thanks

Need to lower a sum of values while keeping another sum as constant as possible

$
0
0

Ive been given a task to reduce one sum of values while keeping another some as constat as possible. I have two contributions:

Item Number, Contribution 1, Contribution 2 1, 100, 200 2, 150, 300 3, 200, -400 4, 300, 500 5, 100, -200 ...

(There are a about 5000 entries like this, with vatiable Contribution 1 and 2).

I need to remove one item (row) at the time and output the following results for each iteration: Sum of Contribution 1 Sum of Contribution 2

I did this with the following VBA code:

For i = 1 To 5000
    If .Cells(i, 2) <> 0 Then
        .Cells(i, 2) = 0
        .Cells(i, 3) = 0



        Application.Calculate

.Cells(i, 5) = Sheets("results").Cells(45, 5)
.Cells(i, 6) = Sheets("results").Cells(25, 5)
//where results sheet contains the sum of column 2 and 3
    End If

    If i Mod 500 = 0 Then
        Debug.Print i
    End If
Next i
End With

However I need to add contrains where: While get Sum of Contributions 1 as close as possible to zero Keep Sum of Contributions 2 as it was. (within 10% of original value)

Before removing an item the code needs to check if Sum of Contributions 1 will bring it closer to zero and Sum of Contributions 2 is still within 10% of original value.

Greatly appriciate your help. Can be done in VBA or Python. Please let me know if you have any questions.

Kind Regards,

Maks

Using Logic Apps to read Excel from sharepoint online and then inserting into Azure SQL

$
0
0

I am trying to do something that shoudl be fairly simple but I get no results. I want to read a Excel file from our sharepoint site (O365) and insert the data from the first worksheet into a table in SQL Server.

Actually quite simple and straightforward. Well, it sounds like that....... Apparantly there is more than reading the file and inserting the file into SQL Server.... Who can provide me with info, tutorials or (even better) step-by-step instructions?

Bonus would be looping through the (online) folder and importing all excel files creating a table for each worksheet

Thanx for thinking with me

Loop through worksheets containing graphs, copy both ChartObjects into another sheet [closed]

$
0
0

This is my first ever post, so please excuse any inadvertent overstepping of protocol.

In my Workbook, I have multiple worksheets each containing 2 graphs – I want to loop through these sheets copying ChartObjects(1) and ChartObjects(2) side-by-side into another sheet named "Graphs".

To clarify, the worksheets that contain 2 graphs are named "John", "Paul", "George" and "Ringo". I want to first select sheet “John”, copy ChartObjects(1) into cell A3 of “Graphs” and then ChartObjects(2) into cell K3 of "Graphs", next I want to select “Paul” and copy ChartObjects(1) into cell A24 of “Graphs” and ChartObjects(2) into cell K24 of "Graphs", and so on for “George”, “Ringo” etc.

I have researched this problem but could not find a solution to copy 2 ChartObjects from one sheet into another sheet side-by-side, as such I am currently using a code that simply selects each sheet in turn and copy/pastes the graphs - I am sure there is a better approach unfortunately it's beyond my limited VBA skills.

NOTE: As requested by the moderators, I have updated my original question, for which @Harassed Dad had kindly provided a solution, but please let me know if anything needs to be clarified.

Regards, TE

How to read data of an Excel file using C#?

$
0
0

How to read an Excel file using C#? I open an Excel file for reading and copy it to clipboard to search email format, but I don't know how to do it.

FileInfo finfo;
Excel.ApplicationClass ExcelObj = new Excel.ApplicationClass();
ExcelObj.Visible = false;

Excel.Workbook theWorkbook;
Excel.Worksheet worksheet;

if (listView1.Items.Count > 0)
{
    foreach (ListViewItem s in listView1.Items)
    {
        finfo = new FileInfo(s.Text);
        if (finfo.Extension == ".xls" || finfo.Extension == ".xlsx" || finfo.Extension == ".xlt" || finfo.Extension == ".xlsm" || finfo.Extension == ".csv")
        {
            theWorkbook = ExcelObj.Workbooks.Open(s.Text, 0, true, 5, "", "", true, Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, false, false);

            for (int count = 1; count <= theWorkbook.Sheets.Count; count++)
            {
                worksheet = (Excel.Worksheet)theWorkbook.Worksheets.get_Item(count);
                worksheet.Activate();
                worksheet.Visible = false;
                worksheet.UsedRange.Cells.Select();
            }
        }
    }
}

Macro to Count Filter Distinct unique Value

$
0
0

I Have Table like this, where i have to use macro because my table always change Every day (SSAS) so i have use macro to filter automatically,

enter image description here

I am able to sum Amount based on same Vendorname, PONuber and Date on Column E (Subtotal).

enter image description here

and then filter to show Subtotal AMount >500

I want to show only row >500 (Column E), and pop up message to count PONumber (Column B) how many Unique PO Number (Only Visible Row to count)

enter image description here

i've been stuck how to count only Visible Unique PO Number and show it on Pop Up message

this is my Macro

Sub FilterCOunt_Click()
Dim Condition As Variant
Dim AVal As Variant
Dim LastRow As Long
Dim Hide, popup  As Long
Dim message  As String

Dim sht As Worksheet
'----------------------------
Dim dictionary As Object
Set dictionary = CreateObject("scripting.dictionary")
'---------------------------
        Application.ScreenUpdating = False
        Application.EnableEvents = False
        Application.AskToUpdateLinks = False
        Application.DisplayAlerts = False
        Application.Calculation = xlAutomatic
        Application.ScreenUpdating = False
        Application.StatusBar = False
'------------------
Columns.EntireColumn.Hidden = False
Rows.EntireRow.Hidden = False
Columns("E:Z").EntireColumn.Delete
Range("E:Z").EntireColumn.Insert
Range("E1").Value = "Sub Total >500 "

Set sht = ActiveSheet

LastRow = sht.Range("B"& Rows.Count).End(xlUp).Row
'-------------------


For i = 2 To LastRow ' with last row count =SUMIFS(I:I,A:A,A8,B:B,B8,C:C,C8)

     AVal = "A"& i

     BVal = "B"& i

     CVal = "C"& i
     Worksheets("Sheet3").Range("E"& i).Formula = "=SUMIFS(D:D,A:A,"& AVal & ",B:B,"& BVal & ",C:C,"& CVal & ")"

Next i

With sht.Range("E1:E"& LastRow)
.AutoFilter
.AutoFilter field:=1, Criteria1:=">=500"

End With
'----------Count Pop UP
Dim CountPO As Long
Range("G1").FormulaArray =  "=SUM(IF(FREQUENCY(IF(SUBTOTAL(3,OFFSET(B2,ROW(B2:B22)-ROW(B2),1)),IF(B2:B22<>"",MATCH(""&B2:B22,B2:B22&"",0))),ROW(B2:B22)-  ROW(B2)+1),1))"


MsgBox "We Found "& CountPO & " PO Open(s)", _
vbInformation, "PO Found"
End Sub

and this is the formula to count it

{=SUM(IF(FREQUENCY(IF(SUBTOTAL(3,OFFSET(B2,ROW(B2:B22)-ROW(B2),1)),IF(B2:B22<>"",MATCH("~"&B2:B22,B2:B22&"",0))),ROW(B2:B22)-ROW(B2)+1),1))}

Add every file inside a folder

$
0
0

I'm trying to do a macro that let's the user select a folder with more folders inside, this folders could have images .jpg or .png. What I want is that the macro adds only the image files in the excel, any image file. What it does right now is that adds the images but only if they have for name 1.jpg, 2.jpg, 3.jpg and so on.

Dim Secfolder As String
MsgBox ("Busque y seleccione la carpeta que contiene las carpetas de los sectores en el punto que realizará.")
With Application.FileDialog(msoFileDialogFolderPicker)

.Title = "Buscar carpeta"
.ButtonName = "Aceptar"
.InitialFileName = "C:\"

If .Show = -1 Then
 Secfolder = .SelectedItems(1)
End If

Sheets("Matriz_de_Hallazgos").Select

l = 1

For i = 1 To 200
idm = (Worksheets("Matriz_de_Hallazgos").Cells(i + 2, 1))

If idm = 1 Then
Application.SpellingOptions.IgnoreCaps = True
 ' Colocar la ruta de las fotos; las fotos deben llamarse como números. Ej: 1.jpg'
    RutaCompleta = Secfolder & "\"& "sector "& idm & "\"& l & ".jpg"
    ActiveSheet.Cells(i + 2, 3).Select
    With ActiveSheet.Shapes.AddPicture(Filename:=RutaCompleta, linktofile:=msoFalse, _
        SaveWithDocument:=msoCTrue, Left:=0, Top:=0, Width:=0, Height:=0)
        .LockAspectRatio = 0
        .Top = ActiveCell.Top
        .Left = ActiveCell.Left
        .Width = ActiveCell.Width
        .Height = ActiveCell.Height
    End With
    l = l + 1
End If
Next i

Any ideas? Thank you


How to find matching headers in a worksheet using vba

$
0
0

I am very new to vba. The task that I am trying to do is there is a sample sheet with lots of data and lots of headers. Out of those headers I have to verify/check that particular 12 headers are available or not. If they are available message should show as success and if not it should show that the specific header is missing. For now I have created a sub and took an array with those twelve values but how to match. Please help.

Excel VBA to set functions Replace, loop, with couple of variables [closed]

$
0
0

enter image description here

Hello guys,

I would like to select all datas concerned by some criterias, and replace with **. So based on /Basis ungew.- any cell <10, all datas into the same column, under the header would be change with **.

There are hundred of tables, and I consider a Loop function to be applied. Thanks for your support

Finding the highest value in a range

$
0
0

How can I find the highest price among the prices with same contiguous label ?

For instance, in the picture below the result of the formula in D6 should be 5 because the formula should consider the lines 4, 5 and 6 only (contiguous lines with label 'a'). Therefore, the prices to be considered should be 3, 4 and 5 and the relevant MAX is 5.

enter image description here

I started building the formula in steps and the first one is to get the row n# where the max price is and I made this formula {=MAX(IF($A$2:A5<>A6,ROW()))} but I cannot even make this to work.

EDIT

The solution from Tom Sharpe in this thread is almost perfect. What I didn't mention in the initial question is I want to see the MAX in each line. Here below is the screenshot with an extra column with what I want to achieve. enter image description here

Extract words between two specific characters or number

$
0
0

I want to extract the two specific words from excel cell ie: cell A1 contains data

{"defvcision":"DISASDEE","reascdwon":"labwcel","cowcddcents":"SwcA:Ercwdcror:CwcOwccPcewS:SewellerApcwecpewcal-BwerLR:2/24/2020 : 306973918 @ snedcharo"}

Now I want to extract 306973918 and snedcharo from cell. These to values will be dynamic in other cells ie A2A3...

I have tried formula

=MID(A1, SEARCH(":",A1) + 1, SEARCH(":",A1,SEARCH(":",A1)+1) - SEARCH(":",A1) - 1)

but that is not working.

Autofil cell with the month number if adjacent cell contains date

$
0
0

I'm looking for a smoother solution for below code. The task is if column O is not empty, then check if AH is empty. If AH is not empty (then it contains a date) I need to get the number of the month from this date to column AI (right next to AH).

I'm new to coding and so far the below is what I've got but this doesn't seem the perfect solution as it is simply adding the formula to and I suppose this could be also done by a loop.

Many thanks in advance.

Sub d_month()

Dim r As Range
Dim LastRow As Long

With Application.ActiveSheet

    LastRow = .Cells(.Rows.Count, "O").End(xlUp).Row

    For Each r In .Range("O2:O"& LastRow)
        If r.Value <> "" Then
            r.Offset(0, 20).Value = "=IF(RC[-1]="""","""",MONTH(RC[-1]))"
        End If
    Next r
End With

End Sub
Viewing all 88206 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>