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

Excel to generate quotes & track inventory

$
0
0

I have a question, more about possibilities. We are currently tracking inventory for a specific project through Excel, and we are also generating quotes for this project through Excel. There is a set inventory spec for this (so there are only certain items that can be chosen for the quotes based on what was ordered). I'm working if there's a way to have a quote generated from Excel (through a Macro), that is picking items from stock (inventory levels don't matter - simple data validation). Then after its generated, push the item levels that were specified on the quote to a worksheet to help track what has been allocated?

More of a "is this even possible" question at this stage then will try and figure out how to accomplish this. I know there are more better tools for this task, but we're limited to Excel at this time.


Why does the call from a sheet slow down the entire routine?

$
0
0

If I run this code from within the VBA IDE, e.g. press F5 on the Test routine, my connection and parsing the xml happens almost instantly.

Sub Test()

Sheet1.Range("4:20000").Clear

Dim con As New msxml2.ServerXMLHTTP60
    con.Open "GET", "mySite", False, "username", "password"
    con.setRequestHeader "Content-type", "application/x-www-form-urlencoded"
    con.send

Dim xmlDoc As msxml2.DOMDocument60
Set xmlDoc = con.responseXML

    parseXmlDoc xmlDoc

End Sub


Private Sub parseXmlDoc(xmlDoc As msxml2.DOMDocument60)

Dim r As Integer: r = 3
Dim c As Integer: c = 0

Dim oo As Object
Dim pp As Object
Dim qq As Object

On Error GoTo ErrHandle
With Sheet1
    Set oo = xmlDoc.SelectNodes("root/myNode")     
    For Each pp In oo
        r = r + 1
        For Each qq In pp.ChildNodes
            c = c + 1
            .Cells(r, c).Value2 = qq.nodeTypedValue
        Next qq
        c = 0
    Next pp
End With
ErrHandle:

End Sub

However, if I add a hyperlink and call the routine from there, the looping through the xml document takes about 5 seconds... Why is this happening and how can I stop it!?

Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink)
  Select Case Target.Range.Address(False, False)
    Case "A1"
        Test
  End Select
End Sub

I'm simply calling the routine from another place. I don't have any calculations on the sheet nor is there any other worksheet events. Like I say, if I run the Test routine from my IDE it works in milliseconds...

How to use Regular Expressions (Regex) in Microsoft Excel both in-cell and loops

$
0
0

How can I use regular expressions in Excel and take advantage of Excel's powerful grid-like setup for data manipulation?

  • In-cell function to return a matched pattern or replaced value in a string.
  • Sub to loop through a column of data and extract matches to adjacent cells.
  • What setup is necessary?
  • What are Excel's special characters for Regular expressions?

I understand Regex is not ideal for many situations (To use or not to use regular expressions?) since excel can use Left, Mid, Right, Instr type commands for similar manipulations.

When I run vba macro nothing happens?

$
0
0

I have the below code in my excel file, but when I run it nothing happens and it doesnt come up in window either.

    GetDataFromADO()

        'Declare variables'
            Dim objMyConn As ADODB.Connection
            Dim objMyCmd As ADODB.Command
            Dim objMyRecordset As ADODB.Recordset

            Set objMyConn = New ADODB.Connection
            Set objMyCmd = New ADODB.Command
            Set objMyRecordset = New ADODB.Recordset

        'Open Connection'
            objMyConn.ConnectionString = "Provider=SQLOLEDB;Password=*******;User ID=*****; Initial 
        Catalog=*******; Data Source=*********************,1433;"
            objMyConn.Open

        'Set and Excecute SQL Command'
            Set objMyCmd.ActiveConnection = objMyConn
            objMyCmd.CommandText = "SELECT wh_id,mst_ship_num, cus_name, car_id, vsl_id,late_ship_dt, 
        load_cmpl, dsp_dt,live, ckin_dt,driver_arr_dte   FROM [dbo].[CXU_ALL_LOAD_CONTROL] WHERE wh_id = 
        'U07S' And dsp_dt = '2019-12-31'"
            objMyCmd.CommandType = adCmdText

        'Open Recordset'
            Set objMyRecordset.Source = objMyCmd
            objMyRecordset.Open

        'Copy Data to Excel'
            ActiveSheet.Range("A5").CopyFromRecordset objMyRecordset

   End Sub

