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

How to loop over columns with multiple ranges in Excel

$
0
0

I am trying to loop over columns to check if each cell in same row of my range Union(Range("A2:A5"), Range("C2:E5")) is not empty if it is highlight the empty cell then check for the second row of my range. I am not sure how to approach this problem since my range is a union of multiple columns. any help with that ?

enter image description here

Union(Range("A2:A5"), Range("C2:E5")).Columns.Count

I am getting 1 as a result even if I use this Union(Range("A2:A5"), Range("C2:E5")).end(xlToLeft).Columns ( I think I should get 2 instead)


How to compare and show differences on multiple columns in Microsoft Excel

$
0
0

I have a sheet with data in 2 columns, A and B:

--A--     --B--
Apple     57
Orange    62
Lime      45
Orange    58
Apple     57

What I want is, I need to search column A for duplicates, then if there are any, look for their value in column B. If they are different, I want to color the cell in column A to red, show the other value of that entry in column C, and show a message on how many indifferences there are. Something like this:

--A--     --B--   --C--
 Apple     57
 Orange    62       58
 Lime      45
 Orange    58       62
 Apple     57

Please help me with this, I know how to compare the value in one column, but then don't know how to search for additional value for them in the other column.

Grouping and exporting excel rows using python

$
0
0

This is using Python.

I have an excel sheet that in its most basic form looks like this

New York    Cup a   3
Stockholm   Plate b 5
Madrid  Cup a   2
New York    Cup b   5
New York    Plate a 8
Madrid  Cup b   9
Stockholm   Plate a 2
Stockholm   Cup a   5
Stockholm   Cup b   3
Madrid  Cup a   5
New York    Plate a 8

I want to group the locations together so that all the new yorks are together and madrids etc and export them to separate excel sheets called new york, madrid, stockholm. With the same info on the rows. So basically just a copy and paste of the row into a new excel sheet named after that row. Then I want to add all cups together as one and all plates as one on the second page of each one. Would make sense to do this before exporting the data right?

End result 3 excel sheets named, containing only their data, and some easy math on the second sheet.

The real excel sheet is dealing with 15000 rows 50 locations and 100 items. These change so would have to be a procedural way. New york might be Toronto next time.

So far I have been able to group them by pandas but every attempt after that as failed.

New to pandas so I thought this one would be relatively easy to do.

import pandas as pd

stock_report_excel = "small_stores_blocked_stock_value.xlsx"

df_soh = pd.read_excel(stock_report_excel, sheet_name='SOH')
df_stores = df_soh.groupby(['Site Name'])

guess loop to add to sheet

adding of the items to sheet 2

exporting

Does excel consume more memory while storing data into single pages rather than the multiple sheets?

$
0
0

When I try to create a sheet, is it better to write the data into different sheets or into a single sheet?.

Is memory consumption increased while data is writing into different sheets instead of a single sheet?

Skip csv file columns when importing to Excel

$
0
0

I'm trying to paste copied data from a csv file into Excel. When pasting the data, I need to skip a good portion of the columns that are included in the data. To this end, I've tried using FieldInfo with Text to Columns to create an array. I actually had success using this code 2 times. The columns that I wanted to skip (data type 9) were not imported and all the other columns were imported into my Excel sheet. For some reason, it doesn't seem to work anymore, so perhaps i made a minute change or I'm missing a small detail.

When running this code, the first column is skipped and not imported, but then all subsequent columns are imported. I've researched questions on this site and many others. I can't figure it out.

Any help is appreciated. Thanks in advance!

Here is the code I'm using:

Sub Test_PasteParsing()
    With ThisWorkbook.Sheets(1)
            Range("A1").PasteSpecial
    End With
    Columns("A:A").TextToColumns _
                Destination:=Range("A1"), _
                DataType:=xlDelimited, _
                TextQualifier:=xlDoubleQuote, _
                ConsecutiveDelimiter:=True, _
                Tab:=True, _
                Semicolon:=False, _
                Comma:=False, _
                Space:=False, _
                Other:=False, _
                OtherChar:=False, _
                FieldInfo:=Array(Array(1, 9), Array(2, 9), Array(3, 4), Array(4, 2), Array(5, 9), Array(6, 9), _
                    Array(7, 9), Array(8, 2), Array(9, 9), Array(10, 9), Array(11, 2), Array(12, 9), _
                    Array(13, 2), Array(14, 9), Array(15, 9), Array(16, 2), Array(17, 9), Array(18, 9), _
                    Array(19, 9), Array(20, 9), Array(21, 9), Array(22, 9), Array(23, 9), Array(24, 9), _
                    Array(25, 9), Array(26, 9), Array(27, 9), Array(28, 2), Array(29, 2), Array(30, 2), _
                    Array(31, 2), Array(32, 9), Array(33, 9), Array(34, 9), Array(35, 9), Array(36, 9), _
                    Array(37, 9), Array(38, 2), Array(39, 9), Array(40, 2), Array(41, 9), Array(42, 9), _
                    Array(43, 9), Array(44, 9), Array(45, 9), Array(46, 9), Array(47, 9), Array(48, 9), _
                    Array(49, 9), Array(50, 9), Array(51, 2), Array(52, 2), Array(53, 2), Array(54, 2), _
                    Array(55, 9), Array(56, 9), Array(57, 2), Array(58, 9), Array(59, 2), Array(60, 9), _
                    Array(61, 9), Array(62, 2), Array(63, 9), Array(64, 9), Array(65, 2), Array(66, 2)), _
                TrailingMinusNumbers:=True
