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

XML reading and writing to Excel using VB.Net

$
0
0

I am completely new with XML operations in VB. I am very much confused with child nodes, attributes, XElements. I tried few ways using XElements it is showing empty values, am not successful. Please help me in this. :(

I have this sample code in ".arxml" file.
I need to iterate the CLUSTER and get the SHORT-NAME (Note - In this there is only one cluster, but it might vary).

Under the one Cluster's "SCHEDULE-TABLES, there will be CON-SCHEDULE-TABLE. For each CON-SCHEDULE-TABLE I need SHORT-NAME, DELAY, TRIGGER values which are under table-entrys>application-entrys.

I need respective CON-SCHEDULE-TABLE values to be written in one row of Excel.

I need to write the details which is read from XML to Excel sheet as below which will contain the header as

Context

Sample Excel rows:

------------------------------------------------------------------------------------
TEST-ID | CLUSTER-SHORT-NAME | CON-SCHEDULE-TABLE-SHORT-NAME  | DELAY  |  TRIGGER 
------------------------------------------------------------------------------------
 1      |  LIN-1             |     DIAG1                      |  0.01  |  M_LIN
                                                              |  0.11  |  M_LIN_1

 2      |                    |     RUN_MAIN                   |  0.01  |  M_LIN_01

------------------------------------------------------------------------------------
<?XML version = '1.0’ encoding='UTF-8'?>
<AUTOSAR xmlns=http://autosar.org>
   <AR-PACKAGES>
     <AR-PACKAGE>
       <SHORT-NAME>System</SHORT-NAME>
      <AR-PACKAGES>
         <AR-PACKAGE>
            <CLUSTER>
                <SHORT-NAME>LIN-1</SHORT-NAME>
                <LIN-CLUSTER-VARIANTS>
                    <LIN-CLUSTER-CONDITIONAL> 
                       <BAUDRATE>19200</BAUDRATE>
                       <PHYSICAL-CHANNELS>
                          <LIN-PHYSICAL-CHANNEL>
                             <SHORT-NAME>M_LIN_9</SHORT-NAME>
                             <ADMIN-DATA/>
                             <FRAME-TRIGGERINGS>
                                <FRAME-TRIGGERING>
                                    <SHORT-NAME>M_LIN_01</SHORT-NAME>
                                    <IDENTIFIER>60</IDENTIFIER>
                                    <CHECKSUM>ENHANCED</CHECKSUM>
                                </FRAME-TRIGGERING>
                                <FRAME-TRIGGERING>
                                    <SHORT-NAME>M_LIN_01</SHORT-NAME>
                                    <IDENTIFIER>60</IDENTIFIER>
                                    <CHECKSUM>ENHANCED</CHECKSUM>
                                </FRAME-TRIGGERING>
                             </FRAME-TRIGGERINGS>
                             <SCHEDULE-TABLES>
                                <CON-SCHEDULE-TABLE>
                                    <SHORT-NAME>DIAG1</SHORT-NAME>
                                    <RESUME-POSITION>START-FROM-BEGINNING</RESUME-POSITION>
                                   <TABLE-ENTRYS>
                                      <APPLICATION-ENTRY>
                                           <DELAY>0.01</DELAY>
                                           <TRIGGER>M_LIN</TRIGGER>
                                     </APPLICATION-ENTRY>
                                    <APPLICATION-ENTRY>
                                        <DELAY>0.11</DELAY>
                                        <TRIGGER>M_LIN_1</TRIGGER>
                                   </APPLICATION-ENTRY>
                             </CON-SCHEDULE-TABLE>
                           <CON-SCHEDULE-TABLE>
                              <SHORT-NAME>RUN_MAIN</SHORT-NAME>
                             <RESUME-POSITION>START-FROM-BEGINNING</RESUME-POSITION>
                             <TABLE-ENTRYS>
                                  <APPLICATION-ENTRY>
                                      <DELAY>0.01</DELAY>
                                     <TRIGGER>M_LIN_01</TRIGGER>
                                  </APPLICATION-ENTRY>
                                 <APPLICATION-ENTRY>
                                     <DELAY>0.01</DELAY>
                                    <TRIGGER>M_LIN_02</TRIGGER>
                                 </APPLICATION-ENTRY>
                             </TABLE-ENTRYS>
                        </CON-SCHEDULE-TABLE>
                        <CON-SCHEDULE-TABLE>
                             <SHORT-NAME>RUN_MAIN</SHORT-NAME>
                            <RESUME-POSITION>START-FROM-BEGINNING</RESUME-POSITION>
                           <TABLE-ENTRYS>
                               <ASSIGN-FRAME-ID-RANGE>
                               <DELAY>0.01</DELAY>
                               <ASSIGNED-SLAVE-CONFIG>SAMPLE</ASSIGNED-SLAVE-CONFIG>
                               <FRAME-IDS>
                                  <FRAME-ID>
                                     <INDEX>0</INDEX>
                                  </FRAME-ID>
                                    <FRAME-ID>
                                     <INDEX>0</INDEX>
                                  </FRAME-ID>
                               </FRAME-IDS>
                            </ASSIGN-FRAME-ID-RANGE>
                            <ASSIGN-FRAME-ID>
                                <DELAY>0.01</DELAY>                       
                                <TRIGGER>M_LIN_03</TRIGGER>
                            </ASSIGN-FRAME-ID>
                            <ASSIGN-FRAME-ID>
                                <DELAY>0.01</DELAY>                       
                                <TRIGGER>M_LIN_03</TRIGGER>
                            </ASSIGN-FRAME-ID>
                          </TABLE-ENTRYS>
                       </CON-SCHEDULE-TABLE>
                       <CON-SCHEDULE-TABLE>
                         <SHORT-NAME>RUNEVENT</SHORT-NAME>
                         <RESUME-POSITION>START-FROM-BEGINNING</RESUME-POSITION>
                         <TABLE-ENTRYS>
                            <APPLICATION-ENTRY>
                               <DELAY>0.02</DELAY>
                               <TRIGGER>M_LIN</TRIGGER>
                            </APPLICATION-ENTRY>
                         </TABLE-ENTRYS>
                       </CON-SCHEDULE-TABLE>
                     </SCHEDULE-TABLES>                    
      </LIN-PHYSICAL-CHANNEL>


                      </PHYSICAL-CHANNELS>
                    </LIN-CLUSTER-CONDITIONAL>


                </LIN-CLUSTER-VARIANTS>

         </AR-PACKAGE>
     </AR-PACKAGES>
     </AR-PACKAGE>


   </AR-PACKAGES>

Please find the script which i have tried for the logic

Imports Microsoft.Office.Interop
Imports Microsoft.Office.Interop.Excel
Imports System.Text.RegularExpressions
Imports System.IO
Imports System.Xml
Imports System.Linq
Imports System.Xml.Linq
Imports System.Collections.Generic

Public Class frm_HexGen
    Private Sub Button1_Click1(Sender As Object, e As EventArgs) Handles Button1.Click
        Dim str_File_Name = “Schedule.xlsx”
        Dim str_File_Template As String
        Dim xlApp As Excel.Application
        Dim xlWB As Excel.Workbook
        Dim xlSH As Excel.WorkSheet
        Dim myRange As Excel.Range

        Dim Current_Directory As String

        Current_Directory = CurDir()

        str_File_Template = Current_Directory&”\_log”&str_File_Name

        xlWB=xlApp.Workbooks.Open(str_File_Template)
        xlApp.Visible=True
        xlApp.ActiveWindow.WindowState=XlWindowState.xlMaximized

        xlSH=xlWB.Worksheets(“Sheet1”)
        xlSH.Activate

        If NOT My.Computet.FileSystem.FileExists(str_File_Template) Then
            MsgBox(“error”)
        End If

        Dim iRow As Long = 2

        Dim bOK As Boolean
        Dim OXMLDOC As Object=Nothing

        oXMLDOC=CreateObject(“Microsoft.XMLDOM”)
        bOK=oXMLDOC.Load(“board.xml”)

        If not bOK Then
            MsgBox(“failed to load”)
        End If

        Dim nodes1,nodes2,nodes3,nodes4,nodes5
        Dim nodes1,node2,node3,node4,node5

        Dim str_Frame_Trigger As String = “”
        Dim str_Frame_Trigger_Name As String()
        Dim str_Trigger_Name As String
        Dim str_Length As Integer
        Dim str_Frame_Name As String
        Dim str_Identifier As Integer

        nodes1=oXMLDOC.SelectNkdes(“//CLUSTER”)

        For Each node1 In nodes1
            For Each node2 In node1.ChildNodes
                If node2.tagName =”SHORT-NAME” Then
                    iRow = iRow+1
                    xlSH.Cells(iRow,2)=node2.Text
                ElseIf node2.tagName = “LIN-CLUSTER-VARIANTS”
                    nodes3 = node2.SelectNodes(“//LIN-CLUSTER-VARIANTS/LIN-CLUSTER-CONDITIONAL/PHYSICAL-CHANNELS/LIN-PHYSICAL-CHANNEL/SCHEDULE-TABLES/SCHEDULE-TABLE/*)
                    For Each node3 in nodes
                        If node3.tagName=”SHORT-NAME” Then
                        testID = testID+1
                        xlSH.Cells(iRow,1)= testID
                        xlSH.Cells(iRow,3)= node3.text
                ElseIf node3.tagName=”Table-Entrys” Then
                    node4=node3.SectNodes(“(APPLICATION-ENTRY|ASSIGN-FRAME-ID|ASSIGN-FRAME-ID-RANGE)/*)
                    For Each node4 In nodes4
                        If node4.tagName = “DELAY” Then
                        If not Is nothing(xlSH.Cells(iRow,4) Then iRow=iRow+1
                        xlSH.Cells(iRow,4)=node4.text
                ElseIf node4.tagName = “TRIGGER” Then
                If not Is nothing(xlSh.Cells(iRow,5) Then iRow=iRow+1
                str_Frame_Trigger= node4.Text

                nodes5=node2.SelectNode(“//LIN-CLUSTER-VARIANTS/LIN-CLUSTER-CONDITIONAL/PHYSICAL-CHANNELS/LIN-PHYSICAL-CHANNEL/FRAME-TRIGGERINGS/FRAME-TRIGGERING/*)
                For Each node5 In nodes5
                    If node5.tagName=”SHORT-NAME”
                        str_Frame_Name=node5.Text
                        If str_Frame_Name = str_Frame_Trigger Then
                            str_Identifier = node5.tagName(“IDENTIFIER”).text
                            xlSH.Cells(iRow,6)=str_Identifier
                            Exit For
                        End If
                    End If
                Next

            End If

        Next
        iRow=iRow+1

    End If
Next

        End If
    Next

Next




    End Sub


End Class

I have a time in a cell, want to minus 2 hrs and add 2hrs to the time and display in excel

$
0
0

I have a time in a cell, want to minus 2 hrs and add 2hrs to the time and display in excel

Example : 02/08/2020 11:00AM So Minus 2hrs and plus 2 hrs next cell must display as 9:00AM-13:00PM

I tried the below formula but displays like 43811.0577893518 - 43811.2244560185 =CONCATENATE(A1-TIME(2,0,0),"","-","",A1+TIME(2,0,0))

vba run time error '- 2146697208 800c0008 )': the download of the specified resource has failed telegram

$
0
0

Request your help to solve the below issue,I am struck for two days,

vba run time error '- 2146697208 (800c0008 )': The download of the specified resource has failed

This is my code for your reference:

Sub telebot15status155555()

   'Program Excel Messeger
   ' Purpose : Send Message to Telegram
   ' Author : John Eswin Nizar
   ' Date : 09 October 2017

    Dim objRequest As Object
    Dim strChatId As String
    Dim strMessage1 As String
    Dim strMessage2 As String
    Dim strPostData As String
    Dim strResponse As String

    strChatId = "@messstatus"
    strMessage1 = ""
    strMessage2 = Now()

    'strMessage = "hallo"

     strPostData = "chat_id="& strChatId & "&text="& strMessage1 & strMessage2

     Set objRequest = CreateObject("MSXML2.XMLHTTP")

     With objRequest
         .Open "POST", "https://api.telegram.org/sendMessage?", False
         .setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
         .send (strPostData)
         GetSessionId = .responseText
         MsgBox GetSessionId
     End With
End Sub

Header menu included in exported excel sheet in wordpress front pages

$
0
0
$now = gmdate('D, d M Y H:i:s') . ' GMT';
  $filename ="analysis_report.xls";
  header('Content-type: application/ms-excel');
  header('Expires: ' . $now);
  header('Content-Disposition: attachment; filename='.$filename);
  header('Pragma: no-cache');
  require(SB_PATH."views/export_analysis/analysis_report_export.php");
  exit;

I have to export dynamic html table data in wordpress front users data comes fine but header menu also get included in excel sheet Same code working fine in wordpress backend. Here is screenshot https://prnt.sc/qyw9v6

Please suggest to correct this.

Code saves my file lots of times instead of one

$
0
0

Can anyone help me with my code. I am just a beginner in VBA and I manage to get few codes from internet to create an automatic saving for my file on specific time with creating a new file with a date and time. The problem is when it start creating the new file, instead of one, it create random files every second. For yesterday I had 200 files created. I have few saving code in my VBA : one after every action taken in the Workbook, one for preventing of closing the file and one to do the copy with the date and time name.

I know I have plenty of savings inside of the code but do not know which one to remove so my code to stop saving the file n-times every day.

Thank you in advance. If you need more explanations, please let me know.

The code in my workbook :


    Private Sub Workbook_AfterSave(ByVal Success As Boolean)
     'If Weekday(Date) = 5 Then
     Application.OnTime TimeValue("23:30:00"), "copySheets"
    End Sub

    Private Sub Workbook_BeforeClose(Cancel As Boolean)
    'Step 1: Check to see if cell C7 is blank
    If sheets("Trailers").Range("Z1").Value = "" Then
    'Step 2: If cell is blank, cancel the close and tell user
        Cancel = True
        MsgBox "NOPE !!!"'Step 3: If cell is not blank, save and close
    Else
        ActiveWorkbook.Close SaveChanges:=True
    End If
    End Sub


    Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
    Application.DisplayAlerts = False
    ActiveWorkbook.Save
    Application.DisplayAlerts = True
    End Sub

    Private Sub Workbook_WindowResize(ByVal Wn As Window)
    Wn.WindowState = xlMaximized
    ActiveWindow.EnableResize = False
    End Sub

     and The code in my Module for creating a new file with date and time. (sorry can't make this out of the code in here).

    Sub copySheets() 

    Dim wkb As Excel.Workbook
    Dim newWkb As Excel.Workbook
    Dim wks As Excel.Worksheet
    Dim newWks As Excel.Worksheet
    Dim sheets As Variant
    Dim varName As Variant
    '------------------------------------------------------------
     'Clearing all the values every Saturday
     'If Weekday(Date) = 7 Then
     'Worksheets("Trailers").Range("A3:D307").ClearContents
     'Worksheets("Trailers").Range("G3:G307").ClearContents
     ' Worksheets("Trailers").Range("J3:J307").ClearContents
      ' Worksheets("Trailers").Range("M3:M307").ClearContents
       ' Worksheets("Trailers").Range("P3:P307").ClearContents
       ' End If
       ' Application.OnTime TimeValue("23:30:00"), "copySheets"'Define the names of worksheets to be copied.
    sheets = VBA.Array("Trailers")


    'Create reference to the current Excel workbook and to the destination workbook.
    Set wkb = Excel.ThisWorkbook
    Set newWkb = Excel.Workbooks.Add


    For Each varName In sheets

        'Clear reference to the [wks] variable.
        Set wks = Nothing

        'Check if there is a worksheet with such name.
        On Error Resume Next
        Set wks = wkb.Worksheets(VBA.CStr(varName))
        On Error GoTo 0


        'If worksheet with such name is not found, those instructions are skipped.
        If Not wks Is Nothing Then

            'Copy this worksheet to a new workbook.
            Call wks.Copy(newWkb.Worksheets(1))

            'Get the reference to the copy of this worksheet and paste
            'all its content as values.
            Set newWks = newWkb.Worksheets(wks.Name)

        End If

    Next
    'ActiveWorkbook.SaveCopyAs Filename:=ThisWorkbook.Path & Format(Now(), "YYYYMMDD") & " Forecasting"& ".xlsm"
         Application.DisplayAlerts = False
     ActiveWorkbook.ActiveSheet.Name = "report"
     ActiveWorkbook.SaveAs Filename:=ThisWorkbook.Path & "\"& "report "& Format(CStr(Now()), "dd-mmm (hh.mm.ss AM/PM)") & ".xlsx"
        Application.DisplayAlerts = False
        ActiveWorkbook.Close SaveChanges:=True


    End Sub

Excel VBA is Finding Every Other Cell not Every Cell From Method

$
0
0

Excel VBA is finding every other cell using a method to check for Empty Cells. On the next time running the same macro, it then finds the cell that it skipped over on the last run while again skipping the next instance of an empty cell. If I cycle through the macro a few times, eventually every row without data is getting deleted, as per the purpose of the macro. The rows do shift upward upon deletion of the row one at a time, I will try a Union and delete the Range as stated by @BigBen

When a cell that is empty is found, it checks columns A, B, and D to see if formula is applied, and if a formula exists in that row, the entire row gets deleted.

Dim cel, dataCells As Range
Dim rngBlank, dc As Range
Dim lastRow, cForm, c, blnkRange As String
Dim cycleTimes As Integer

On Error Resume Next

Set dataCells = Range("F2:W2").Cells    'This is header of the table of data
cycleTimes = dataCells.Count            'Number of times to cycle through macro

For Count = 1 To cycleTimes             'I don't want to cycle through macro
    lastRow = Range("N"& Rows.Count).End(xlUp).Row   'To find end of column
    For Each dc In dataCells
        c = Split(Cells(1, dc.Column).Address, "$")(1)    'Column Letter
        blnkRange = c & "3:"& c & lastRow                'Range to look over for empty cells
        Set rngBlank = Range(blnkRange).SpecialCells(xlCellTypeBlanks).Cells
        For Each cel In rngBlank                          '**Skipping Every other Row**
            If Not TypeName(cel) = "Empty" Then
                cForm = "A"& cel.Row & ",B"& cel.Row & ",D"& cel.Row  'Formula check
                If Range(cForm).HasFormula Then
                    cel.EntireRow.Delete
                End If
            End If
        Next
    Next
Next

Converting a multiple spaced text data into dataframe/excel/csv

$
0
0

I have a data in txt format with 38 columns which looks like this. Except the header row, most of the rows have missing values.I want to convert this table into an array/dataframe/excel. But it is not coming as it looks in table.

I tried using python

df = pandas.read_csv(filename, sep='\s+',names=colnames, header=None)

I am confused about what seperator to use.

The program should look for value after single space. If no value is present, fill it with nan. How to do that?
Thanks in advance!

Protected excel file locked when user stays on the "password screen"

$
0
0

I have a password protected workbook which can be opened for read only if you can not enter with password to edit. Really basic stuff.

But when someone stays on the password asking window and the user does not click on anything then I can not open the file to edit. ("another user" blocking problem...) I am not able to log who is in the file because it is not actually opened but somehow still.

What is the solution for this? Can I prevent this issue? How can a read only file be protected?

The file is on a remote server and it is on read only usage by users. It is really annoys me when I need to update this file an I am just not able to do that. :(


How could I replace XML with a linebreak using the Javascript Excel API

$
0
0

I have a spreadsheet that has multiple cells containing XML formatting that I want to remove. The problem is that I can't just remove a linebreak since it ruins the formatting of the text. How can I replace the <br /> with a linebreak?

function run() {
  return Excel.run(function(context) {
    const sheet1 = context.workbook.worksheets.getItem("Sheet1");
    const sheet2 = context.workbook.worksheets.getItem("Sheet2");
    const sourceCell = sheet1.getCell(1,1).load("text") 
    const destinationCell = sheet2.getCell(1,1)

    return context.sync().then(function() {
      destinationCell.values = sourceCell.text
    })
  })
}

Let's say my sourceCell contains the following text:

[["08:00 - 08:30 brushing teeth<br />08:30 - 09:00 eating breakfast<br />09:00 - 09:30 ride the bus"]]

How would I go about replacing the <br />with a linebreak in the destination cell?

sending an excel file from backend to frontend in java [closed]

$
0
0

-how to demonstrate excel file in webpage and add it to database(MySQL Workbench) -excel columns should match my database columns. What does it mean? Imagine I have excel file and I want to convert information from file to my database. The data should be arranged by headers. P.S. I am using java language(eclipse) and tomcat(for servlet)

PERCENTILE By Header Name

$
0
0

I need to use PERCENTILE within excel

What I need to do is search the headers for a name and then do the PERCENTILE on that column

Header 1 | Header 2 | Header 3

If I want to search for Header 2, it will run the PERCENTILE on that column

how is this done?

Excel VBA change font color based on partial string match to Lists

$
0
0

I have a two worksheets with a list of devices in Sheet1 column A with installed apps, column B, and need to color code apps based on certain criteria on Sheet 2. I have three lists with all the possible applications and I am looking for a way to color code the text of the applications, not the entire cell, if the application name matches an application from the three lists.....If the application is in Sheet 2 Column A then change the font color of that app name to Red, if the application is in Sheet 2 Column B, then change the font color to Blue and Green for the 3rd List in column C. I have roughly 750 devices and about 150 applications split between 3 lists that I need to have this done. Here is the code I have so far. It works to some degree. It works with a sample sheet wiht a few apps perfectly, but once I apply it to my main sheet with 150 or so applications it doesn't change the font of all the apps listed.

Option Explicit

Sub Macro1()

    Dim Cell    As Range
    Dim Dict    As Object
    Dim Key     As String
    Dim Matches As Object
    Dim n       As Long
    Dim RegExp  As Object
    Dim Rng     As Object
    Dim Wks     As Worksheet

        Set Dict = CreateObject("Scripting.Dictionary")
            Dict.CompareMode = vbTextCompare

        Set Wks = ThisWorkbook.Worksheets("Sheet2")

        Set Rng = Wks.Range("A1").CurrentRegion
        Set Rng = Intersect(Rng, Rng.Offset(1, 0))

            For Each Cell In Rng.Cells
                Key = Trim(Cell)
                If Key <> "" Then
                    If Not Dict.Exists(Key) Then
                        Dict.Add Key, Cell.Font.Color
                    End If
                End If
            Next Cell

        Set RegExp = CreateObject("VBScript.RegExp")
            RegExp.IgnoreCase = True
            RegExp.Global = True
            RegExp.Pattern = "\w+"

        Set Wks = ThisWorkbook.Worksheets("Sheet1")

        Set Rng = Wks.Range("A1").CurrentRegion
        Set Rng = Intersect(Rng, Rng.Offset(1, 0))

            For Each Cell In Rng.Columns(2).Cells
                Set Matches = RegExp.Execute(Cell.Value)
                For n = 0 To Matches.Count - 1
                    Key = Matches(n)
                    If Dict.Exists(Key) Then
                        Cell.Characters(Matches(n).FirstIndex + 1, Matches(n).Length).Font.Color = Dict(Key)
                    End If
                Next n
            Next Cell

End Sub

enter image description hereenter image description here

If a time range in to different cells is between a range return "YES"

Any way to run multiple instances of the same excel workbook with macros?

$
0
0

I have a large macro enabled workbook that processes data and exports it in a usable format. some of the data that it processes can be large and take a while to run through the workbook. I'd like to be able to open this workbook multiple times to process multiple data sets at once. is there any way that this can be done?

I am using a python 3 app that I developed to manage the books and am more than open to using other languages and software.

Iterate through a list and compare with a user input value and return value in the adjacent cell [closed]

$
0
0

I need to compare a user input value and find the first value in a list which is larger than the user input. When that value is found, I want to provide as output the value in the same row, but adjacent column. Any help is much appreciated.

Excel Screenshot - If in this case, user inputs a value 6100, I want my vba to detect 6150, and return 28

enter image description here


Need to save changes to an already opened Excel file using Word VBA

$
0
0

I am trying to write a macro in Word so that I can save some information into an excel file somewhere else in my computer. For this reason I wrote this:

Dim exlApp As Object
Dim exlWbk As Object
Set exlApp = CreateObject("Excel.Application")
Set exlWbk = exlApp.Workbooks.Open(FileName:="D:\database.xlsx")
exlWbk.ActiveSheet.Cells(1, 1).Value = "some info"
exlWbk.Close SaveChanges:=True
Set exlWbk = Nothing
exlApp.Quit
Set exlApp = Nothing

Now this all works perfectly fine for me, except when the excel file in question (database.xlsx) is already opened by the user. In that case running the macro will prompt me to save the new changes into a new copy of my excel file, which is not what I want. I want the new changes to be included in the current excel file without creating a second copy of it.

Any help would be very much appreciated.

Since the above code presented some problems, I wrote this:

Dim exlApp As Object
Dim exlWbk As Object
Set exlApp = CreateObject("Excel.Application")
Set exlWbk = exlApp.GetObject("D:\database.xlsx")
exlWbk.ActiveSheet.Cells(1, 1).Value = "some info"
exlWbk.Save
Set exlWbk = Nothing
exlApp.Quit
Set exlApp = Nothing

But nothing changed. The thing is there are some ways to figure out whether my excel file is open or not, but the problem is that I don't know how to change my code if I find out that file is open.

Transfer of data from one worksheet to another worksheet based on a specific cell value

$
0
0

How do I transfer data from a worksheet to another based on a specific cell value? I tried several different VBA codes but I must be honest; I only have basic knowledge of VBA codes.

The case is, I have one worksheet, which is a register of a lot of information, and I want to transfer specific data from each row based on one specific cell value in the same row.

For example in Column L, I have the option via a dropdown menu to select "Yes - Urgent", "Yes" and "No". If it is "Yes - Urgent" or "Yes", I want it to automatically transfer some of the data to two separate worksheets. For example cell A, C, E and G of the same row that has "Yes" and transferred to B, D, E and F in a separate worksheet.

FYI, in the Excel workbook there is headers in all worksheets with filters. It's the filters that's bugging me specifically. I use Microsoft Office 2010.

Copy cells from one sheet to another if cell contains a value greater than zero

$
0
0

I am quite new to VBA programming, and i am facing a huge workbook, where: Sheet 1 contains around 40k rows of data and 40 columns of data. Sheet 2 contains around 550 rows of data and 15 columns of data. What i have done with the data in the two sheets is that i have made them as a table, and then i have searched "A to Z" in both tables on the same column.

What i then want to do is copy data(only values) from Sheet 2, column 12(L) to Sheet 1, column 9(I) but it should only copy it Sheet 1, column 9(I) contains a value.

I have tried with some different code, but it doesn't seem to work, do you guys have any suggestions?

Best Regards.

Is this possible? 1st .py file imports 2nd .py file which generates .xlsx file via Openpyxl. Possible to write to .xlsx file from 1st .py file?

$
0
0

I have two python files.

  1. spreadsheet_master.py
  2. spreadsheet_default.py

The _master.py imports the _default.py. The _default.py generates a .xlsx file that has empty cell data but is a formatted default spreadsheet ready for a printer. This all works without errors.

Is it possible to write cell (data) values from the _master.py file which would effectively be written to the .xlsx through the _default.py file?

Thanks, Phil

spreadsheet_master.py code:

    #! python3
'''
Purpose of this file:
Build your excel file on a copy of this file, which imports my default spreadsheet file, spreadsheet_default.py
'''
# Directly importing a module works once. For repetitive importing, use importlib.reload(fileName)
print('\n  spreadsheet_master.py launched')
import sys
for path in sys.path:
    print('path = ', path)
import importlib
importlib.import_module('spreadsheet_default') # No .py needed, causes 'ModuleNotFoundError'
print('\n  spreadsheet_master.py complete')

spreadsheet_default.py code:

#! python3
print('\n  spreadsheet_default.py started')
'''
Purpose of this file:
# Create Spreadsheet
# Create Sheets
# Enter Cell Values
# Set Font & Cell Color
# Merge Cells
# Add Print Options
# Column and Row Dimensions
# Add Borders
'''
# Create Spreadsheet
print('\n  Create Spreadsheet')
import os
import openpyxl
from openpyxl.styles import Alignment, Border, Side, NamedStyle, Font, PatternFill, Protection, GradientFill, Color, colors
# Set directory
# os.chdir('D:') # Todo: Change directory
print('Current Working Directory = %s' % os.getcwd())
# create workbook
wb = openpyxl.Workbook()
print('type(wb) =', type(wb))

# Create Sheets
print('\n  Create Sheets')
print('sheetnames = ', wb.sheetnames)
# wb.active = 0 # sheet index number
sheet01 = wb.active
sheet01.title = 'sheet01'
sheet02 = wb.create_sheet(title='sheet02', index=1)
sheet03 = wb.create_sheet(title='sheet03', index=2)
print('sheetnames =',  wb.sheetnames) # 
wb.save('_spreadsheet_template.xlsx')


# Cell Values (Note: Both ways enter values into cells)
print('\n  Cell Values')
sheet01['A1'] = ''
sheet01['B1'].value = ''
sheet01['C1'] = ''
sheet01['D1'].value = ''
sheet01['E1'] = ''
sheet01['F1'].value = ''
sheet01['G1'] = ''
sheet01['H1'].value = ''
sheet01['I1'] = ''
sheet01['J1'].value = ''
sheet01['A2'] = 'merged A2:A5'

# Set Font & Cell Color
print('\n  Set Font & Cell Color')
headerFont = Font(name='Calibri', size=12, bold=True, underline='single', italic=False)
for row_cells in sheet01.iter_rows(min_row=1, max_row=1):
    for cell in row_cells:
        cell.font = headerFont
        cell.fill = PatternFill(fgColor='A9A9A9', fill_type = 'solid')
        cell.alignment = Alignment(horizontal='center', vertical='center', wrapText=True)

# Merge Cells
print('\n  Merge Cells')
sheet01.merge_cells('A2:A5')
# sheet.unmerge_cells('A1:A5')

# Freeze Panes # See notes at end
print('\n  Freeze Panes')
sheet01.freeze_panes = 'A2'

# Print Options
print('\n  Print Options')
sheet01.print_area = 'A1:J40' # Set print_area
sheet01.print_options.horizontalCentered = True
sheet01.print_options.verticalCentered = True
# Page margins
sheet01.page_margins.left = 0.25
sheet01.page_margins.right = 0.25
sheet01.page_margins.top = 0.75
sheet01.page_margins.bottom = 0.75
sheet01.page_margins.header = 0.3
sheet01.page_margins.footer = 0.3
# Headers & Footers
sheet01.oddHeader.center.text = "&[File]"
sheet01.oddHeader.center.size = 20
sheet01.oddHeader.center.font = "Tahoma, Bold"
sheet01.oddHeader.center.color = "000000" # 
sheet01.oddFooter.left.text = "&[Tab]"
sheet01.oddFooter.left.size = 12
sheet01.oddFooter.left.font = "Tahoma, Bold"
sheet01.oddFooter.left.color = "000000" # 
sheet01.oddFooter.right.text = "&[Path]&[File]"
sheet01.oddFooter.right.size = 6
sheet01.oddFooter.right.font = "Tahoma, Bold"
sheet01.oddFooter.right.color = "000000"

# Column and Row Dimensions
rows = range(2, 20, 1)
cols = range(1, 10, 1)
for row in rows:
    for col in cols:
        sheet01.row_dimensions[row].height = 15.00
        # DELETE: sheet01.row_dimensions[row].width = 200.00
        sheet01.column_dimensions['A'].width = 22.00
        # ERROR: sheet01.column_dimensions[cols].width = 30.00
sheet01.row_dimensions[1].height = 40.00 # header row

# Cell Borders
print('\n  Cell Borders')
borderThick = Border(left=Side(style='thick'), 
                    right=Side(style='thick'), 
                    top=Side(style='thick'), 
                    bottom=Side(style='thick')) #
borderThin = Border(left=Side(style='thin'),
                    right=Side(style='thin'),
                    top=Side(style='thin'),
                    bottom=Side(style='thin')) # 
borderTop = Border(top=Side(style='thick'),
                    left=Side(style='thin'),
                    right=Side(style='thin'), 
                    bottom=Side(style='thin'))
borderBottom = Border(bottom=Side(style='thick'),
                    left=Side(style='thin'),
                    right=Side(style='thin'),
                    top=Side(style='thin'))
borderLeft = Border(left=Side(style='thick'),
                    right=Side(style='thin'),
                    top=Side(style='thin'),
                    bottom=Side(style='thin')) # 
borderRight = Border(right=Side(style='thick'),
                    left=Side(style='thin'),
                    top=Side(style='thin'),
                    bottom=Side(style='thin')) # 
borderTopLeft = Border(left=Side(style='thick'),
                    right=Side(style='thin'),
                    top=Side(style='thick'),
                    bottom=Side(style='thin')) #
borderTopRight = Border(left=Side(style='thin'),
                    right=Side(style='thick'),
                    top=Side(style='thick'),
                    bottom=Side(style='thin')) #
borderBottomLeft = Border(left=Side(style='thick'),
                    right=Side(style='thin'),
                    top=Side(style='thin'),
                    bottom=Side(style='thick')) #
borderBottomRight = Border(left=Side(style='thin'),
                    right=Side(style='thick'),
                    top=Side(style='thin'),
                    bottom=Side(style='thick')) #
# Set thin borders on entire sheet
rows = range(1, 41)
rowTop = int(1)
rowBot = int(40)
colLeft = int(1)
colRight = int(10)
columns = range(1, 11)
for row in rows:
    for col in columns:
        sheet01.cell(row, col).border = borderThin
# Set thick outer borders
for row in rows:
    for col in columns:
        sheet01.cell(rowTop, col).border = borderTop
        sheet01.cell(rowBot, col).border = borderBottom
        sheet01.cell(row, colLeft).border = borderLeft
        sheet01.cell(row, colRight).border = borderRight
        sheet01['A1'].border = borderTopLeft
        sheet01['J1'].border = borderTopRight
        sheet01['A40'].border = borderBottomLeft
        sheet01['J40'].border = borderBottomRight

wb.save('_spreadsheet_template.xlsx')
print('\n  spreadsheet_default.py complete\n')

Leave where left off [closed]

$
0
0

This may not be the hardest thing to solve but I cannot seem to figure out how to make a C# WPF program made in visual studio save where it left off. It’s more of an accounting program with the add on GrapeCity for excel sheets but whenever I type into the excel sheets and close the program, it resets the sheet. If there is any way to make the program reopen exactly where it left off that would be perfect or even a save button within the program so it can overwrite the excel sheet with the edited one. Thanks for any suggestions.

Viewing all 88566 articles
Browse latest View live


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