Quantcast
Channel: Excel Help Forum - Excel Programming / VBA / Macros
Viewing all 50117 articles
Browse latest View live

Need newton raphson method to converge to only positive numbers

$
0
0
Hey guys,

I posted a thread recently wondering about the best way to construct a Newton-Raphson method to approximate a list of cells using VBA, and ended up coming up with something that works. I'll link back to the old thread once I figure out how, and I'll post my code below.

The issue is, the "correct" solution to the equation is the one that is always positive. Sometimes some of the cells give me negative values, which later on in my spreadsheet gives me errors or incorrect solutions. I can't come up with an initial guess that gives me a positive root every time, and I am wondering if there is a way to inside of the newton raphson method, force the method to converge onto the first POSITIVE real solution. ANY help would be so appreciated, this has me thoroughly stumped. Maybe I could set up something where if a negative value for P pops up, it forces p to a higher and higher guess for p, until it converges on the real solution? Any help would be great, and I'd love to hear your thoughts. Here's my code as it is, and I have a list of cells in my spreadsheet that say, "=NR(b, c, d, e, 0)" except b c d and e are just 4 columns of cells in the same row as the NR equation. Please let me know your thoughts, also, how do I link my old thread to this one?
Code:


Public Function f(x, b, c, d, e)

        'Input a function that you are interested in finding the root of
        'COUNT NUMBER OF CELLS HERE AND STORE AS J

        'j = 4 'Worksheets("Sheet1").Range("Ce1:e38").Cells.SpecialCells(xlCellTypeConstants).Count
        'b = Cells(j, "B")
        'c = Cells(j, "A")
        'd = Cells(j, "C")
        f = -d * x ^ 3 + d * e * x ^ 2 + d * b ^ 2 * x + c * e * b ^ 2 - d * e * b ^ 2
    End Function

  Public Function df(x, b, c, d, e)

        'Input derivative of function
        'COUNT NUMBER OF CELLS HERE AND STORE AS J
        'j = 4 'Worksheets("Sheet1").Range("e1:e38").Cells.SpecialCells(xlCellTypeConstants).Count
        'b = Cells(j, "B")
        'c = Cells(j, "A")
        'd = Cells(j, "C")
        df = -3 * d * x ^ 2 + 2 * e * d * x + d * b ^ 2

    End Function
  Public Function NR(b, c, d, e, p0) '(i, n, err, tol, p0)
        'This is a method of approximating the answer for the wind column #2... It works similar to the way excel's solver would except it is faster since it has a taylor series approximation to conform to. (it uses derivatives to estimate the answer, not a linear approximation. Thus less iterations and a quicker result.)
        'Dim the variable that gets updated by this function
        Dim p, p_old As Double
 '      Dim b, c, d As Integer
n = 100
tol = 0.000001

        'Initialize our Iteration'
        i = 0
        p = p0

        'perform the iteration
        Do
        p_old = p
        'From Newton's Formula
        p = p - f(p, b, c, d, e) / df(p, b, c, d, e)
        i = i + 1

        'if p is not 1, we have an error
        If (p <> 1) Then
        err = Abs((p - pold) / p)
        End If

        'input the stopping criterion for the iteration
        If err < tol Or i >= n Then Exit Do

        Loop

        NR = p

    End Function


[SOLVED] Change Font Color in column (Text and Number same cell)

$
0
0
Hi.

How change font color each number in same cell with text in column?

In my exemple I have data in column A, each cell has text and number together.


2ma34rr6ec7o

Thank you!!

Error when importing table from PDF to Excel

$
0
0
Hi Guys!

I have this almost figured out and it works great, except I run into the following errors anytime I open the workbook and have to go through this process of uncommenting and commenting a section of code.

Below is the code:

Code:

Private Sub ActivateExcel()
   
    AppActivate "Microsoft Excel"
   
        'Import_PDF receives the table from the PDF file.
        Sheets("ImportPDF").Select
       
        'clear all previous data (at the moment this causes an error so look for another way)
        ThisWorkbook.Sheets("ImportPDF").Cells.ClearContents
       
        Range("A1").Select
        ActiveSheet.Paste
   
   
    'IMPORTANT NOTE__________________________________________________________________
    '
    'The section which requires tinkering: this next code below will separate the pdf
    'table into excel columns, however it only needs to be done the first time, and then
    'just pasting works! doing this the 2nd time makes an error. 2nd run now only need to
    'sort a-z the new ImportPDF sheet (put 3.5 after 3 instead of at the end!
   
        Application.CutCopyMode = False
    '    Selection.TextToColumns Destination:=Range("A2"), DataType:=xlDelimited, _
    '      TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=True, Tab:=True, _
    '      Semicolon:=False, Comma:=False, Space:=True, Other:=False, FieldInfo _
    '      :=Array(Array(1, 1), Array(2, 1), Array(3, 1), Array(4, 1), Array(5, 1), Array(6, 1), _
    '      Array(7, 1), Array(8, 1), Array(9, 1), Array(10, 1), Array(11, 1), Array(12, 1), Array(13, 1 _
    '      ), Array(14, 1)), TrailingMinusNumbers:=True
   
   
        ActiveWorkbook.Worksheets("ImportPDF").Sort.SortFields.Clear
        ActiveWorkbook.Worksheets("ImportPDF").Sort.SortFields.Add Key:=Range("A3"), _
            SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
   
        With ActiveWorkbook.Worksheets("ImportPDF").Sort
            .SetRange Range("A3:N26")
            .Header = xlNo
            .MatchCase = False
            .Orientation = xlTopToBottom
            .SortMethod = xlPinYin
            .Apply
        End With
   
       
        'copy the column from Import_PDF "dev" to the volute sheet which was active on ctrl-b
        '
        Range("B3:B26").Select
        Selection.Copy
        'ActiveWindow.ScrollWorkbookTabs Position:=xlFirst
       
        'here select the target active sheet when ctrl-b started the macro:
        'whichever sheet is open during ctrl-b will get the PDF "dev" col now...
        'MsgBox ActiveSheet.Name & "  activating this sheet now..."
        Sheets(ActiveSheetImport).Select
        'ActiveWindow.SmallScroll Down:=24
       
      'need a time delay right here!
      'MsgBox "currently active = " & ActiveSheet.Name & "      active on ctrl-b was = " & ActiveSheetImport
     
        'and here we can paste to the active cell when ctrl-b started macro:
        'the range is the active cell! that's where the dev col pastes to next line:
        ActiveSheet.Paste
   
     
        Range("A1").Select
    'Range("A1").Activate
    'SendKeys ("^v")
   
    'Shell "pskill " & StartAdobe
    'Call Shell("TaskKill /F /PID " & CStr(vPID), vbHide)
    End Sub

So when I first run the macro to import the data into the "ImportPDF" worksheet the data looks like ths:Error 20.JPG

So to solve all the data being exported into a single coloumn: This section of code was written:

Code:

Application.CutCopyMode = False
        Selection.TextToColumns Destination:=Range("A2"), DataType:=xlDelimited, _
          TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=True, Tab:=True, _
          Semicolon:=False, Comma:=False, Space:=True, Other:=False, FieldInfo _
          :=Array(Array(1, 1), Array(2, 1), Array(3, 1), Array(4, 1), Array(5, 1), Array(6, 1), _
          Array(7, 1), Array(8, 1), Array(9, 1), Array(10, 1), Array(11, 1), Array(12, 1), Array(13, 1 _
          ), Array(14, 1)), TrailingMinusNumbers:=True

So I would uncomment this line of code and then re run the macro. I have to run the macro twice. The second time I run the macro I get this error: error11.JPG

Once I get that error, if I comment that code again, and run the macro. The data transfer is perfect and works like a charm. But if I close the workbook, I have to redo the entire process. Does anyone know why that is? or how I can fix this issue?

Excel Template ? and consecutive numbering

$
0
0
Hi everyone.

Please could someone help me......

This is what I am trying to do.
I need to create an Invoicing system in one Excel Workbook. There will be one Invoice to start with - Design already set up, with a cell with the number 0001 and the sheet named Invoice 0001. When the bookkeeper needs to create a second Invoice, the template needs to automatically populate to the new sheet with the cell for the Invoice number already reading 0002, as well as the Sheets name must automatically create as Invoice 0002.

Can someone please help me with this? I am getting stuck

Procedure too Large Error - Any suggestions appreciated on how to split this code? Thanks

$
0
0
Hi all,

I would like to ask for advice regarding this code on how to split it? Thank you in advance! Appreciate the assistance.
Attached Files

generating new tab based on existing pivot

$
0
0
well, instead of using code to generate pivot and format to no subtotal and tabular form. I just set up template for that (lazy way) . see "pivot" tab. but to get to the way look like in "final" tab.

I still need to highlight everything, copy and paste special to value. then insert blank row under header. then separate by ship to name. then add two new cols to the end of header" group" "shipment". that is the part can someone shred some lights for me on the code. once I got those code, can I just stack them under the code for auto refreshing part?
Attached Files

Macro to Copy and Paste Specific Text in Column A on the last line with Text in Column B?

$
0
0
Hi,