End Sub

Excel - Replace " / " character within non-formula cells

$
0
0

For example i have two cells

A1: =1/2
A2: /abc

I want to replace / char in second cell with something else without changing first cell which contains formula. Final result should be like this

A1: = 1/2
A2: #abc

Excel Power Query - Filter rows by comparing two columns

$
0
0

I have a table in Excel that is self outer joined in Power Query Editor to create pairs

Table named Items
-----------------
Item   Value
A      1
B      2
C      3

I create a From Table/Range query that is closed and loaded to connection only that is named "Items"

let
    Source = Excel.CurrentWorkbook(){[Name="Table1"]}[Content],
    #"Changed Type" = Table.TransformColumnTypes(Source,{{"Item", type text}, {"Value", Int64.Type}})
in
    #"Changed Type"

Then another query is made that is a reflexive cross join

let
    Source = Items,
    #"Added Custom" = Table.AddColumn(Source, "Custom", each Items),
    #"Expanded Custom" = Table.ExpandTableColumn(#"Added Custom", "Custom", {"Item", "Value"}, {"Custom.Item", "Custom.Value"}),
    #"Renamed Columns" = Table.RenameColumns(#"Expanded Custom",{{"Custom.Item", "Item.2"}, {"Custom.Value", "Value.2"}, {"Value", "Value.1"}, {"Item", "Item.1"}}),
    #"Added Custom1" = Table.AddColumn(#"Renamed Columns", "Value", each [Value.1]*[Value.2])
in
    #"Added Custom1"

At this point the query shows 9 rows (3x3)

Item.1 Value.1 Item.2 Value.2 Value
A      1       A      1       1
A      1       B      2       2
A      1       C      3       3
B      2       A      1       2
B      2       B      2       4
B      2       C      3       6
C      3       A      1       3
C      3       B      2       6
C      3       C      3       9

I am struggling to edit the query so it will filter the results down to the cases of value.1 <= value.2

Item.1 Value.1 Item.2 Value.2 Value
A      1       A      1       1
A      1       B      2       2
A      1       C      3       3
B      2       B      2       4
B      2       C      3       6
C      3       C      3       9

The Power Query Editor UI does not seem to offer a x < y filter capability and I am not sure how to use the Power Query M formula language to filter the data the way I want.

Microsoft Power Query provides a powerful data import experience that encompasses many features. Power Query works with Analysis Services, Excel, and Power BI workbooks. A core capability of Power Query is to filter and combine, that is, to mash-up data from one or more of a rich collection of supported data sources. Any such data mashup is expressed using the Power Query M Formula Language. It's a functional, case sensitive language similar to F#.

Excel formula to match digits after concatenation

$
0
0

enter image description here

In the above image, I want to check on which row the input 1,2,3 & 4 are matching. So in this example I want result 3 as it has "1 1 0 0" and the box on the top also has "1 1 0 0".

I tried following array formula but it's not working.

=IF((C10:C25=C3)(D10:D25=C4)(E10:E25=C5)*(F10:F25=C6),G10:G25,"")

It would be great if this can be done without using any intermediate result columns.


VBA - comma/dot number format (US > EU (German))

$
0
0

Got a piece of code where are some parameters that I want to have with (,) instead of (.) What my code is doing, taking some system specific files (.dif) and convert them into .txt , but there I managed to convert Column A to certain date format (instead of US format), but problem is with another Columns. Column M to Column T are "Temperatures", and US format is with (.), so you have for instance 25.5 C or German (EU) is with (,) 25,5 C.

p.s. Temperatures are marked with T11, T21, T31 and so on...

What I wanted is to convert them all to Comma and I am not managing with .NumberFormat or changing it in Excel > Advanced > 1000 separator options.

