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

Refresh pivot tables but not external data source

$
0
0

I have a spreadsheet with multiple tables, where the data is pulled from an external data source (SQL database). The connections/tables refresh by changing an option in a drop down box and then pressing a button to run a VBA.

Attached to each of these tables is a pivot table. The pivot tables don't refresh with the tables. If I try pressing refresh all I get the error;

'Data Source name not found and no default driver specified'

However if I go through the spreadsheet and hit refresh on each individual pivot table they update without the error.

So either I need some way to get the pivot tables to refresh with the tables or have a button that refreshes only the pivot tables and not the external data connections.

Any ideas appreciated, I don't know where to begin with this one!


Is an array inside a select case statement possible?

$
0
0

I just want to know if it is possible for me to assign an array and use it as a qualifier inside a case statement?

Sub AccountCopy()
Dim Criteria1 As Variant
Dim Criteria2 As Variant
Dim Acct As Variant
Dim NR As Integer

Criteria1 = Array("Checking", "Savings")
Criteria2 = Array("Loans", "Credit Card")

MonthSheet.Range("T1") = "Title"
MonthSheet.Range("U1") = "Account"
MonthSheet.Range("V1") = "Description"
MonthSheet.Range("W1") = "Amount"
MonthSheet.Range("X1") = "Date"
MonthSheet.Range("Y1") = "Category"

With Range("T1:Y1")
    .Font.Name = "Calibri"
    .Font.Size = 8
    .Font.Bold = True
    .HorizontalAlignment = xlCenter
    .Style = "Title"
    .Columns.AutoFit
End With



For Each Acct In [AccountNameList]
    Select Case Acct.Offset(0, 1).Value
        Case Is = Criteria1
            NR = Range("T"& Rows.Count).End(xlUp).Row + 1 'Next Row
            'MonthSheet.Range 
        Case Criteria2
    End Select

Don't criticize me too hard, I'm still pretty new to this. I don't post on fourms very often, but their are some really talented people on here and I thought who better to ask then the people that have been coding for years? Thanks in advance!

This is what I want to accomplish: I want to define the "Criteria1" Array to how ever many dimensions I so desire. Perhaps I want to add a third criteria to the list. Rather than going and changing the case statement, I would rather just add to the array later on down the line to include that additional qualifier. Perhaps I've set the wrong type? I don't know? I feel like this can be done rather easy but I am missing a very small detail.

Sorting excel based on color

$
0
0

Im trying to sort the data based on colour and record that action and repeat it. But my prblm is I need to sort even if the data is not present in rows and columns.can anyone please help me out about this.

Get rid of multiple html tags in python using SQL query as data source

$
0
0

I have a SQL query being loaded in Python and a column in the data has multiple html tags in each record. Within the tags is description data that I need. How does one remove the html tags and keep the text so then be able to export the cleaned data to Excel?

How to create Python code to read data from Excel file and create XML files

$
0
0

I need help with creation of Python code to Create XML's using data in an Excel sheet. I am not a Python expert. I tried to create a piece of code below. The code just reads data from Excel but I am not sure how to write a code to convert that into an XML format.

The column in the Excel represents XML tags and rows represent unique data points

The code needs to create multiple XML files using the data points in the Excel file

Please find the code below. I have tried multiple things but couldn't complete the code.

 import xlrd

 ExcelFileName= 'Data.xlsx'
 workbook = xlrd.open_workbook(ExcelFileName)
 worksheet = workbook.sheet_by_name("Sheet1")
 num_rows = worksheet.nrows
 num_cols = worksheet.ncols
 result_data = []

 for curr_row in range(0, num_rows, 1):
     row_data = []

     for curr_col in range(0, num_cols, 1):
         data = worksheet.cell_value(curr_row, curr_col)
         print(data)
         row_data.append(data)

     result_data.append(row_data)

disable formatting while copy paste operation in excel

$
0
0

I'm come around with the following code to disable to formatting while cell copy paste operation-

Private Sub Worksheet_Change(ByVal Target As Range)
    With Application
        .EnableEvents = False
        myValue = Target.Formula
        .Undo
        Target.Formula = myValue
        .EnableEvents = True
    End With
End If
    Application.CutCopyMode = False
End Sub

Code works perfect but it insert many other issues in the sheet.

  1. Not able to use the undo/redo functionality
  2. Not able to change the focus of cell in single click.

Any idea would be appreciated.

Sequential reading of file names in a folder using excel VBA

$
0
0