I would like to know a VBA code to copy the word 'Name' in Column A from A1 unti A'x', where x is the last row with text in Column B.

In other words, if my Column B has 27 registries with text from B1 to B27, I want the macro to copy the word 'Name' in Column A from A1 to A27, however, if the number of rows are more or less in Column B, I want the code to know where is the limit to copy.


Thanks in advance for your support,
D2S

Macro to Copy Duplicate Rows into a Different Tab

$
0
0
I have a data set that I add to every day.

Here's what I have...

The data is essentially records (with a unique person_ID) that have an error with them.
Every day, the data is spit out and sent to me. I add the old data to the new data.
if the record is fixed, then it drops from the data, if it doesn't get fixed, it's in the next day's report again, and again, and again until someone fixes it.

What I want to do:
Once I paste the data from yesterday's report to my master data base and go through the new records
If the person_ID is repeated, I want both of the rows (in their entirety) to be sent to a 2nd tab.

Does that make sense?

I would love help from the experts

search non active sheet

$
0
0
Good Afternoon,

I have this code
Set target = Sheets("Database").Cells.Find(What:=EmNum, After:=ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)

and it is working fine if I want to search an the entire sheet, but I would only like to search 3 columns J-N. I change the above code to this

Set target = Sheets("Database").Columns ("J:N:).Find(What:=EmNum, After:=ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)

I also tried this

Set target = Sheets("Database").Range ("J1:N1000").Find(What:=EmNum, After:=ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False)

neither would find the number I was looking for. The first one does. For example I was searching for N12698. The first code finds it but if I try to just narrow into the 3 columns the target variable comes back as empty.

I would appreciate any thoughts anyone would have on this.

Thank you

Caption not updating and hourglass not activated

$
0
0
I have a user form with a command button. When the user clicks the command button, I would like:

1. a label's caption on the form to update ("Updating sheet ...")
2. the cursor to change to an hour glass
3. the main code to run
4. the label's caption to update again ("Done!")
5. the cursor to return to default

#3 and #4 work fine, but #1 doesn't execute (the caption stays empty), and the cursor stays in it's default status (i.e., it never changes to an hourglass).

Code:

Private Sub cmdCutPasteData_Click()

lblStatus.Caption = "Updating sheet ..."
Application.Cursor = xlWait

Range("C1:M20").Cut Range("B1")
' Lots more cutting and pasting of other ranges
Application.CutCopyMode = False

lblStatus.Caption = "Done!"
Application.Cursor = xlDefault

End Sub

Any suggestions?

[SOLVED] Textjoin?

$
0
0
I've been trying to understand how to use textjoin to make this work but I think I need some help.

I want to join all cells in sheets("race").range("AO2:AQ17) to a single cell. So that the output would look the same as the range but within a single cell and with spaces as a delimiter.

This is what the range looks like:
2017-08-19 09_28_57-Javelin.xlsm - Excel.png

Modify the code

$
0
0
Hi All,

I have attached four workbooks. 3 from suppliers and one masterdata.
The three supplier’ workbooks are Supplier-a.xlsx, Supplier-b.xlsx, Supplier-c.xlsx and the master zMaster.xlsm
I am able to transfer the data from the suppliers’ workbooks to the master workbook, but, I have to hard code the number of lines.

I want to alter the code below to do two things
1. Be able to drag thousands of lines.
2. Update the lines that have been dragged to show “Yes” in column E and they are not dragged again.
Regards

Raghu

Code:

Option Explicit
'http://www.exceltrainingvideos.com/transfer-data-multiple-workbooks-master-workbook-automatically/

Sub LoopThroughDirectory()
Dim MyFile As String
Dim eRow As Long
Dim LastRow As Long


Dim FilePath As String
FilePath = ActiveWorkbook.Path & "\"
MyFile = Dir(FilePath)
    Do While Len(MyFile) > 0
        If MyFile = "zmaster.xlsm" Then
            Exit Sub
        End If
       
        Workbooks.Open (FilePath & MyFile)
'            If Range("E2").Value = "" Then
                Range("A2:D20").Copy
'            End If
        ActiveWorkbook.Close
   
        eRow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
        ActiveSheet.Paste Destination:=Worksheets("Sheet1").Range(Cells(eRow, 1), Cells(eRow, 4))
       
        MyFile = Dir
        ActiveWorkbook.Save
    Loop
End Sub

Attached Files

Need to change PivotField Name based on a Cell

$
0
0
Hi Guys,

I have a problem with creating a code for Pivot Table. The problem is that I wish to add a Pivot Field to Data, but this field has to depend on what is within a particular cell of the workbook. For example, if the cell contains the text "January", then the PivotField to be added to the Data in the Pivot Table is to be "January". I have the following code which is giving me an error.

Code:

Sub UpdatePivot()
Dim ws As Worksheet, SrcData As String, pvtCache As PivotCache
Dim ws2 As Worksheet, ws3 As Worksheet
Dim pf As PivotField, pt As PivotTable, df As PivotField, str As String
'Set ws = ThisWorkbook.Worksheets("Lisun Data")
Set ws2 = ThisWorkbook.Worksheets("Cover")
Set ws3 = ThisWorkbook.Worksheets("Stockist")
Set pt = ws3.PivotTables("PivotTable3")
For Each pf In pt.ColumnFields
    pf.Orientation = xlHidden
Next pf
Set str = ws2.Cells(6, 1)
With pt.PivotFields(str)    'PROBLEM LIES HERE
    .Orientation = xlDataField
    .Function = xlSum
    .Position = 1
End With
End Sub

Much appreciated for your advice, thank you.

Tick Currency Datafeed Need Decoding?

$
0
0
Hey,
Being working on this all night, I need to found the high/low values in a string to reduce a datafeed to per sec OHLC dataset.

Formula used to decode mil-sec tick datafeed into sec OHLC strings. Need one high/low value in each row on each second.
(got the open/close just need High/Low?)

I have a attached my sheet below. Thx for any help.
Attached Files

Insert blank row after max value less than X

$
0
0
Hello,
Please forgive me. I'm a new VBA user and can't figure this out.

I have a list that looks like this:

106
108
110
201
202
203 .... etc,

I need a vba code that finds the maximum value that is less than 200, and inserts a blank row below it. If there is no value less than 200, do nothing.

Please and Thank you!

Insert Rows and Maintain Values

$
0
0
Hi,
I am stuck with an excel file where I have data from A to T copied from website and data from U to Z are manually inserted.
usually I have 100-200 lines of data everday, what happens is data on the website gets sorted alphabetically

So say in day 1:
I have
B
C
E
and I have written manual comments in cell U to cell Z in reference to B and C and E

now when I go to the website the order has became
A
B
C
D
E
and I want to highlight everything and copy it, so now the manual inputs in Cells U to Z are no longer in reference to the correct rows

Is there a way to handle this using VBA?

I Need Excel VBA Code to Import Real-time FX Datafeed into Excel

$
0
0
Hey, only for VBA financial expects.
got a big task related to FX datafeed imported in excel and updated in real-time.
please state your payment cost and I will pay you in forum points?

I simply need a custom written Excel VBA Macro program to update/stream real-time FX currencies (data feed) from FXCM FIX API Gateway.
Second, within VBA the data-feed needs to be encoded from tick too seconds with OHLC strings and then displayed in excel rows, updating from top to bottom to be graphed by me.

Attached is the brief and excel sheet.

Thx Stewart

Search,Edit and Save

If 2 cells match then pull data

$
0
0
I recently had help with this project and now required a little more help to finish it off.

What I need is if the "Graph" number on the Graph sheet matches the "Graph" number in column "F" on the BD-CO sheet then then fill in the relevant boxes on the Graph sheet to the right of the "Graph" number. (It will all make sense when you see the example i have attached)

If it is a breakdown (B/D) it should ideally display a blank fleet number with the "From" time (Column H) next to it and then when a replacement vehicle is found that will be placed next with the "To" time (column I) next to it. Should it just be a simple change over then just the "To" time (column I) should be used with the replacement fleet number (Column L).

Should this not be possible with the breakdown and changeovers then just using the "To" time (column I) and replacement fleet number will be sufficient.

Please see attached file for the examples ive used.
Attached Files

Change the number of rows in existing table to match cell value

$
0
0
Hello all you lovely people,

I have been scouring the web to find a solution to my problem but thanks to my utter uselessness and lack of knowledge in excel I cant quite make any of the solutions work for me. My apologies if this has been answered many times.

What I am aiming to achieve is to have an existing table containing formulas automatically (if possible) contain the number of rows dictated in a cell on a different work sheet.

For example, I would like to input the number of guests into a cell on sheet1 and then have (automatically if possible) the table on sheet2 readjust to only contain that number of rows (so each guest has one row) while also maintaining the formulas in each column. Most of this tables data will be inputted afterwards.

I am trying to make this as fool proof as possible since there maybe people who have no idea how to use excel interacting with the sheet. As such I will be locking down the sheet leaving only a few cells open. Trouble is the person making this sheet is also a fool, I really don't know much about VBA but I am keen to learn. So if this question is clear enough and one of you clever people can help, would you also be kind enough to explain what the code is doing.

Thank you in advance
Viewing all 50117 articles
Browse latest View live