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

ASP.net Gridview Export to Excel .xlsx not working

$
0
0

Export to excel in .xls is working but export to .xlsx is not working after change content type- My code is below:

private void ExportToExcel()
{
    try
    {
        Response.Clear();
        Response.Buffer = true;

        //Response.AddHeader("content-disposition", "attachment;filename=LoanDataDeletion.xls");
        //Response.Charset = "";
       // Response.ContentType = "application/vnd.ms-excel";

        Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        Response.Charset = "";
        Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}", "LoanDataDeletion.xlsx"));

        StringWriter sw = new StringWriter();
        HtmlTextWriter hw = new HtmlTextWriter(sw);

        grdView.AllowPaging = false;
        grdView.DataBind();

        //Change the Header Row back to white color
        grdView.HeaderRow.Style.Add("background-color", "#FFFFFF");

        //Apply style to Individual Cells
        for (int i = 0; i < grdView.Columns.Count; i++)
        {
            grdView.HeaderRow.Cells[i].Style.Add("background-color", "green");
        }
        for (int i = 0; i < grdView.Rows.Count; i++)
        {
            GridViewRow row = grdView.Rows[i];

            //Change Color back to white
            row.BackColor = System.Drawing.Color.White;

            //Apply text style to each Row
            row.Attributes.Add("class", "textmode");

            //Apply style to Individual Cells of Alternating Row
            if (i % 2 != 0)
            {
                row.Cells[0].Style.Add("background-color", "#C2D69B");
                row.Cells[1].Style.Add("background-color", "#C2D69B");
                row.Cells[2].Style.Add("background-color", "#C2D69B");
                row.Cells[3].Style.Add("background-color", "#C2D69B");
            }
        }
        grdView.RenderControl(hw);

        //style to format numbers to string
        string style = @"<style> .textmode { mso-number-format:\@; } </style>";
        Response.Write(style);
        Response.Output.Write(sw.ToString());
        Response.Flush();
        Response.End();
    }
    catch (Exception)
    {
        throw;
    }
}

Not able to fix Formatting im attendabce sheet

$
0
0

I was preparing a template file for Attendance sysytem.In which I need to fetch data from The report which I download from Biometric Attendance machine.Report which I download from Attendance machine values of cells are in 'Time Text Format'.So now when I Copy data from Attendance report (i.e from machine) format in my template also gets coverted and formula which I have applied shows error.So please help me with this.

Code to search column A:A, copy values in same row F:F and paste to same row O:O for the first A:A instance then same row Q:Q for second F:F value

$
0
0

I am looking to have a VBA code that will look down A:A in a sorted and organized data table from A2 to A100 for example.

  • For the first A2 value copy the value in F2 and paste it to O2.
  • If A3 is the same as A2 the value from F3 would be copied and pasted to Q3.
  • If A4 is the same value as A3 The value from F4 would be copied and pasted to S4
  • else if the value in A5, for example, is not the same as A4, Then the whole process starts over at A5.

Below is a link to a workbook with the page layout. https://drive.google.com/open?id=1R80JN0ceoO5UikT2qPAyz4F6X86mISjz TIA for any help you can provide.

Excel crashes when i set com object to call python script

$
0
0

I am running windows10 on an azure vm with Office365 Pro Plus. I am trying to set up a COM object to call a python script a la this:

http://exceldevelopmentplatform.blogspot.com/2018/01/calling-python-class-using-vba-with-com.html

I was able to get the clsid with pip install pywin32 -> [python shell] import pythoncom -> print(pythoncom.CreateGuid()) and so my python script is very simple.

Just trying to test if it works:

class PythonClass1(object):
    _reg_clsid_= "{<Guid from script above here>}"
    _reg_progid_= 'PythonLib1.PythonClass1'
    _public_methods_ = ['Greeting']

    def Greeting(self):
        print("this work?")
        return "Hello World"

if __name__=='__main__':
    print("Registering COM server...")
    import win32com.server.register
    win32com.server.register.UseCommandLine(PythonClass1)

I am trying to call this from vba in excel like so:

Sub TestingButton_Click()
    Dim objPython As Object
    Set objPython = CreateObject("PythonLib1.PythonClass1")
    Debug.Print objPython.Greeting()
End Sub

When I run this module, i get a loading spinner on my cursor for about 5 seconds then excel just crashes and restarts excel with a version recovery bar on the left side just like when excel crashes normally.