I am trying to read nearly 1000 files in a folder using VBA. I wish the code to pick the file name in an incremental order such as Dummy3_1, Dummy3_2, Dummy3_3, etc. But instead, the current code picks Dummy3_10 after Dummy3_1. How I could make the code to read the file name sequentially. Thanks

Application.ScreenUpdating = False
    With Application.FileDialog(msoFileDialogFolderPicker)
        .Title = "Please select a folder"
        .ButtonName = "Pick Folder"
        If .Show = 0 Then
            MsgBox "Nothing was selected"
            Exit Sub
        Else
            FileDir = .SelectedItems(1) & "\"
        End If
    End With
FiletoList = Dir(FileDir & "")
    Do Until FiletoList = ""

How do I pass a char list by reference from VBA to an external .NET dll?

$
0
0

I'm trying to use a call in a library which is requesting a char array and I'm not sure how I can provide that through VBA.

Every call I'm trying to make is causing excel to crash fantastically with no error message or feedback.

Here is the documentation I'm looking at (With function name changed):

FunctionABC( unsigned short nCount,
char *ServiceName,
unsigned short Starting,
char *Point[], 
unsigned short nPoint,
double Value[],
char *Time[],
unsigned short nTime,
char *Status[], 
unsigned short nStatus,
char *Desc[],
unsigned short nDesc,
char *Units[],
unsigned short nUnits
);

The return value is an integer where a non-zero number is returned if the call is unsuccessful.

Here is the code I wrote in excel...

Public Declare PtrSafe Function FunctionABC Lib "SOMEAPI.dll" (ByVal nCount As Integer, _
    ByVal ServiceName As String, ByVal nStarting As Integer, Point() As String, _
    nPoint As Integer, value() As Double, Time() As String, nTime As Integer, _
    Status() As String, nStatus As Integer, Desc() As String, nDesc As Integer, Units() As String, _
    nUnits As Integer) As Integer

Sub test()

Dim nCount As Integer
Dim ServiceName As String
Dim nStarting As Integer

nCount = 1
ServiceName = "DMS.UNIV5"
nStarting = 0

Dim Point(1) As String
Dim nPoint As Integer
Dim value(1) As Double

Dim Time(1) As String
Dim nTime As Integer
Dim Status(1) As String
Dim nStatus As Integer
Dim Desc(1) As String
Dim nDesc As Integer
Dim Units(1) As String
Dim nUnits As Integer

Dim retval As Integer

retval = FunctionABC(nCount, ServiceName, nStarting, Point, nPoint, value, Time, nTime, Status, nStatus, Desc, nDesc, Units, nUnits)

End Sub

So trying to run this code in VBA freezes the UI and causes excel to restart. I don't get any feedback or error message so it's difficult to tell what the issue is, but I'm really not sure how to pass an unsized char array by reference from VBA over to this DLL like the documentation is requesting, and searching around has not provided any clear results.

I tried a lot of variations of this call, adding and removing symbols, using different data types like ListObject, trying to dynamically resize, and such but no luck, everything I pass in makes excel implode on itself.

At one point, having unsized arrays declared caused excel to crash when I tried to just 'view' the code. I ended up having to disable macros and go into Visual Studio to specify an array size in order to stop the crashes from happening.

The most frustrating thing about all of this is that there is no error message or log for me to debug so I'm just blindly guessing at this point on what is going on.


How to rewrite excel formulas in a readable manner?

$
0
0

I have an Excel file with formulas in this manner:

=IF(OR(ISERROR(G16),ISERROR(G17)),X16,IF(OR(G16="xxx",G16="yyy",G16="zzz"),Y16,IF(G16="333","N\A",IF(G17="333",Z16,IF(D17="",IF((HEX2DEC(W$10)-HEX2DEC(W16))/VLOOKUP(F16,$M$36:$N$41,2,FALSE)<0,0,(HEX2DEC(W$10)-HEX2DEC(W16))/VLOOKUP(F16,$M$36:$N$41,2,FALSE)), IF((HEX2DEC(W17)-HEX2DEC(W16))/VLOOKUP(F16,$M$36:$N$41,2,FALSE)<0,0,(HEX2DEC(W17)-HEX2DEC(W16))/VLOOKUP(F16,$M$36:$N$41,2,FALSE)))))))

I would like to simplify them so it will be written in a more readable manner.

  • Can I edit/write Excel formulas in indented way?
  • What kind of simplifications can I do?
  • Should I use an VBA script instead of Excel's formulas?

Outputting the number of y's in one column that correspond to a condition in another column

$
0
0