I am getting .txt file but with still (.) and that makes me always unnecessary trouble when importing it to Power Query /BI > have to always remove previous step (not a lot of people is familiar with PBI and Editor, and when you say to someone to take care of it...people forgetting easily because you have lot of steps to do..)

This is part of the code:

Sub DoFolder(Folder, targetFolder As String)
Dim Workbook
Dim SubFolder

For Each SubFolder In Folder.SubFolders
        DoFolder SubFolder, targetFolder
Next
Dim File
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
For Each File In Folder.Files

    ' *** Operate on each file ***
    Set Workbook = Workbooks.Open(File)

    ' *** Sort, filter and rename each file/column ***
    If Workbook.FileFormat = -4158 Then
        Set Workbook = Workbook.ActiveSheet
            'Workbook.Columns("D:E").EntireColumn.Delete
            'Workbook.Columns("E").EntireColumn.Delete
            'Workbook.Columns("R:T").EntireColumn.Delete
            Workbook.Rows("1").Delete

            Range("A1:W1").Value = Array("Date/Time", "P0 [mbar]", "P1 [mbar]", "P3 [mbar]", "P7 [mbar]", "PS160 [mbar]", "P190 [mbar]", "P220 [mbar]", _
            "Q1 [ppb]", "Q2 [ppb]", "Q3 [ppb]", "Q4 [ppb]", _
            "T11 [°C]", "T21 [°C]", "T31 [°C]", "T12 [°C]", "T22 [°C]", "T32 [°C]", "T01 [°C]", "T02 [°C]", "FM1 [slm]", "FM2 [slm]", "FM3 [slm]")

            Workbook.Columns("A").NumberFormat = "dd.mm.yyyy hh:mm"
            'Workbook.Columns("M").NumberFormat = "#.###"
            'Workbook.Columns("N").NumberFormat = "#.###"
            'Workbook.Columns("O").NumberFormat = "#.###"
            'Workbook.Columns("P").NumberFormat = "#.###"
            'Workbook.Columns("Q").NumberFormat = "#.###"
            'Workbook.Columns("R").NumberFormat = "#.###"
            'Workbook.Columns("S").NumberFormat = "#.###"
            'Workbook.Columns("T").NumberFormat = "#.###"


    ' *** Preparing new folder for filtered/sorted files ***
        Dim FLDR_NAME As String
        FLDR_NAME = Mid(Application.ActiveWorkbook.Path, InStrRev(Application.ActiveWorkbook.Path, "\") + 1)
        Dim fso As Object
        Set fso = CreateObject("Scripting.FileSystemObject")

        FLDR_NAME = targetFolder & "\" & FLDR_NAME
        If Not fso.FolderExists(targetFolder) Then
               fso.CreateFolder (targetFolder)
        End If

        If Not fso.FolderExists(FLDR_NAME) Then
               fso.CreateFolder (FLDR_NAME)
        End If

    ' *** Save As Converter_Converted as separate file ***
        Dim newFileName As String
        newFileName = FLDR_NAME & "\" & Workbook.Name & ".txt"
        Application.DisplayAlerts = False
        Workbook.SaveAs FileName:=newFileName

    ' *** Close and SaveAs ***
        Application.ActiveWorkbook.Close
    End If
Next
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic

End Sub

After converting with VBA

PowerBI (Editor)

This in PBI Editor is auto- change type, what I dont wanna everytime to have.

As it should be!

On last picture from PBI, is actually what I wanted, but without further steps of replacing values and changing values.

Excel Chart Y Axis to Rollover Back to Zero at 360

$
0
0

I'm trying to create an Excel chart in VBA with time on the X axis and bearing angles (from North) on the Y axis. This looks fine most of the time except where the sample of data is dealing with Northerly bearings. In this case, we might get a sample with bearing values of 000.1, 000.2, 359.9, 359.8, 000.5 etc.. The chart Y axis then stretches from 0 to 360 with data at the bottom and data at the top with a lot of empty space in between. Is there any way that the Y axis can be configured to either restart at zero when it reaches 360 or split into two so that for example, it covers the range 0 to 5 and then the range 355 to 360? I'm simply asking whether this is feasible or not. I don't want to get too busy with coding just yet if it's a non-starter.

EDIT: - a couple of images to try and explain the problem. One image shows the sample of bearings to be around 90 degrees and it produces a nice Y axis. The second image shows the sample of bearings to be around 359-360 degrees with the odd one in the middle at 0 degrees Bearings at 90

Bearings at 360

For the sample with Bearings around 360, I would like to be able to either "rollover" the Y axis back to 0 as it reaches 360 or have a split Y axis such that the section between 5 degrees and 355 degrees is not visible.

Convert excel file from XLSX to XLSB in Java

$
0
0

I am using Java + Apache POI to generate an excel file (format xlsx/xls). Due to huge data the generated excel file (format xlsx/xls) takes more size (~50 MB).

So I am trying to convert xlsx/xls to xlsb to reduce the size of the excel file.

Here is the problem: Apache POI does not support writing to xlsb file. So what I am trying is:

  1. Generate a xlsx/xls file using Apache POI.
  2. After that convert generated xlsx/xls to xlsb. For this I am using SmartXls Java library. But this library is not open source. You need to buy license for this. Also I checked EasyXls Java library, but it also requires buying a license.

Below code is used to convert xlsx/xls to xlsb using SmartXls Java library:

WorkBook wb = new WorkBook();
wb.readXLSX(.../xlsxPath);
wb.writeXLSB(new java.io.FileOutputStream(.../xlsbPath));
wb.dispose();

Kindly someone help me whether any open source library is available for it or is there any other way to do this conversion in Java.

Thanks in advance.

Conditional formatting - highlighting in VBA

$
0
0

I am trying to make the VBA that highlights the entire row if the row contains a word "New".

The applying range of conditional formatting, I am trying to put maybe A1 till AZ2000

the reason, I also had a problem setting range as whole worksheet.

I never learned VBA so I am getting information from internet

I wrote this much but it is not working, to my knowledge, it should work but i don't know why it is not working, it is frustrating how, I fix one, and another problem comes up...lol

Sub Highlighting()

  'Definining the variables:
  Dim rng As Range
  Dim condition1 As FormatCondition

 'Fixing/Setting the range on which conditional formatting is to be desired
  Set rng = ("A1, AZ2000")

  'To delete/clear any existing conditional formatting from the range
   ws.FormatConditions.delete

  'This is where I get Syntax error, it says "New" needs list separator
  Set condition1 = ws.FormatConditions.Add(xlConditionValueFormula, xlGreater, "=FIND(""New"",$AF1)>0)")

  'Defining and setting the format to be applied for each condition
   With condition1
    .EntireRow.Interior.ColorIndex = 10498160
   End With

End Sub

enter image description here

this is how i want it set up in VBA

Calculate new columns from existing

$
0
0

I have excel files with anywhere from 30-35 columns and 50-1500 rows of data depending on the company. The columns in question are as follows; USED REMAIN REFUND. These three columns are made up of calculations from other columns.

USED is each row of GAL added up as it goes along so the excel calculation looks like this: starts with one =W2, then the next row is W2+W3 then W3+W4 and so on

REMAIN is ASSIGNED-USED

REFUND is GAL*CREDIT

Would something like this even be possible, currently I'm doing all the calculations in excel which is time consuming and after some research I figure it would be easier to code something to automate this. Grateful for any help even if its just the calculations for one column

I've looked for some ideas online and figure pandas is the best way of going about it, but if anything else is suggested I'm open to anything

import pandas as pd
filename = home/itdept/Documents/BestWines.xlsx
df = pd.read_excel(filename)
df['Refund'] = df['QUANTITY IN GAL']*df['CBMA Credit']
df.head(5)
df.to_excel("path to save")

This is what I came up with for the one column: Refund, I wasn't sure how/if I could incorporate all of the other columns in the code as well

VBA Find/Replace & Text Color Change

$
0
0

VBA Find/Replace & Text Color Change

I've a spreadsheet with three columns. Column A has some sentences in it (written in black font color). Columns C has a list of terms to search for. And column D has a list of replace terms (written in red font color).

I'm trying to search the sentences in column A for the search terms in column C. And, if column A contains any of the search terms in column C, replace the text in column A with the replace terms in column D.

The find/replace feature works great. But I haven't been able to get the font color of the replaced portion of the string in column A to turn red.

Any thoughts?

Here's the code I've got so far.

Private Sub CommandButton1_Click()

    For i = 3 To 6

    Worksheets("Sheet1").Range("A2:A35").Select

    Selection.Replace What:=Cells(i, 3).Value, Replacement:=Cells(i, 4).Value, _
    LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False

    Next

    Worksheets("Sheet1").Cells(1, 1).Select

End Sub

Excel VBA program crashing when selecting from listbox

$
0
0

I am really puzzled with some error causing crash and I don't know what it is. Can someone identify the problem?

https://www.dropbox.com/s/3l3q985y75n9nup/xxx.xlsb?dl=0

In form "SettingsForm" line containing Me.CheckBoxXlGrouped2.Value = .XlGrouped2 causes crash. In excel Ctrl+r, tab "SQL Tables and Columns" when you select something from the left listbox (listbox3) it will crash excel. However if you comment out Me.CheckBoxXlGrouped2.Value = .XlGrouped2 the program won't crash.


Can't solve error 1004 with VBA ExportAsFixedFormat

$
0
0

I've been putting up together a small macro in VBA to save a table as a PDF in Excel. This is the code I've written:

Sub ExportPDF()
    Dim File_name As String

    File_name = "C:\Test\"& _
      "Rapport du "& Date & "_Assurances.pdf"

    Sheets("Assurances.Rapport").Select

    Dim Last_row As String

    Last_row = "C1:Y"& Range("Z2").Value
    ActiveSheet.PageSetup.PrintArea = Last_row

    ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, _
    FileName:=File_name, Quality:=xlQualityStandard, _
    IncludeDocProperties:=True, IgnorePrintAreas:=False, _
    OpenAfterPublish:=True

    Sheets("Assurances").Select
End Sub

I've run it on my personal Mac, with Excel 2019 and it seems to be working, I've also run it on windows 7 with Excel 2019, also working.

But I tried running it on Mac and Windows 10, both running Excel 2016, and it didn't work on either one of them: On Mac, it opens a print window, waiting for me to select a printer.

On Windows, it gives me the following error:

"Run-time error '1004': Document not saved. The Document may be open, or an error may have been encountered when saving."

The error point to the 4 lines of the "ExportAsFixedFormat".

What could have caused the problem?

Create excel file without library

$
0
0

I using this code:

header( "Content-Type: application/vnd.ms-excel" );
header("Content-Disposition: attachment; filename=liste.xls");

echo "\xEF\xBB\xBF";

and I writing my SQL datas in a while loop like this:

echo "\n<table><tr><td>".$first[$post_a]."</td>\t<td>".$second[$post_a]."</td>\t<td>".$third[$post_a]."</td>\t</td></tr></table>";

When I try to open this created file, excel saying version and type are unmating even so I can open file after this warning on desktop but when I try to open on my phone file can't opening after warning.

Excel VBA filter and Delete data

$
0
0

In a Excel sheet i have data from column A1 to G12. In that C column i have employee ID. From this i need to filter certain employee ID and Delete only those particular rows. Example: I need to filter 51168, 79783, 70682 these 3 employee ID and delete. I have try to recorded a macro. If the particular employee ID is not in the place means its deleting some other row. Could anyone help me on this. This is the code i recorded,

ActiveSheet.Range("$A$1:$I$12").AutoFilter Field:=3, Criteria1:=Array( _
"51168", "70682", "79783"), Operator:=xlFilterValuesRows("2:2").Select
Range("C2").Activate
Range(Selection, Selection.End(xlDown)).Select
Selection.Delete Shift:=xlUp
Range("C1").Select
ActiveSheet.Range("$A$1:$I$9").AutoFilter Field:=3

Using VBA to open and run a userform

$
0
0

I have a userform on an excel file called "userform":

Private Sub add1_Change()

End Sub

Private Sub add2_Change()


End Sub

Private Sub Calc_Click()


Result.Value = Val(add1.Value) + Val(add2.Value)



End Sub

This userform takes the value from the user and adds them together and shows the result in a textbox.

I want to create a new macro in another workbook named "input". The macro in this workbook should open the userform workbook, enter values in the textbox add1 and add2, then run the userform calculate button.

What I've tried thus far:

  • Set add1.value to extract a value from say, cell A1, and similarly for add2.value. Then I created a macro on the input workbook to change the values in cells A1 and A2. The problem from here is I don't know how to force excel to open the userform and click calculate.

Ideally, I would really prefer to not go through what I've done. I'd like to set a macro which opens the userform, enters the data and hits calculate then closes the userform - Rather than editing the userform itself

Any ideas on how to get thorugh this issue it'd be really appreciated.

Combining Column Values in an Excel Pivot Table

$
0
0

In order to simplify a stacked bar chart, I am looking to sum up the counts of multiple columns I have in my pivot table. For example, in this sample table, I would like to combine Fruits and Vegetables into one column, so that each bar will comprised of three colors: one for Meats, one for Grains, and one for Fruits+Vegetables.

Pivot Table and Stacked Chart

For reference, this is the data source:

Data Source table

I tried adding a Calculated Field, but I'm not sure if I can use specific values from a column in the Formulas field. Is there a way to create something like this from a pivot table, or should I be taking a different approach to this all together?

Viewing all 88796 articles
Browse latest View live


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