I'm absolutely at a loss for why this would happen. I've tried debug.print-ing all over in vba and also in the python script. Nothing in the win32traceutil.py, no errors... just crashes and restarts.

Does anybody have any ideas as to what's going on? Any help would be greatly appreciated, thank you in advance.

Transfer Specific Columns from .txt to Excel

$
0
0

I am trying to transfer the data in this .txt file into a spreadsheet.

enter image description here

After I run the VBA I have, all the data will get transferred, so, Column A through Column E will get filled.

enter image description here

But I only need the data in the first 3 columns (A-C). I do not want to transfer any data after the Column C. I cannot use Range.Clear method because in my real project, Columns after the Column C contain data that cannot be erased/rewrite.

Sub Fill()

With ActiveSheet.QueryTables.Add(Connection:= _
        "TEXT;C:\Users\xxxxxxx\Desktop\Input.txt", Destination:=Range("$A:$C") _
        )
        .Name = "Input"
        .FieldNames = True
        .RowNumbers = False
        .FillAdjacentFormulas = False
        .PreserveFormatting = True
        .RefreshOnFileOpen = False
        .RefreshStyle = xlInsertDeleteCells
        .SavePassword = False
        .SaveData = True
        .AdjustColumnWidth = True
        .RefreshPeriod = 0
        .TextFilePromptOnRefresh = False
        .TextFilePlatform = 437
        .TextFileStartRow = 1
        .TextFileParseType = xlDelimited
        .TextFileTextQualifier = xlTextQualifierDoubleQuote
        .TextFileConsecutiveDelimiter = False
        .TextFileTabDelimiter = True
        .TextFileSemicolonDelimiter = False
        .TextFileCommaDelimiter = True
        .TextFileSpaceDelimiter = False
        .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1)
        .TextFileTrailingMinusNumbers = True
        .Refresh BackgroundQuery:=False
    End With
End Sub

This is my code, is there a way to only transfer part (first nth columns) of the data from my text file without creating an extra helper/reference sheet? Any help would be appreciated!

Type mismatch error on importing values to an array

$
0
0

I m initializing an array and import values from a specific range. if the range are greater than one line the code works fine BUT in case the range is just one line i m getting an error of:

Run time error 13: Type mismatch

Code:

Sub test()

    Dim arr As Variant
    Dim i As Long, LastRow As Long

    With ThisWorkbook.Worksheets("Sheet1")

        LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row

        arr = .Range("A1:A"& LastRow)

        For i = LBound(arr) To UBound(arr)

        Next i

    End With

End Sub

Any help will appreciated.

After @JvdV answer i manage to overcome this problem but i face other one:

when there is more than one lines the array looks like that:

enter image description here

But when there is only one line:

enter image description here

How to create the same array structure - dimensions?

Need to group Time Slots in Excel

$
0
0

I am working on logistics data. I have booking being made throughout the day at regular intervals from start to the end of the day. Now these booking are consistent and I have time from like

04:45
21:10
21:10
06:07
05:44
05:45
05:45
05:45
etc. 

Now as there are multiple bookings I need to group them such as 04:00- 05:00 (1 hours)- this should capture all booking made during this period. Similar for other hours during the day. By doing this I will be able to group individual values into specific group. Can you please advice how to achieve the same in excel.

Prevent a command button from being clicked multiple times while a sub is iterating

$
0
0

I'm creating an Excel macro that will run when a command button is pressed (VBA 7.1), and will not allow the user to click multiple times during execution, however every trick I've found online to this end has not worked: even while locked, disabled, and with focus on a different object, the user can still cause the sub to run multiple times before the first one finishes.

My current code looks like this (run_slow_macro opens a Word document to make changes, then saves it, and can take about 30 seconds to complete.)

Private Sub CommandButton1_Click()

    If CommandButton1.Enabled = False Then
        MsgBox ("STOP CLICKING")
    End If

    Me.Frame1.SetFocus
    CommandButton1.Enabled = False
    CommandButton1.Locked = True
    CommandButton1.Caption = "WAIT"

    Call run_slow_macro

    CommandButton1.Caption = "CommandButton1"
    CommandButton1.Enabled = True
    CommandButton1.Locked = False


End Sub

When I click the button, it locks and becomes disabled, and the caption changes as expected. However, subsequent clicks do not cause the "STOP CLICKING" messagebox to appear, yet still cause the Word document to be opened multiple times, edited, and then closed.