I'm struggling to output the number of "y"s that correspond to the last 5 "a"s in a data set of two columns, for example the first column contains cells occupied by either an "a" or "b". The second column contains cells that contain either a "y" or an "n". Is there a way of outputting the number of y's in column 2 corresponding for the last 5 a's of column 1? (The a's and b's are in no particular order).

iterating over each cell in account number column and using that to read a excel file

$
0
0

I need to perform some data analysis on some excel files (that are saved as account number of respective customesr). I also have a master sheet with all the account numbers in a column. I need python to iterate over "Account Number" column in "MasterSheet.xlsx" and read the respective account's excel file (for eg: for account number 123, i have a "123.xlsx", that is in the same location as Master Sheet) and then assign that account number as their variable name. For a rough understanding of what i want to do, please refer the below code.I want to use pandas or openpyxl.

master = pd.read_excel("MasterSheet.xlsx")

for account in master.iterrows():
    filename= str(account)+'.xlsx'
    account= pd.read_excel(filename)

You can see, i have tried to create a filename from each account number read via for loop. And then assign the account number as the variable name for each account's dataframe.

I know this is a very badly framed question but i tried and couldn't frame it better. I have just started using python. Please help. I am stuck here. If you need any further information, ask. But please help.

Reverse an array in Excel VBA

$
0
0

I have the following code, which based on the logic it should work.

I want it to be (4,3,2,1), but at the end of the loop I get t=(4,3,3,4)

Sub try()

  Dim t As Variant

  t = Array(1, 2, 3, 4)
  a = UBound(t)

  For k = 0 To a
    t(k) = t(a - k)
  Next k

End Sub

Any ideas?

populate combobox from an excel sheet based on listbox selection (multiselect enabled)

$
0
0

I have a listbox with 3 values and multi select option enabled. Based on the values selected, I want to populate a combobox by referring to certain ranges in excel sheet. The code below works if only one value is selected from listbox. I know it will not work for multiple selections, but I am unable to write code to loop through the list of selections and then add corresponding ranges to combo box.

So, if I select customer1 and customer2, i want the values in ranges d3:d34 AND c4:c24 populated in the combobox. similarly for other combinations too. However, if one of the values is unselected, corresponding values should be cleared from the combobox.

If I were to save all the selected items in listbox in an array, how do i do a "search" or "find" for each of the values stored in the array?

Please suggest how I could revise this code.

Thank you!

Private Sub Combobox1_DropButtonClick()

    Dim curSelected As String
    Dim i As Integer

    For i = 0 To Listbox1.ListCount - 1
        If Listbox1.Selected(i) Then
            curSelected = Listbox1.List(i)
                If curSelected = "customer1" Then
                    ChooseDeals.List = Sheets("Sheet3").Range("d4:d34").Value
                ElseIf curSelected = "customer2" Then
                    ChooseDeals.List = Sheets("Sheet3").Range("c4:c24").Value
                ElseIf curSelected = "customer3" Then
                    ChooseDeals.List = Sheets("Sheet3").Range("e4:e20").Value
                End If
          End If
    Next i


End Sub

filterbased ranking in powerpivot table

$
0
0

I hope you might be able to help me. My table (T-Brand) consist of the following columns:

Category, Subcategory, Segment, Brand: Benefit, Brand : Benefit, Timeslots, the brands itself and their respective sales also one column (dynamicRank) in which I want to rank the brand sales.

I use this formula to calculate the brand sales for each brand for each category, benfit, brand and timeslots (e.g. years, quarter, etc) combination. This seems to work well.

CALCULATE(SUM('T-Brand'[Value]);ALLEXCEPT('T-Brand';'T-Brand'[Product: Category];'T-Brand'[Product: Brand (global)];'T-Brand'[Product: Benefit];'T-Brand'[Timeslots]))

….but instead of the calculated sales value I am "just" interested in the ranking of each brand based on the above filters. I tried to use RANKX but I am not able to make the ranking based on the filters. it is alway showing me the rank of a brand in the total table not the filtered one..

How do I create a normal distribution graph on Excel? [closed]

$
0
0

I have already used the Norm.Dist function, but the results show like this

enter image description here


Create a True Count to select most likely possible column

$
0
0

I am importing data from an excel file and am trying to locate certain information from their relevant columns by using RegEx to locate columns that have the data that I am looking for. However, the regex is imperfect because sometimes the expressions are found in more than one column. So to account for this basically I want to make some sort of internal counter that will count the number of times that a column has one of the Regular Expressions that I have defined in the set. An example for this is happening can be found below.