Why is my VBA ComboBox blank until I type

$
0
0

I created a simple UserFormComboBox with a list of items:

Private Sub CourseComboBox_Change()
CourseComboBox.List = Sheets("Course Lists").Range("G2:G15").Value
End Sub

When I run the UserForm the drop down list appears empty until I type something. At this point the full list displays for me to choose from. Is there something I'm doing wrong that makes the text in my ComboBox not show up until I type?

I tried adding CourseComboBox.ListIndex = 0 (a previous solution on here), which had no effect.

Combining IF Formulas in Excel with Variable Ranges [duplicate]

$
0
0

I'm a beginner here. I'm looking to essentially run formulas down in a separate column taking metrics from another column into the formula. Since each month of data is 4000 rows long, The range upon this formula will change from month to month.

The formula in excel looks like this, and I want to replicate it in VBA with using variable ranges.

=IF(H15>=PERCENTILE($H$15:$H$628604, 0.95), H15, 0)

I came up with this:

Range(NewRangeU).Formula = "IF(" + NewRange2 + ")">=(PERCENTILE(" + NewRangeU + ", 0.95)"

I essentially don't know how to combine the two formulas in VBA.

NewRangeU = M4624:M9209
NewRange2 = M4624

So the formula in each cell going down the column should be:

=IF(M4624>=PERCENTILE($M$4624:$M$9209, 0.95), M4624, 0)

=IF(M4625>=PERCENTILE($M$4624:$M$9209, 0.95), M4625, 0)

 =IF(M4626>=PERCENTILE($M$4624:$M$9209, 0.95), M4626, 0)

and so forth

Please don't close this post it's not a duplicate I know how to add variable ranges inside VBA, what I don't know how to do is combine Variable Ranges with multiple Formulas that includes a condition. Haven't been able to find this answer from my search. The suggestion from the moderator on my original post didn't help with the question.

The suggestion doesn't work below.

Range(NewRangeU).Formula = "=IF("& NewRange2.Address(False, False) & ")">=(PERCENTILE("& NewRangeU.Address(False, False) & ", 0.95)"

I've also tried combining them into a string which also doesn't work.

String1 = "=IF(" + NewRange2 + ">="
String2 = "PERCENTILE(" + NewRangeU + ", 0.95)"
String3 = String1 & String2
'Range(NewRangeU).Formula = String3

A more accurate and more efficient fuzzy searching algorithm

$
0
0

I have been researching fuzzy match / search algorithms across the internet. I have tried a couple of solutions.

The only that gave somewhat accurate results was from Mr. Excel (http://www.mrexcel.com/pc07.shtml). The problem with this method is the order or relative position of characters in the words and the order of the words themselves had no effect on the results.

I would like to get better results based on the relative word position as well as the order of the letters per word.

Function FuzzyMatchByWord(ByVal lsPhrase1 As String, ByVal lsPhrase2 As String, Optional lbStripVowels As Boolean = False, Optional lbDiscardExtra As Boolean = False) As Double

'' Compare two phrases and return a similarity value (between 0 and 100).
'' Arguments:
'' 1. Phrase1        String; any text string
' 2. Phrase2        String; any text string
' 3. StripVowels    Optional to strip all vowels from the phrases
' 4. DiscardExtra   Optional to discard any unmatched words
''local variables
Dim lsWord1() As String
Dim lsWord2() As String
Dim ldMatch() As Double
Dim ldCur As Double
Dim ldMax As Double
Dim liCnt1 As Integer
Dim liCnt2 As Integer
Dim liCnt3 As Integer
Dim lbMatched() As Boolean
Dim lsNew As String
Dim lsChr As String
Dim lsKeep As String

'set default value as failure
FuzzyMatchByWord = 0

'create list of characters to keep
lsKeep = "BCDFGHJKLMNPQRSTVWXYZ0123456789 "
If Not lbStripVowels Then
    lsKeep = lsKeep & "AEIOU"
End If

'clean up phrases by stripping undesired characters
'phrase1
lsPhrase1 = Trim$(UCase$(lsPhrase1))
lsNew = ""
For liCnt1 = 1 To Len(lsPhrase1)
    lsChr = Mid$(lsPhrase1, liCnt1, 1)
    If InStr(lsKeep, lsChr) <> 0 Then
        lsNew = lsNew & lsChr
    End If
Next
lsPhrase1 = lsNew
lsPhrase1 = Replace(lsPhrase1, "", "")
lsWord1 = Split(lsPhrase1, "")
If UBound(lsWord1) = -1 Then
    Exit Function
End If
ReDim ldMatch(UBound(lsWord1))
'phrase2
lsPhrase2 = Trim$(UCase$(lsPhrase2))
lsNew = ""
For liCnt1 = 1 To Len(lsPhrase2)
    lsChr = Mid$(lsPhrase2, liCnt1, 1)
    If InStr(lsKeep, lsChr) <> 0 Then
        lsNew = lsNew & lsChr
    End If
Next
lsPhrase2 = lsNew
lsPhrase2 = Replace(lsPhrase2, "", "")
lsWord2 = Split(lsPhrase2, "")
If UBound(lsWord2) = -1 Then
    Exit Function
End If
ReDim lbMatched(UBound(lsWord2))

'exit if empty
If Trim$(lsPhrase1) = "" Or Trim$(lsPhrase2) = "" Then
    Exit Function
End If

'compare words in each phrase
For liCnt1 = 0 To UBound(lsWord1)
    ldMax = 0
    For liCnt2 = 0 To UBound(lsWord2)
        If Not lbMatched(liCnt2) Then
            ldCur = FuzzyMatch(lsWord1(liCnt1), lsWord2(liCnt2))
            If ldCur > ldMax Then
                liCnt3 = liCnt2
                ldMax = ldCur
            End If
        End If
    Next
    lbMatched(liCnt3) = True
    ldMatch(liCnt1) = ldMax
Next

'discard extra words
ldMax = 0
For liCnt1 = 0 To UBound(ldMatch)
    ldMax = ldMax + ldMatch(liCnt1)
Next
If lbDiscardExtra Then
    liCnt2 = 0
    For liCnt1 = 0 To UBound(lbMatched)
        If lbMatched(liCnt1) Then
            liCnt2 = liCnt2 + 1
        End If
    Next
Else
    liCnt2 = UBound(lsWord2) + 1
End If

'return overall similarity
FuzzyMatchByWord = 100 * (ldMax / liCnt2)


End Function

Function FuzzyMatch(Fstr As String, Sstr As String) As Double

'' Code sourced from: http://www.mrexcel.com/pc07.shtml
' Credited to: Ed Acosta
' Modified: Joe Stanton
'

Dim L, L1, L2, M, SC, T, R As Integer

L = 0
M = 0
SC = 1

L1 = Len(Fstr)
L2 = Len(Sstr)

Do While L < L1
    L = L + 1
    For T = SC To L1
        If Mid$(Sstr, L, 1) = Mid$(Fstr, T, 1) Then
            M = M + 1
            SC = T
            T = L1 + 1
        End If
    Next T
Loop

If L1 = 0 Then
    FuzzyMatch = 0
Else
    FuzzyMatch = M / L1
End If

End Function

I am trying to compare account descriptions from a trial balance to a list of 30,000 past account descriptions and I want to find the 5 top results per account.

To give you an example:

Debug.Print FuzzyMatchByWord("Cash and Cash Equivalents", "Bank and Cash")
Debug.Print FuzzyMatchByWord("Cash and Cash Equivalents", "Cash and Bank")
Debug.Print FuzzyMatchByWord("Cash and Cash Equivalents", "Shack sequential")
Debug.Print FuzzyMatchByWord("Cash and Cash Equivalents", "Sequential shack")

Returns:

75 
75 
37.5 
37.5

I would want the relative placement of a word in a phrase to count more towards the score and I would also prefer the order of the letters have a bigger impact. Sequential shack should not have scored that high compared to Cash and Cash Equivalents.

Randomly select data from multiple sheets in Excel [closed]

$
0
0

Sample Data

I have data of various companies arranged in different sheets date-wise.

How can I select randomly any number of sample (say 10) where data can be extracted from any sheets with the condition that there is letter Y in the corresponding row in column "H".

In other words, I need to refer to random rows from random sheets with the given criteria and get the result of the values in a separate sheet.

Found a somewhat similar post here1 and here2

Solution can be formula based but use of VBA is preferred as there is huge amount of data to be processed.

One approach may be to Collect data from multiple sheets into one with VBA code then apply autofilter and sort all rows with letter Y in column "H" and then select random sample. But with huge amount of data this process doesn't seem to be efficient as the sheet would be full of too much of data and create a problem.

The data can be filtered in their respective sheets first and then copied to a summary/master sheet and then sampling may be done.

Please, guide me in the right direction.

In case it is confusing some, the below code is what I have now as my working code (may not be the best option what I was looking for, before the question was closed- but it solved my purpose) and no longer need any answer. I have posted it just in case it may help someone in need:-

Sub Test()
    Call RunMacroTimes(3)                         'run macro 3 times
End Sub

Sub RunMacroTimes(ByRef Times)
    Do
        Application.Run "'Book1.xlsm'!CopyRandomFilteredRowsMultipleSheets"
        Times = Times - 1
        DoEvents
    Loop Until Times = 0
End Sub
Sub CopyRandomFilteredRowsMultipleSheets()
    Dim wb     As Workbook
    Dim ws     As Worksheet
    Sheets("yes").Cells.Clear
    'apply filter to sheets
    For Each ws In Sheets(Array("Sheet1", "Sheet2", "Sheet3", "Sheet4"))
        If ws.AutoFilterMode Then ws.AutoFilterMode = False
        ws.Range("A1").AutoFilter 1, "asdf"
    Next ws
    Dim rngVisible As Range
    Dim arr    As Range
    Dim CellsToCount As Long
    Dim RandCell As Range

    Dim wf     As WorksheetFunction
    Set wf = Application.WorksheetFunction
    Sheets("Sheet"& wf.RandBetween(1, 4)).Activate
    Set rngVisible = ActiveSheet.Range("A1:A20").SpecialCells(xlCellTypeVisible)
    CellsToCount = Int(Rnd * rngVisible.Count) + 1
    With ActiveSheet
        For Each arr In rngVisible.Areas
            If arr.Cells.Count >= CellsToCount Then
                Set RandCell = arr.Cells(CellsToCount)
                Exit For
            Else
                CellsToCount = CellsToCount - arr.Cells.Count
            End If
        Next
        RandCell.Select
        ActiveSheet.Range(Selection, Selection).EntireRow.Copy
    End With
    With Sheets("yes")
        .Range("A"& .Rows.Count).End(xlUp).Offset(1).PasteSpecial xlPasteValues
    End With
End Sub
Sub ClearFilterFromAllSheets()
    For Each ws In Sheets(Array("Sheet1", "Sheet2", "Sheet3", "Sheet4"))
        If ws.AutoFilterMode Then ws.AutoFilterMode = False
    Next ws
End Sub

Is it possible to read Excel data from specific cells using PX.Data.XLSXReader?

$
0
0

Is it possible to read Excel data from specific cells using PX.Data.XLSXReader? I'm trying to read a specific column from an Excel file using Acumatica's XLSXReader library but I have been unable to find a function to get the information of a specific cell(s) - e.g. H7. It would appear that I need to define an index for the columns in order to iterate and get the information. However, in my case the excel file does not include information in the first row, and we are unable to modify it because it's automatically generated by a third party. This is my action:

    [PXUIField(DisplayName = "Upload Data", MapEnableRights = PXCacheRights.Select, MapViewRights = PXCacheRights.Select, Visible = true)]
    [PXButton()]
    public virtual IEnumerable uploadFileBatch(PXAdapter adapter)
    {
        string complete = "";
        if (this.NewFilePanel.AskExt() == WebDialogResult.OK)
        {
            PX.SM.FileInfo info = PXContext.SessionTyped<PXSessionStatePXData>().FileInfo[SessionKey] as PX.SM.FileInfo;
            byte[] bytes = info.BinData;
            List<string> pONotFound = new List<string>();
            using (PX.Data.XLSXReader reader = new XLSXReader(bytes))
            {
                reader.Reset();
                Dictionary<String, Int32> indexes = reader.IndexKeyPairs.ToDictionary(p => p.Value.ToUpper(), p => p.Key);
                while (reader.MoveNext())
                {
                    //This is correct when there is info in the first row with those titles
                    string data = reader.GetValue(indexes["TITLE"]).Trim() + "\n";
                    //However I would like to do something like this
                    string data2 = reader.GetValue("H7").Trim() + "\n";
                }
            }
        }
    }

Also, I have noticed that when I don't include

 Dictionary<String, Int32> indexes = reader.IndexKeyPairs.ToDictionary(p => p.Value.ToUpper(), p => p.Key);

the code doesn't iterate with

 reader.MoveNext()

I understand why Acumatica uses the first row to identify the columns and help with the mapping during the upload of documents - but I'm thinking of managing the library with more flexibility - if possible.

Adding Source File Name to First Column of Workbook (VBA)

$
0
0

I'm fairly new to using VBA, but I currently have a code written that does the following:

  • Searches within a folder, all excel files which contain a specific worksheet, and outputs in to a master sheet.

I am trying to add a column, either at the beginning or end of the master sheet which indicates the file source name. My code is the following

Sub CombineWorkbooks()

    'Declare the variables
    Dim arrFiles() As String
    Dim strPath As String
    Dim strFile As String
    Dim wkbDest As Workbook
    Dim wksDest As Worksheet
    Dim wkbSource As Workbook
    Dim wksSource As Worksheet
    Dim SourceRange As Range
    Dim SourceRowCount As Long
    Dim NextRow As Long
    Dim LastRow As Long
    Dim LastCol As Long
    Dim FileCnt As Long
    Dim Cnt As Long
    Dim i As Long
    Dim CalcMode As Long

    'Specify the path to the folder containing the files
    strPath = "FOLDER PATH\"'Make sure that the path ends in a backslash
    If Right(strPath, 1) <> "\" Then strPath = strPath & "\"'Check if the path exists
    If Len(Dir(strPath, vbDirectory)) = 0 Then
        MsgBox "The path to your folder does not exist.  Please check"& vbCrLf & _
            "the path, and try again!", vbExclamation
        Exit Sub
    End If

    'Get the first Excel file from the folder
    strFile = Dir(strPath & "*.xls", vbNormal)

    'Fill the array with a list of Excel files in the folder...
    FileCnt = 0
    Do While Len(strFile) > 0
        '...except this workbook, in case it's in the same folder
        If strFile <> ThisWorkbook.Name Then
            FileCnt = FileCnt + 1
            ReDim Preserve arrFiles(1 To FileCnt)
            arrFiles(FileCnt) = strFile
        End If
        'Get the next Excel file from the folder
        strFile = Dir
    Loop

    'If no Excel files were found, exit the sub
    If FileCnt = 0 Then
        MsgBox "No Excel files were found...", vbExclamation
        Exit Sub
    End If

    'Change the settings for Calculation, DisplayAlerts, EnableEvents,
    'and ScreenUpdating
    With Application
        CalcMode = .Calculation
        .Calculation = xlCalculationManual
        .DisplayAlerts = False
        .EnableEvents = False
        .ScreenUpdating = False
    End With

    'Create a new workbook with one worksheet
    Set wkbDest = Workbooks.Add(xlWBATWorksheet)

    'Set the destination worksheet
    Set wksDest = wkbDest.Worksheets(1)

    'Specify the row in which to start copying the data
    NextRow = 1

    'Loop through each Excel file in the array...
    Cnt = 0
    For i = LBound(arrFiles) To UBound(arrFiles)

        'Open the current file
        Set wkbSource = Workbooks.Open(strPath & arrFiles(i))

        'Set the source worksheet
        On Error Resume Next
        Set wksSource = wkbSource.Worksheets("Worksheet you are looking to import")
        On Error GoTo 0

        'Check if the worksheet exists
        If Not wksSource Is Nothing Then

            With wksSource

                'Find the last used row in Column A
                LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row

                'Find the last used column in Row 1
                LastCol = .Cells(1, .Columns.Count).End(xlToLeft).Column

                'Check if the worksheet contains data beyond column headers
                If LastRow > 1 Then

                    'Increase the count by one
                    Cnt = Cnt + 1

                    'Set the source range...
                    If Cnt = 1 Then
                        '...including the column headers
                        Set SourceRange = .Range("A1", .Cells(LastRow, LastCol))
                    Else
                        '...excluding the column headers
                        Set SourceRange = .Range("A2", .Cells(LastRow, LastCol))
                    End If

                    'Count the number of rows in the source range
                    SourceRowCount = SourceRange.Rows.Count

                    'If there aren't enough rows in the destination sheet,
                    'exit the sub
                    If NextRow + SourceRowCount - 1 > wksDest.Rows.Count Then
                        MsgBox "Sorry, there are not enough rows available "& _
                            "in the destination worksheet!", vbExclamation
                        wkbSource.Close savechanges:=False
                        GoTo ExitSub
                    End If

                    'Copy the data from the source range to the destination sheet
                    SourceRange.Copy
                    With wksDest.Cells(NextRow, "A")
                        .PasteSpecial Paste:=xlPasteValues
                        .PasteSpecial Paste:=xlPasteFormats
                    End With

                    'Determine the next available row
                    NextRow = NextRow + SourceRowCount

                End If

            End With

            'Set the object variable for the source worksheet to Nothing
            Set wksSource = Nothing

        End If

        'Close the current file, without saving it
        wkbSource.Close savechanges:=False

    Next i

    'Check if any data has been copied to the destination worksheet
    If Cnt > 0 Then

        'Select the first cell and change the width of the columns to
        'achieve the best fit
        With wksDest
            .Cells(1).Select
            .Columns.AutoFit
        End With

    Else

        'Display message box advising user that no data was available to be copied
        MsgBox "No data was available to be copied...", vbInformation

        'Close the destination workbook, without saving it
        wkbDest.Close savechanges:=False

    End If



ExitSub:

    'Restore the settings for Calculation, DisplayAlerts, EnableEvents,
    'and ScreenUpdating
    With Application
        .Calculation = CalcMode
        .DisplayAlerts = True
        .EnableEvents = True
        .ScreenUpdating = True
    End With

End Sub

Any help would be greatly appreciated!

Choosing Specific Tab on Internet Explorer by number because i have similar title

$
0
0

i need to make this code work by changeing number of the tab without title filtring Sub accessExistingIEBrowser()

  On Error Resume Next

  boolWindowFound = False
  Set objShell = CreateObject("Shell.Application")
  WinCount = objShell.Windows.Count
  For winNo = 0 To (WinCount - 1)

      strURL = objShell.Windows(winNo).document.Location
      strTitle = objShell.Windows(winNo).document.Title
      If strTitle Like "Sample Form" Then
          Set IE = objShell.Windows(winNo)
          boolWindowFound = True
          Exit For
      Else
      End If

  Next

  If boolWindowFound Then
    Set doc = IE.document
    doc.getElementsByName("fname")(0).Value = "HHHH"
  End If

 End Sub

Getting data by checking the boxes on the web page

$
0
0

I would like to get data for certain date ranges from a website. The site address is "http://arsiv.mackolik.com/Canli-Sonuclar". There are boxes in this address that should be selected or not selected. "Futbol (futbol-text)", "Basketbol (basketbol-text)" will be selected from these boxes. "Tarihe Göre (aOrderBydate)" will be selected. But "Duello (chkDuel)", "Iddaa (chkIddaa)", "Canlı (chkLive)" and "Seçili (chkSelected)" will not be marked. In line with these preferences, I would like to pass all the data in the "list-table" table together with the link addresses. For example, I'll take a month's data in one go and transfer it to the excel sheet. I haven't written a code about it or changed a code.

VBA: Range.Formula Returns Application Defined or Object Defined Error

$
0
0

For my code, I am trying to find the difference between an objects value from two different days.

Sub GoingBack()

numberCube = InputBox("Which file are we going back to?")
numberYest = numberCube - 1

Workbooks.Open ("C:\Users\user\Downloads\file ("& numberCube & ").xlsx")
Workbooks.Open ("C:\Users\user\Downloads\file ("& numberYest & ").xlsx")

Set Work1 = Workbooks("file ("& numberCube & ").xlsx")
Set Work2 = Workbooks("file ("& numberCube - 1 & ").xlsx")

'Add the Time Difference Column (AA--27)
LastRow67 = Work1.Sheets("67").Cells(Rows.Count, 2).End(xlUp).Row
Work1.Sheets("67").Cells(1, 27).Value = "Time Clock Difference"
Work1.Sheets("67").Cells(1, 27).FormulaR1C1 = "=RC[-15]-VLOOKUP(RC[-21], '[file ("& numberYest & ").xlsx]67'!$F:$L, 7, FALSE)"
Work1.Sheets("67").Range("AA2").Select
Selection.AutoFill Destination:=Range("AA2:AA"& LastRow67)

Work1.Close savechanges:=True
Work2.Close savechanges:=True

End Sub

The line that is throwing the "Application Defined or Object Defined" error is:

Work1.Sheets("67").Cells(1, 27).FormulaR1C1 = "=RC[-15]-VLOOKUP(RC[-21], '[file ("& numberYest & ").xlsx]67'!$F:$L, 7, FALSE)"

I have tried using Range.Formula, and that threw the error as well.

Work1.Sheets("67").Range("AA2").Formula = "=L2-VLOOKUP(F2, '[file ("& numberYest & ").xlsx]67'!$F:$L, 7, FALSE)"

Any help would be appreciated. Thank you so much.

EDIT: I typed in the formula in Excel, and it works. I recorded the inputting of the formula, and the below is the result. I clicked/referenced columns F through L, so I'm not sure why it is only displaying C6:C12 below.

ActiveCell.FormulaR1C1 = "=RC[-15]-VLOOKUP(RC[-21],'[file.xlsx]67'!C6:C12,7,FALSE)"

Split Rows in Power Query

$
0
0

How would I be able to group rows evenly between a a dynamic number of a cell?

1000 rows, need to split into 10, and for each row it will like the below

Index | Group
1     | 1
99    | 1
101   | 2
200   | 3
500   | 6
900   | 10
1000  | 10

VBA copy formula into last row with data (based on different column) not working

$
0
0

I cant get this run even after trying all sort of dim possibilities. I want to pull down the formula results of col M only until the last row with data based on column G (which would be row 23). The formula now gets dragged down until row 224.

Also, i need to pull down formulas for col N and O based on last row with data based on column H (which would be row 24). Also here, the formula gets pulled down to 224 instead of row 24.

What am I doing wrong? I know that for column N and O I will need to create a second dim based on column H, but want to get one dim running first and then try the second dim.

Dim LastRow As Long LastRow = ActiveSheet.Cells(ActiveSheet.Rows.Count, 8).End(xlUp).Row

Range("M2").Select
ActiveCell.FormulaR1C1 = "=IFERROR(RC[-6]/'Sheet1'!R1C2,0)"
Range("N2").Select
ActiveCell.FormulaR1C1 = "=IFERROR(RC[-6]/'Sheet1'!R1C2,0)"
Range("O2").Select
ActiveCell.FormulaR1C1 = "=IFERROR(RC[-3]/'Sheet1'!R1C2,0)"

Range("M2").Select
Selection.AutoFill Destination:=Range("M2:M2"& LastRow)
Range("M3:M"& LastRow).Formula = "=G3&"",""&L3"


Range("M2").Select
ActiveCell.FormulaR1C1 = "=IFERROR(RC[-6]/'Sheet1'!R1C2,0)"
Range("N2").Select
ActiveCell.FormulaR1C1 = "=IFERROR(RC[-6]/'Sheet1'!R1C2,0)"
Range("O2").Select
ActiveCell.FormulaR1C1 = "=IFERROR(RC[-3]/'Sheet1'!R1C2,0)"

Range("M2").Select
Selection.AutoFill Destination:=Range("M2:M2"& LastRow)

Range("N2:O2").Select 'changed from M2 to N2

Selection.AutoFill Destination:=Range("N2:O2"& LastRow) 'changed from M2 to N2

'Range("N2:O2"& LastRow).FillDown
Range(Selection, Selection.End(xlDown)).Select

How can I make my request asynchronously without importing a new file

$
0
0

Hello I am trying to perform a soap call but sometimes the response is thousands of record. I don't want excel frozen while it is processing the responses but every example I've seen require importing a separate file with the async callback. Is there a way I can do this without the extra file?

Dim t As XMLHTTP60
Dim r As MSXML2.DOMDocument60
Dim nodeList As IXMLDOMNodeList
Dim i As Integer
Dim listLengthControl As Integer
Dim listCounter As Integer
Dim xmlHelper As AsyncHelper

  i = 0
   Set t = Transport
   Set xmlHelper = New AsyncHelper
       xmlHelper.init t
   t.Open "POST", EndPointUrl, aSync


   t.send Text

   Set r = New MSXML2.DOMDocument60
   r.aSync = False
   r.validateOnParse = False
   r.SetProperty "SelectionNamespaces", " xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'"
   r.LoadXML t.responseText

   Set nodeList = r.SelectNodes("//result//"& currentTableAltIden)
   listLengthControl = nodeList.Length

   While listCounter <> listLengthControl
      For i = LBound(altIdentifiers) To UBound(altIdentifiers)
                  Debug.Print r.SelectNodes("//result//"& currentTableAltIden & "//"& altIdentifiers(i))(listCounter).Text
                  WorkWebServiceTemp.Cells(TableDataRowNum + listCounter, i + 1).value = r.SelectNodes("//result//"& currentTableAltIden & "//"& altIdentifiers(i))(listCounter).Text
      Next i
      listCounter = listCounter + 1
   Wend


End Function ```

Padding a specific number within a string [closed]

$
0
0

I am looking for some help on a formula to pad a specific number within a string.

A typical data set would be like the following:

FD50-U-98-1

FD152-U-2-10

DEM-FD50-U-98-15

DS987-U-XD1498-1

DS987-U-SDD1659-1

within this dataset:

  • for the first three, the third sequence needs to be padded to four digits (I know you can use =TEXT(CELL,"0000") to get that formatting).

  • for the last two, I need the "1498"/"1659" to be padded to 5 digits

The main issue I am having is being able to extract those number to pad it and reinsert it.

Rules:

  • When there's a "DEM", the fourth grouping needs to be modified.
  • when there is a "DS", the third grouping numbers (there will always be letters preceding the third grouping, sometimes it's 1 or 2 or 3 letters) needs to be padded to 5 digits.
  • else, the third grouping needs to be padded to 4 digits

How to automatically apply specific math calculation to active cell? [closed]

$
0
0

I would like to apply a specific math calculation to the selected cell automatically rather than doing it manually. Specifically, I would want to take the active cell value such as =B1 and multiply it by .85 and divide by 3. Ie turn =B1 to =(B1*.85)/3. I would want to do the same formula no matter what the active cell is. How can I do this?

Set Excel VLOOKUP to dynamic external file

$
0
0

I've built an excel file that runs a VLOOKUP with an external file. The external file changes daily, and the naming/location of the file is dynamically set without a standard convention. So I've put together a small VBA script lets the user select the day's file, then sets the file path and file name of the xls file to look up in the table_array.
However...
Populating a cell with this data and then trying to reference that cell in the VLOOKUP is returning an error ("A value is not available to the formula or function"). If I manually input the full filepath and filename into the cell running the VLOOKUP it works fine. It seems to not understand that the value being passed in from the other cell is a real file path. Here is what I have:

B2 = fileName  (no dir path)
B3 = worksheetName
B4 = pathToFile
B5 = =CONCATENATE(B4&"["&B2&"]"&B3)
B7 = lookupValue
C7 = =VLOOKUP(B7,'B5'!$G:$I,3,FALSE)

C7 is obviously where I'm having the issue. Any and all help is greatly appreciated!

Compare two excel tables based on unique key using formula

$
0
0

I have two tables with same column names in excel which are getting data from two different sources based on certain calculations. We need to compare data between those two tables based on ID column value which will be provided by user in A2. I have attached snapshot of sample tables. I did try using sumproduct (as you can see in K2, but it doesn't work if any of the cell values has #NA as it's value. Please keep in mind that calculations update data for only a particular id (one row only for each table). in this example, values for only the rows with ID 200 will be updated for these two tables.

If I change value from #NA to an integer, formula (in K2) would work. Now I was even thinking about using if(And(logic1,logic2...)) to compare cell to cell values,but I don't kow how would I use it when the placement of ID's in columns C and G can vary and won't necessarly be in the same row.

Formula used:

=IF(G2:G5=A2,IF(SUMPRODUCT((G2:G5=A2)*(H2:I5))-SUMPRODUCT((C2:C5=A2)*(D2:E5))=0,"Match","No Match"),"")

enter image description here

Viewing all 88896 articles
Browse latest View live


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