The command button does not become unlocked/enabled until after all executions are completed, and the "STOP CLICKING" messagebox never appears.

I'm very confused as to how it's executing "Call run_slow_macro" each time, but seems to be skipping everything before and after that line once the first execution is in progress.

I have very little experience with VBA, and have been unable to find any solutions online (the above code is the culmination of the most common recommendation's I've seen), so I appreciate any advice that can be offered.


How to loop through non-zero values in a nested for loop

$
0
0

This is the code i am using. I want to loop through range AB:AF, which contains numbers from 0 to 5 and ignore the values that are 0.

So for example range AB34:AF34 contains 0, 1 and 5, i will only want to iterate 1 and 5.

Sub permutations()

Dim rng As Range, cell As Range
Dim rng1 As Range, cell2 As Range
Dim rng2 As Range, cell3 As Range
Dim rng3 As Range, cell4 As Range

Set rng = ActiveSheet.Range("AB34:AF34").SpecialCells _
 (xlCellTypeFormulas, xlNumbers)
Set rng1 = ActiveSheet.Range("AB35:AF35").SpecialCells _
 (xlCellTypeFormulas, xlNumbers)
Set rng2 = ActiveSheet.Range("AB36:AF36").SpecialCells _
 (xlCellTypeFormulas, xlNumbers)
Set rng3 = ActiveSheet.Range("AB37:AF37").SpecialCells _
 (xlCellTypeFormulas, xlNumbers)

Dim e As Integer
Dim f As Integer
Dim g As Integer
Dim h As Integer
Dim i As Integer
Dim j As Integer

For h = 1 To 5
    For g = 1 To 5
        For f = 1 To 5
            For e = 1 To 5
                For Each cell4 In rng3
                    For Each cell3 In rng2
                        For Each cell2 In rng1
                            For Each cell In rng
                                Cells(34, 9).Value = cell
                                Cells(35, 9).Value = cell2
                                Cells(36, 9).Value = cell3
                                Cells(37, 9).Value = cell4
                                Cells(38, 9).Value = e
                                Cells(39, 9).Value = f
                                Cells(40, 9).Value = g
                                Cells(41, 9).Value = h
                            Next cell
                        Next cell2
                    Next cell3
                Next cell4
            Next e
        Next f
    Next g
Next h

End Sub

Macro stops looping if I call a macro to send an email

$
0
0

I have a workbook named Run All Weekly Reports.xlsm where I list reports that I update each Monday. The workbook/report names to be updated are in column A, the workbook paths in column B and the macro names in column C.

The macro (that I found somewhere online) works perfectly, looping through all of the files and refreshing the data, but I have recently added some files that refresh the data and then call another macro (within the other workbook) to email the workbooks to my colleagues. Once it sends the email, this macro stops and will not continue looping through the rest of the other workbooks. I think it has something to do with Setting the object back to Excel. I have Google searched and tried Set xlApp = CreateObject("Excel.Application"), but it will not continue the loop.

Any help would be greatly appreciated. Here is my macro:

Sub Run()
    'PURPOSE: To loop through all Excel files listed in Worksheet and run macro listed in column C

    Dim wb As Workbook
    Dim myPath As String

    Dim fn As String
    Dim MacroName As String
    Dim x As Integer

    NumRows = Range("A1", Range("A1").End(xlDown)).Rows.Count
    For x = 1 To NumRows

        Workbooks("Run All Weekly Reports.xlsm").Sheets("List").Activate
        ActiveCell.Offset(1, 0).Select

        fn = ActiveCell.Offset(0, 0).Value
        myPath = ActiveCell.Offset(0, 1).Value
        MacroName = ActiveCell.Offset(0, 2).Value
        ActiveCell.Offset(0, 3) = "Done"

        If myPath = "" Then GoTo ResetSettings
        Set wb = Workbooks.Open(Filename:=myPath & fn)
        Application.Run "'"& fn & "'!"& MacroName

        wb.Close SaveChanges:=True
        Workbooks("RUN ALL WEEKLY REPORTS.xlsm").Save

        'Ensure Workbook has closed before moving on to next line of code
        DoEvents

ResetSettings:
        'Reset Macro Optimization Settings
        Application.EnableEvents = True
        Application.Calculation = xlCalculationAutomatic
        Application.ScreenUpdating = True
    Next
    MsgBox ("Finished")
End Sub