columnsWithDescription()
  {
    var refDesRegex = [/resistor/i,/capacitor/i,/res/i,/cap/i]

    var refDesColumnNumber = new Set();
    for (var expression of refDesRegex)
    {
      for (const row of this.data)
      {
        for (var cell = 0; cell<row.length; cell++)
        {
          if (expression.test(row[cell]))
          {
            refDesColumnNumber.add(cell)
          }
        }
      }
    }

data is the excel sheet that has been imported. It is an array of arrays where each array is a row of the excel sheet.

I have experimented with using the forEach method on the resulting Set but this results an overall true count and doesn't isolate the results from each column number. I want to run the test on each value of the set and see how many times the value in the column that matches the cell index returns true and then isolate that row so I can push it into an array later.

create multiple dataframes in loop and write to excel

$
0
0

I am running a loop over a function that produces a dataframe, that looks like this:

        Prd1    Prd2     Prd3    Prd4    Prd5    Prd6
Loc1    0        0        0        0       0       0
Loc2    0        0        0        0       0       0
Loc3    0      30.61      0        0   319.58   430.87  
Loc4    0        0        0        0       0    120.73
Loc5    0        0        0        0       0       0
Loc6    78.21  822.36     0        0       0       0

I want to run the function multiple times, to produce a series of dataframes to then analyse or visualise evolution over time.For this it would be ideal to have them all in one excel workbook. However I am struggling with this. I have tried

for case in CASES:
    B= A[case]
    result = function(B)
    print(result)
    with pd.ExcelWriter('results.xlsx') as writer:  # doctest: +SKIP
        result.to_excel(writer, sheet_name='case_'+str(case))

my hope was that this would write the different results into the same spreadsheet. However as a result the spreadsheet only contains a tab with the last case. I can see how the above being within the CASES loop will overwrite the existing sheet each time. Is there a function to preserve the sheets that already exist and "append" any new sheet to the existing workbook? Thanks in advance. regards P.

Matching data from two sources and simple calculations in excel VBA

$
0
0

I have some calculations i need to do on a data-set. The calculations are simple (i.e input 1 x input 2 = output), but they take inputs recorded in two different excel workbooks by different people. Due to the different input sources the parameters between the two are sometimes in different orders or with slightly different names - the picture attached should show what i mean.

My plan was to take the relevant sheet of input book 1, and the relevant sheet of input book 2, and copy them into a single workbook where i hope to match the parameters with some sort of lookup/find macro, and perform the calculations automatically using a loop to work across the headers and down the rows

combined worksheet concept

Would really appreciate any help.

How to stop Excel VBA from renaming variables and parameters in unrelated modules and methods?

$
0
0

I noticed unbelievable destructive behavior of Excel VBA. It silently and automatically renames variables and function parameters in unrelated modules when I add, say, a new property to class. Observed on Office Professional Plus 2016 and Windows 10.

For concrete example, I have one module and one class. Module looks like this:

Private Function MyRequests() As Collection
    Dim requests As Collection
    Set requests = New Collection
    Dim row As Integer
    row = 3
    Dim oRequest As New MyRequest
    oRequest.Name = "SomeName"
    requests.Add oRequest
    MyRequests = requests
End Function

Class MyRequest looks like this:

Private sName As String

Property Let Name(sValue As String)
    sName = sValue
End Property

Now the unbelievable part comes. I add new property to the MyRequest class:

Private iRow As Integer

Property Let Row(iValue As Integer)
    iRow = iValue
End Property

I save code, go to module and its private function which now looks like this:

Private Function MyRequests() As Collection
    Dim requests As Collection
    Set requests = New Collection
    Dim Row As Integer
    Row = 3
    Dim oRequest As New MyRequest
    oRequest.Name = "SomeName"
    requests.Add oRequest
    MyRequests = requests
End Function

Notice that row became Row! This silent auto-renaming also happens throughout the VBA code in sheets... Basically everywhere, Excel renamed row to Row!

So, my question is what can I do to stop this insane behaviour?

How to generate multiple json in vertical column in Excel VBA?

$
0
0

Using excel macro The first line is the json file name, and the second and subsequent columns are the values.

With the first column as the key to the json object, only the values ​​in the second column and only the values ​​in the third column.

How do I generate json in batches in the same directory as the Excel respectively?

For example, column B is the value of column A as a key, the value of column B and b1.json. Column C uses the value of Column A as a key and the value of Column C and c1.json

For example, when the completed json has a description up to column C,

b1.json

[{
a2: b2,
a3: b3,
a4: b4,
}]

c1.json

[{
a2: c2,
a3: c3,
a4: c4,
}]

And want to be generated.

Viewing all 88667 articles
Browse latest View live


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