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

How to have python wait until an Excel Macro/Refresh is done

$
0
0

I am using Python to run a macro in excel. and I want Python to close excel. The macro refreshes a data connection in excel which can be slow.

How do I have python wait until the refresh is done to close. This is what I am using, I need something before the xl.Quit that will wait until the refresh in macro is done????

 import win32com.client
 import os

 xl = win32com.client.DispatchEx("Excel.Application")
 wb = xl.workbooks.open("X:\Backoffice\Options Trading\BloombergRate.xlsm")
 xl.Visible = True
 xl.run("Refresh")
 xl.Quit()

Wait ways can I make this work?


Showing the full Microsoft Excel Version and Build number with VBA

$
0
0

I am desperately trying to find some VBA code to give me the current Office 365 version and build number, which I will be using further down the line.

I have written the following:

Sub GetVersion()
MsgBox "The current version is "& Application.Version & Application.Build, _
vbOKOnly, "Version"
End Sub

But this only returns:

Version 16.012325

What I am looking for is a way to retrieve the version and full build number (The version number and build number displayed in the File, Account section:

Version 1912 Build 12325.20288

Appreciate the help!

SQL Query to to acces Excel data - Java

$
0
0

I am trying to read from excel using Fillo-1.18. Below is my code:

public static void main(String[] args) {
        Fillo fillo=new Fillo();
        Connection connection;
        try {
            connection = fillo.getConnection("C:\\Users\\Dish\\Desktop\\1.xlsx");

            String strQuery="Select sum(Amount) as amnt, Run_ID from Sheet1 group by Run_ID";
            Recordset recordset=connection.executeQuery(strQuery);

            while(recordset.next()){
                System.out.println(recordset.getField("amnt"));
            }

            recordset.close();
            connection.close();
        } catch (FilloException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

It works fine for normal select clause. But when I am trying to use aggregate functions like SUM(), I am not able to access that field. Inside while I am get the following error:

com.codoid.products.exception.FilloException: amnt field is not found
    at com.codoid.products.fillo.Recordset.getField(Recordset.java:163)
    at ReadExcelSheetData.main(ReadExcelSheetData.java:18)

How can I resolve this?

Invalid State when try to generate a barcode

$
0
0

I am try to make a barcode from a string, what is come from an excel cell. This cell contains special charakcters like"#&'!/()". When I try to make an image from the data, I get the next error:

Unhandled Exception System.InvalidOperationException: 'Invalid state.'

If i give the same string by hand like "string xy= "#&!"; ", the barcode will be created.

private void OpenFile()
    {
        Excel excel = new Excel("MyExcel.xlsx", 4);
        excel.WriteToCell(7,2,textBox1.Text);
        Char[] data= excel.readCell(2, 13).ToCharArray();
        excel.Save();
        excel.Close();
        Code128BarcodeDraw bdraw = BarcodeDrawFactory.Code128WithChecksum;
        string data2 = new string(data);
        pictureBox2.Image = bdraw.Draw(data2, 50,2);
    }

How to verify 2 variables are Integer type?

$
0
0

I would like to let user enter two integers (two text boxes) While this condition is not satisfied, i want to let user fill again the text boxes.

Here is what I've tried but it's not the right answer:

Sub verif_type(n1, n2)


    If TypeName(n1) = "Integer" And TypeName(n2) = "Integer" Then
        MsgBox ("C'est bon !")

    Else
        MsgBox ("C'est pas bon, recommencez !")
        Unload UserForm1
        Call verif_type(n1, n2)
    End If

End Sub

Thanks in advance.

chart series names are not shown until select data in right click menu is clicked and another series is selected

$
0
0

I've created a chart in excel which needs to refresh when there is a change in pivot slicer selection. Because a dynamic trend line (based on user defined trend values)has to be added, haven't created a pivot chart but selecting chart data from a range that gets updated when pivot slicer selection changes. Chart refresh based pivot slicer selection is done through VBA. It works fine without the trend line. But when trend line is selected and pivot slicer selection is changed, randomly I get 1004 error when the trend line is referred to by it's name i.e. ".SeriesCollection(name of the trend line)". While inspecting I found that the chart series names are somehow not updating (below screenshot).

enter image description here

Select Data Source Window

enter image description here

When I click on any other series the chart refreshes immediately and the series names appear (below screenshot)

enter image description here

I've tried using chart.refresh, chart.activate but none works. Alternatively, if I save the excel, close and open it I can see the charts normally but that's not a solution for me.

Kindly somebody help me overcome this issue.

Excel formula named range changes - Jan 2020 update

$
0
0

UPDATE TO THE BELOW

The update has now rolled out to lots of machines, and broken maybe 90% of the work we have done in the past. Just to clarify exactly what I mean:

Using VBA (or C# or anything else for that matter) - we dynamically insert formulas at runtime using named ranges. For example:

=(MIN(Bid_S1,Bid_S2, Bid_S3, Bid_S4, Bid_S5)/Bid_S3)*PriceWeighting

This now longer works and gives a SPILL error. When I try to put the @ in front as suggested, I see a message telling me @ is not supported for some versions of Excel, do I still want to use it.

Option 1 - yes, I put @'s in front of every named range, spill error. Option 2 - the formula they suggest is identical to the one I already had. Same Spill error.

This is going to be a huge problem for a lot of companies, surely.

Hard not to agree with this question:

https://answers.microsoft.com/en-us/msoffice/forum/all/the-new-dynamic-arrays-spill-functionality-should/92f9847f-deca-4ec9-ada3-9e005a5b68da?rtAction=1579696000111&page=1


A very bizarre situation. 4 different computers. Each running identical versions of Excel, Windows.

A simple named range with 4 cells say, called PlanID

PlanID
1
2
3
4

Type "=PlanID" next to the first, on 3 of the machines it returns 1, as I would expect. On the 4th machine it returns the formula array of the whole range. Just spent about 2 hours researching Spill errors etc but nothing seems to directly relate to the 2 issues I have:

  1. How can something that has worked reliably for years suddenly not work
  2. Why only on one machine?

Literally identical versions of Excel (16.0.12325.20280 32 bit)

How to convert a given ordinal number (from Excel) to a date

$
0
0

I have a Value 38142 I need to convert it into date format using python. if use this number in excel and do a right click and format cell at that time the value will be converted to 04/06/2004 and I need the same result using python. How can I achieve this


Split the value on a cell and update the new column with the split value row-wise using Python

$
0
0

I am trying to split the value on a cell and update the new column with the split value row-wise using python. Input and output given below:

Original Excel Sheet

Original Excel Sheet

New Excel Sheet to get

New Excel Sheet to get

Reference another cell outside workbook

$
0
0

I have a list of 150 filenames from the same directory in column A in an Excel workbook using

=REPLACE(CELL("filename"),FIND("[",CELL("filename")),LEN(CELL("filename")),"*")

at the top of the workbook and using formula

=IFERROR(INDEX(FileNameList,ROW()-2),"") 

to list each filename in the directory.

I want to reference D4 in each of these files and put the value of this next to the filename in column B of this external workbook.

What is the best way of retrieving these?

Need help getting the output of a for loop into Excel/CSV using OS.WALK

$
0
0

Need help with getting the printed output to a CSV/Excel file.

Thanks for your help!

import pandas as pd
import os


for root, dirs, files in os.walk("C:/"):
    for file in files:
        if file.endswith(".xlsx"):
             print(os.path.join(root, file))

#Need to print the results of this search into an excel/csv File.

How to read Excel files in powershell?

$
0
0

I would like to parse the following Excel file which perfectly open in the application.

I browsed the Internet and lots of guys said that those two command lines do open Excel files (example Read Excel sheet in Powershell).

$excel = New-Object -com excel.application
$wb = $excel.workbooks.open("c:\users\administrator\my_test.xls")

But I have got the following exception:

Exception calling "Open" with "1" argument(s): "Old format or invalid type library. (Exception from HRESULT: 0x80028018 (TYPE_E_INVDATAREAD))"

How to outputs the value of each cell read-only, if possible keeping the rows ?

How to pull information from QuickSearchResults Pop-up window in internet explorer

$
0
0

I'm writing a macros for downloading Bill Of Material from Internet Explorer by login, I can accesses only the primary window for searching and finding my content and i'm facing difficulty to accesses or alter secondary windows popping-up during my data collection process.

enter image description here

Excel index ,if and And

$
0
0

I have two sheets in excel. Sheet1 has A, B, C and D columns. Sheet2: A, B, E as columns. I want compare Sheet1 and Sheet2 columns (A&B) and write C from Sheet1 only if A&B in both sheets matches.

Eg:

Sheet1

A B C D

Sheet2

A B E

Add column C in Sheet2 only if A&B columns in both sheets matches

Is there any way to set the style of the Excel file via Apache POI in Scala/Spark application?

$
0
0

I my Scala application I use a Spark plugin (spark-excel) for creating and writing Excel files with several new sheets via Apache POI.

import spark.implicits._

val df = Seq(
  ("2019-01-01 00:00:00", "7056589658"),
  ("2019-02-02 00:00:00", "7778965896")
).toDF("DATE_TIME", "PHONE_NUMBER")

df.show()

df.coalesce(1).write
  .format("com.crealytics.spark.excel")
  .option("dataAddress", "'Sheet'!!A1:Z1000000")
  .option("useHeader", "true")
  .option("dateFormat", "yy-mmm-d")
  .option("timestampFormat", "mm-dd-yyyy hh:mm:ss")
  .mode("append")
  .save("/path/filename.xlsx")

Question: Is there any way to change the style of the Excel file? For example I want to change the color of the header, also change the width of columns. What would you advise?


s3 path printed incorrectly by spark excel reader

$
0
0

I am trying to read an excel sheet from Amazon S3 and here is the code snippet. But it fails saying file doesn't exist though its there , I checked there is a slash (/) missing from the path.

println(path)
val data = sqlContext.read.
    format("com.crealytics.spark.excel").
    option("location", s3path).
    option("useHeader", "true").
    option("treatEmptyValuesAsNulls", "true").
    option("inferSchema","true").
    option("addColorColumns", "true").
    load(path)

path is correctly printed as : s3a://AKIAJDDDDDDACNA:A6voquDDDDDqNOUsONDy@my-test/test.xlsx

But why the slash is missing when read by spark? Here is the error message :

 Name: java.io.FileNotFoundException
    Message: s3a:/AKIAJYDDDDDDNA:A6DDDDDDDDDwqxkRqUQyXqqNOUsONDy@my-test/test.xlsx (No such file or directory)
    StackTrace:   at java.io.FileInputStream.open0(Native Method)
      at java.io.FileInputStream.open(FileInputStream.java:212)
      at java.io.FileInputStream.<init>(FileInputStream.java:152)
      at java.io.FileInputStream.<init>(FileInputStream.java:104)
      at com.crealytics.spark.excel.ExcelRelation.<init>(ExcelRelation.scala:28)
      at com.crealytics.spark.excel.DefaultSource.createRelation(DefaultSource.scala:31)
      at com.crealytics.spark.excel.DefaultSource.createRelation(DefaultSource.scala:7)
      at org.apache.spark.sql.execution.datasources.DataSource.resolveRelation(DataSource.scala:345)
      at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:149)
      at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:122)
      at $anonfun$1.apply(<console>:46)
      at $anonfun$1.apply(<console>:46)
      at time(<console>:36)

How to read multiple excel sheets using spark sql in java

$
0
0

I am using maven project to read excel file in spark sql that contains 2 sheets.

Sheet1 and Sheet2

When I try below code, it runs without error but sheet option doesn't work. It always read Sheet1 regardless sheetName option. Could anyone point me what I am missing?

Dependencies

<dependencies>
    <!-- https://mvnrepository.com/artifact/org.apache.spark/spark-core -->
    <dependency>
        <groupId>org.apache.spark</groupId>
        <artifactId>spark-core_2.11</artifactId>
        <version>2.4.2</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.spark/spark-sql -->
    <dependency>
        <groupId>org.apache.spark</groupId>
        <artifactId>spark-sql_2.11</artifactId>
        <version>2.4.2</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/com.crealytics/spark-excel -->
    <dependency>
        <groupId>com.crealytics</groupId>
        <artifactId>spark-excel_2.11</artifactId>
        <version>0.11.1</version>
    </dependency>
</dependencies>

Code

import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.apache.spark.sql.Dataset;
import org.apache.spark.sql.Row;
import org.apache.spark.sql.SparkSession;

public class ReadExcelSheets {

  public static void main(String[] args) {

    Logger.getLogger("org").setLevel(Level.ERROR);

    SparkSession spark = SparkSession
            .builder()
            .appName("Java Spark SQL Example")
            .config("spark.master", "local")
            .getOrCreate();


    Dataset<Row> df = spark.read()
            .format("com.crealytics.spark.excel")
            .option("useHeader", "true")
            .option("sheetName", "Sheet2")
            .load("datasets/test1.xlsx");

    df.show();
  }
}

Create PDF for each pivot filter

$
0
0

I currently have a pivot table which created a statement of outstanding invoices, which is filtered by account name. I would like to create a macro where excel makes a PDF statement for each account.

I have no knowledge of VBA so I got the code below by searching google and edited it for my pivot table.

However when I try to run it excel does not like this line “.CurrentPage = pi.Name”. When I take this out it does run and created several PDFs with the correct account name, but all the statements are the same just.

Is anyone able to help?

Option Explicit
Sub test()
Dim strPath As String
Dim wksSource As Worksheet
Dim PT As PivotTable
Dim pf As PivotField
Dim pi As PivotItem

Set wksSource = Worksheets("AP Pivot")

Set PT = wksSource.PivotTables("PivotTable1")

Set pf = PT.PivotFields("ACCOUNT")

If pf.Orientation <> xlPageField Then
MsgBox "There's no 'ACCOUNT' field in the Report Filter. Try again!", vbExclamation
Exit Sub
End If

strPath = "T:\"

If Right(strPath, 1) <> "\" Then strPath = strPath & "\"

ActiveWorkbook.ShowPivotTableFieldList = False

PT.PivotCache.Refresh

With pf
.ClearAllFilters
For Each pi In .PivotItems
.CurrentPage = pi.Name
wksSource.ExportAsFixedFormat Type:=xlTypePDF, Filename:=strPath & pi.Name & ".pdf"
Next pi
.ClearAllFilters
End With
End Sub

Filter Column and enter Range as Input Box

$
0
0

Everybody,

I want to show only those columns in a table whose headers I enter in an input field.

I also want to use an InputBox to select the area to which the filter should be applied (e.g. row 4).

For this I would like to have only a part of the colums header to be sufficient to filter the columns.

FOR EXAMPLE:

If a column carries the heading: eQuantum (02) then I would like to enter only a part of the heading, no matter in which length (e.g. eQuan), and then all columns should be shown which carry this partial heading. All other columns should be hidden.

The script is not running yet.

But here the code is as far as I got.

Sub Spalten_Filtern_Horizontal_InputBox()
Dim Zelle As Range
Dim Bereich As Range
Dim FilterText As String
Dim Einblenden As Range

Set Bereich = Application.InputBox(prompt:="Enter range", Type:=8)
  If Bereich Is Nothing Then
    MsgBox "Operation Cancelled"
  Else
    Bereich.Select
      End If
FilterText = InputBox("Bitte Spaltenwert eingeben")
For Each Zelle In Bereich
    If Zelle.Text Like FilterText Then
        If Einblenden Is Nothing Then
            Set Einblenden = Zelle
        Else
            Set Einblenden = Union(Einblenden, Zelle)
        End If
    End If
Next
Bereich.EntireColumn.Hidden = True
Einblenden.EntireColumn.Hidden = False
End Sub

Create & Save filtered lists into PDF

$
0
0

I've seen variations of this problem, but I'm pretty much brand new to VBA so I'm struggling to fit other examples to my specific use case. The Excel Workbook I'm using has 9 tabs, 3 of which are data dump only tabs that, when filtered, generate the results on the other 6 tabs. The filter criteria is the same on each of the 3 tabs, in this case I'm using names. The process is like this:

  1. Filter for a name (ie Swanson, Ron) on the 3 data dump tabs (name to be filtered is located in same column on each tab) Also, to note, the filter would remove all other rows.

  2. Highlight the other 6 tabs

  3. Save as a PDF with page numbers

  4. Repeat with the next name (ie Knope, Leslie)

This seems a bit tricky, especially because I'd like the PDF outputs to have page numbers. How can I have a macro that filters the same name on 3 tabs and saves down the filtered result as a PDF with page numbers? Any guidance is helpful. Thank you.

Viewing all 89424 articles
Browse latest View live


Latest Images

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