My macro experience is limited to a bit of trial and error, so please excuse my crude descriptions.

The macro in my original message is one that I copied from somewhere online and just modified it a little to suit.

I copied it into my macro enabled workbook and so to launch it, I have to select the macro called 'Run' from my macro list and 'Run' it.

I think that means that it is a public sub?
I have a list of workbooks in a file eg. Backorder Reports that it opens and Refreshes the data from an ODBC query, then calls the email to send to my colleague, but after the Sub SEND_Mail_Outlook_With_Signature_Html(), the loop macro just stops.

If I don't call the SEND macro, it loops through to the next file listed in my workbook without a problem.
I hope that I am making sense.

Below is and example of the macro's that are in each of my sheets that it should open and execute.

Sub Refresh()

    ' Refreshes the data and the dates in the pivot tables

    ActiveWorkbook.RefreshAll
    Application.CalculateUntilAsyncQueriesDone
    ActiveWorkbook.Save
    Call SEND_Mail_Outlook_With_Signature_Html
    ActiveWorkbook.Close

End Sub

Sub SEND_Mail_Outlook_With_Signature_Html()
    Dim OutApp As Object
    Dim OutMail As Object
    Dim StrBody As String

    Set OutApp = CreateObject("Outlook.Application")
    Set OutMail = OutApp.CreateItem(0)

    StrBody = "Today's report attached."

    On Error Resume Next

    With OutMail
        .Display
        .To = "mycolleague@live.com.au"
        .CC =
        .BCC =
        .Subject = "Backorder Report"
        .HTMLBody = StrBody & "<br>"& .HTMLBody
        .Attachments.Add ActiveWorkbook.FullName
        .Send
    End With

    On Error GoTo 0
    Set OutMail = Nothing
    Set OutApp = Nothing
End Sub

Move cells to row with criteria

$
0
0

enter image description hereHow can I move cells from the row where the first value is same as in the second or third to the same row. get first picture from the second.

enter image description here

Find a text range in column and write search result to other column in excel

Comparing shape object retrieved from Selection and the same shape retrieved from ActiveSheet.Shapes set

$
0
0

I'm trying to check if the Shape selected by user is the proper one. For the simplicity, let's say we have only one shape in otherwise empty worksheet. Because of that, we know that the selected shape must be the right one:

Sub AreShapesTheSame()

    Dim ws As Worksheet
    Set ws = ActiveSheet

    Dim shape As Object
    Dim selShape As Object

    Set shape = ws.Shapes.Item(1).DrawingObject
    Set selShape = Selection

    MsgBox shape Is selShape

End Sub

I can see in the Locals window, that the objects shape and selShape have the same attributes. Also if I change the name of one of them (shape.name = "xxx"), the name of the other object also changes. So I presume, that they are the same objects, or at least referencing the same object.

If that is the case, why is the statement (shape Is selShape) returning False? How can I check if the user Selection is referencing some specific Object?

Looping from the limit of contents in a sheet to match and copy in VBA Excel

$
0
0

I'm new here, and this is my problem; in vba, excel 2010 I want to search for a specific word or a list of words in every row with content in one sheet and if it matched then it copy the entire row of that sheet and paste it in a new one at the first row, and then continues looping back and foward from sheet to sheet after the list of words ends. At the end you get a new sheet with a bunch of rows collected from your search Query. I got some initial code, dont know if you guys will like to see it. Thanks.

Sub Macro1()
    Dim sheetName As String
    Dim recintos As String
    Dim recintosArray() As String
    Dim namevar As Variant
    Dim sheetLimit As Integer
    Dim n As Integer

    'Words to search and copy in the sheet 
    'Nombre del sheet a buscar en el documento abierto
    sheetName = InputBox("Nombre de la hoja o sheet en donde desea copiar los recintos :")

    'Save a string type data 
    'Guarda los datos como tipo cadena
    recintos = InputBox("Introduzca los nombres  de los recintos separados por coma :", "Buscador de recintos", "00000,00000,00000...")

    'Split the words and save it in array type 
    'Separa la cadena y los guarda en un arreglo
    recintosArray() = Split(recintos, ",")
    namevar = InputBox("Introduzca el nombre de la hoja que desea crear para pegar c/u :")

    'Makes a new sheet and defines a name
    'Crea un sheet nuevo y define el nombre
    Sheets.Add After:=Sheets(Sheets.Count)
    Sheets(Sheets.Count).Name = namevar
    sheetLimit = Sheets(sheetName).Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row

    'Array index
    'Indice del arreglo recintosArray
    n = 0

    For i = 1 To sheetLimit
        Sheets(sheetName).Activate
        currentCellName = Sheets(sheetName).Cells(i, 1).Value

        If n <= UBound(recintosArray) Then
            If Replace(currentCellName, Chr(32), "") = recintosArray(n) Then
                Sheets(sheetName).Rows(i).Copy
                newSheetLimit = Sheets(namevar).Cells(Rows.Count, 1).End(xlUp).Offset(0, 0).Row
                Sheets(namevar).Activate
                Sheets(namevar).Cells(newSheetLimit + 1, 1).Select
                ActiveSheet.Paste
                n = n + 1
                i = 1
            End If
        End If
    Next i
End Sub

Pseudoinverse computation using VBA and C++ DLL

$
0
0

I want to pseudoinverse a big degenerate matrix using VBA in Excel (analog of wide-known "pinv" function). As I understand excel tools can't deal with degenerate matrices.

I found nothing better than try to implement a C++ DLL library and link to VBA. I faced following problems:

My configuration is: Windows 10 x64, Office 16 x64. I create DLL with VS 2015 as x64 DLL. I have managed to create and link simple DLL and even pass to and get from Double Arrays. But when it came to use math libraries such as Armadillo with dynamically linked BLAS, a mess arose.

Any working and debugged code which uses BLAS x64 DLL in case being wrapped as DLL and invoked from VBA crashes Excel. I already checked dependencies and put BLAS/LAPACK dlls into almost every suitable folder. It crashes even I don't use any passed parameters. Proc monitor shows that dependencies are ok. It looks like when Excel calling some function from the DLL prevents external calls from that DLL.


How do I combine a regular expression function in vlookup?

$
0
0

I have a VBA regular expression which I would like to combine with VLOOKUP however it does not return the value based on the regular expression if used with VLOOKUP.

This is what it returns when I execution the function =udfRegEx(A2,B2)

String

Microsoft Windows Server 2003, Standard Edition (64-bit)

Regular expression

^([^,]*)

Result

Microsoft Windows Server 2003

However when I execute =IFERROR(VLOOKUP(udfRegEx(A2,RegularExpression!B2),[Sample.xls]Sheet1!$B$2:$E$4177,4,FALSE),0) it still returns Microsoft Windows Server 2003, Standard Edition (64-bit)

Column B2 is the regular expression ^([^,]*)

Putting loop inside a Select Case generates error

$
0
0

I have put a do/while statement inside a SELECT CASE/END SELECT and it generates the error

Case without Select Case.

Select Case myVariable
    Case 0
        Do
        While ...
    Case 1
    ...
End Select

How to fetch match details and display in TextBox | Excel VBA | Application |

$
0
0

I have a scenario

where I want to display data in a textbox..if keyword matches from entered sheet name

Below is the Application how it look

My application GUI

enter image description here

As per above image i am taking two input in textbox

enter sheet name [where i will enter sheet name] as "A1"

enter SC name [where i enter keyword need to match] as "AB4"

Below is the sheet **A1 details **

enter image description here As i enter Sheet name = A1 and SC name = AB4

The match is found and should display details on Display button click

4   AB4 3456    DEMO4   D4  Good 

Ouptut:

enter image description here

Insert a Row in Excel Using Java Apache POI

$
0
0

I am developing a desktop application related to Excel sheets. I have some problems inserting rows between two rows. Is there any possibility to do this in Java using Apache POI?

Workbook wb3=WorkbookFactory.create(new FileInputStream("Book1.xls"));
Sheet sh=wb3.getSheet("sheet1");

//Reading the available rows using (sh.getRow(1))

//Here i need to insert second row (????)

//I have third row here which already exists (sh.getRow(3))

How to use two value in the last row of a table to add rows to another table with Excel vba

$
0
0

I am new to vba and having a little trouble figuring this out. Don't really know where to start

I have two tables. I'm simply just trying to find code to say that if the last row in table 1 of worksheet 1 has any value in the 2nd column and the value in the last column is greater than 1 then take the value in the last column of the last row and add that many rows to table 2 of worksheet 2.

I tried searching other posts for this same type of topic but couldn't find any. Any help would be greatly appreciated.

Viewing all 88541 articles
Browse latest View live


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