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

Calling the UserForm_Click subroutine

$
0
0

I have a VBA userform and I would like it to close if the user clicks the mouse anywhere (preferably anywhere on screen, but I'll take anywhere within the userform as a workable 2nd best option).

Here's my single line of code within the Userform_Click subroutine, which is located in the userform code (not in a standard module, nor in 'this workbook', nor in a worksheet):

Private Sub UserForm_Click()

    Unload Me

End Sub

The problem I have seems to be calling the UserForm_Click subroutine. No matter where or how many times I click, it just never seems to be called. This seems like it should be so simple, but I must be missing something somewhere.

Apologies if this has been asked elsewhere, but I couldn't find an answer to this specific question in my searches.


Extract Multiple Values From Same Cell

$
0
0

I have a spreadsheet of products that I need to make into an XML for importing purposes.

There are 1000's of lines and one of the cells has the product sizes combined into a single cell with sporadic use of a comma as a delimiter. Please see below;

Product | Size

aProduct| X,S,L

bProduct| XXS s

I am wanting to extract the multiple values from within the 'size' cell so that I can create an XML ready for import using foreach($sizes as $size){}

Any help on this would be great.

How can I load a library in R to call it from Excel with bert-toolkit?

$
0
0

Bert-toolkit is a very nice package to call R functions from Excel. See: https://bert-toolkit.com/

I have used bert-toolkit to call a fitted neuralnet (avNNnet fitted with Caret) within a wrapper function in R from Excel VBA. This runs perfect. This is the code to load the model within the wrapper function in bert-toolkit:

    load("D:/my_model_avNNet.rda")

    neuraln <- function(x1,x2,x3){
    xx <- data.frame(x1,x2,x3)
    z <- predict(my_model_avNNET, xx)
    z
}

Currently I tried to do this with a fitted GAM (fitted with package mgcv). Although I do not succeed. If I call the fitted GAM from Excel VBA it gives error 2015. If I call the fitted GAM from a cell it gives #VALUE! At the same time the correct outcome of the calculation is shown in the bert-console!

This is the code to load the model in the wrapperfunction in bert-toolkit:

library(mgcv)
load("D:/gam_y_model.rda")

testfunction <- function(k1,k2){
  z <- predict(gam_y, data.frame(x = k1, x2 = k2))
  print (z)
}

The difference between the avNNnet-model (Caret) and the GAM-model (mgcv) is that the avNNnet-model does NOT need the Caret library to be loaded to generate a prediction, while the GAM-model DOES need the mgcv library to be loaded.

It seems to be not sufficient to load the mgvc-library in the script with the GAM-model which loads the GAM-model in a wrapper function in bert-toolkit, as I did in the code above. Although the correct outcome of the model is shown in the bert-console. It does not generate the correct outcome in Excel. I wonder how this is possible and can be solved. It seems to me that maybe there are two instances of R running in bert-toolkit.

How can I load the the mgcv-library in such a way that it can be used by the GAM-model within the function called from Excel? This is some example code to fit the GAM with mgcv and save to model (to load it in bert-toolkit with the code above) :

library(mgcv)

# construct some sample data:
x <- seq(0, pi * 2, 0.1)
x2 <- seq(0, pi * 20, 1)
sin_x <- sin(x)
tan_x2 <- tan(x2)
y <- sin_x + rnorm(n = length(x), mean = 0, sd = sd(sin_x / 2))
Sample_data <- data.frame(y,x,x2)

# fit gam:
gam_y <- gam(y ~ s(x) + s(x2), method = "REML")

# Make predictions with the fitted model:
  x_new <- seq(0, max(x), length.out = 100)
  x2_new <- seq(0, max(x2), length.out = 100)
y_pred <- predict(gam_y, data.frame(x = x_new, x2 = x2_new))

# save model, to load it later in bert-toolkit:
setwd("D:/")
save(gam_y, file = "gam_y_model.rda")

Adjusting a function which pulls a table from a web page to pull only a single element + repeat

$
0
0

I've got a weird project I'm trying to pull off. Essentially, I have a tool that will create an extensive spreadsheet of the entire inventory of a specific section of a warehouse. It lists off their location, inventory state, and their item ID ("ASIN" which is basically it's barcode and virtual reference in the internal system. Problem is, it does not list off the "velocity" (a metric of how many we sell in a week) of those specific items, and I would like to get this metric printed out adjacent to every item ID so I can sort out what isn't selling and send it to a long-term storage section of the warehouse. I've found another tool which grabs a table of information about an individual item ID from our internal wiki("FCresearch") which happens to contain this specific metric. I'm looking to grab only the velocity of an item out of this table (essentially the number that is in this location:

/html/body/div[2]/div/div[1]/div/div[1]/div/div[2]/div/div/div[2]/table/tbody/tr[19]/td 

on the web page) and then adapt this macro so it acts on an ASIN in the table created by the former tool, prints the velocity of it to the adjacent cell, then moves a row down and repeats for all ~4000 entries until it hits empty space.

Here is the full relevant function:

    Sub getFCresearch()
Dim A As Object, H As Object, D As Object, C As Object, asin$, B$, F$
Dim x&, t&
Set C = CreateObject("New:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")
Set D = CreateObject("HTMLFile")
Set A = CreateObject("New:{00000566-0000-0010-8000-00AA006D2EA4}")
Set H = CreateObject("WinHTTP.WinHTTPRequest.5.1")
    H.SetAutoLogonPolicy 0

''passes badge
    H.Open "GET", "https://hrwfs.amazon.com/?Operation=empInfoByUid&ContentType=JSON&employeeUid="& Environ("USERNAME")
    H.send

DoEvents

B = Split(Split(H.ResponseText, "employeeBarcode"":""")(1), Chr(34))(0)


    H.Open "POST", "http://fcmenu-iad-regionalized.corp.amazon.com/do/login"
    H.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
    H.setRequestHeader "Content-Length", Len("badgeBarcodeId="& B)
    H.send "badgeBarcodeId="& B

DoEvents

H.Open "GET", "http://fcmenu-iad-regionalized.corp.amazon.com/"& F
H.send
DoEvents

''Needs to derive "asin" variable from adjacent cell
asin = Sheets("Sheet1").[A1]

''This gathers the specific item's page on the wiki "FCresearch"
H.Open "GET", "http://fcresearch-na.aka.amazon.com/DEN3/results/inventory?s="& asin, False
H.send

'''This gets the whole table,where I only need one specific element called "velocity" at: /html/body/div[2]/div/div[1]/div/div[1]/div/div[2]/div/div/div[2]/table/tbody/tr[19]/td
D.body.InnerHTML = H.ResponseText
C.SetText D.GetElementById("table-inventory").OuterHTML
C.PutInClipboard

''This pastes the table to a different sheet, but needs to paste to a cell adjacent to the "asin" variable of each row
''Before moving down to the next row and repeating the process
Sheet2.[C:Z].Cells.ClearContents
Sheet2.[C1].PasteSpecial

Sheet2.[C:N].WrapText = False
Sheet2.Columns("C:N").AutoFit
End Sub

Any help you all can provide would be amazing. Apologies that it's such an extensive thing, I'm fairly new to this and I've only been able to adjust minor things about the code, and I haven't been able to find documentation anywhere that helps any deeper than the .GetElementById function that doesn't work on a html element without an ID.

Image of table HTML, + plaintext

<table data-row-id="1579657885" class="a-keyvalue"><tbody><tr><th>ASIN</th><td><a href="/DEN3/results?s=1579657885">1579657885</a></td></tr><tr><th>Title</th><td><a target="_blank" href="http://www.amazon.com/gp/product/1579657885">1,000 Places to See Before You Die (Deluxe Edition): The World as You've Never Seen It Before</a></td></tr><tr><th>Binding</th><td>Hardcover</td></tr><tr><th>Publisher</th><td></td></tr><tr><th>Vendor Code</th><td>ATSAN</td></tr><tr><th>Weight</th><td>6.45 pounds</td></tr><tr><th>Dimensions</th><td>1.50 x 13.00 x 9.80 IN</td></tr><tr><th>List Price</th><td>USD 50.00</td></tr><tr><th>Expiration Date</th><td class=""></td></tr><tr><th>Asin Demand</th><td><a target="_blank" href="https://ufo.amazon.com/srw14na/asins/place_in_line/1579657885?warehouse=DEN3">Demand for 1579657885</a></td></tr><tr><th>Sortable</th><td>true</td></tr><tr><th>Conveyable</th><td>true</td></tr><tr><th>Very High Value</th><td>false</td></tr><tr><th>Master Case</th><td>false</td></tr><tr><th>FCSku Scope</th><td>FNSKU</td></tr><tr><th>Sales Forecast</th><td>4.0</td></tr><tr><th>Sales History (approx)</th><td>5.0</td></tr><tr><th>Sales Override</th><td>0.0</td></tr><tr><th>ASIN Velocity (approx)</th><td>5.0</td></tr><tr><th>Provenance Value</th><td>UNTRACKED</td></tr><tr><th>Provenance IOG</th><td>Info Not Found</td></tr></tbody></table>

How can I learn to use R to do an excel V-lookup function that retrieves data from other excel files?

$
0
0

I am trying to learn how to use R/R studio for a project. Some of the initial tasks I will be using R for are described below, and I would be very grateful for a resource that teaches me how I could perform the tasks below.

I have a column of unique identifiers in one excel document (document A), ie a, b, and c. I have another excel document for each of these identifiers, with the same name as these unique identifiers. So for each unique ID, I want to look-up the spreadsheet with a matching name, and from that spreadsheet, I want to retrieve the first and final value in a certain column, as well as the mean and maximum values in that column.

I am interested in finding a resource that will teach me to do all this and more, and don't mind investing time to learn ie I am not in a rush to do this.

After this step, I have something more complicated I want to do.

I have another document (document B) where I have a column of identifiers, but the identifiers are repeated multiple times. So again, using the first document with the list of identifiers, I want to search through document B and retrieve values from the rows where the identifier is mentioned for the first and last time in the column.

If you have a resource I can study to learn to do all this and more I would be very grateful. Thank you.

Index Match on 2 Million Records covering 10k rows

$
0
0

I have a Normal Table, the Match Column is what is brought back with the index match formula, the ID is what we search for

ID | Name | Group | Match
11 | Bob  | Red   | **2020**
---- continues for 10,000+ rows ----

The Lookup needs to search 2 million records, but Excel is not able to hold so many records, how am I able to look up all those records?

Excel/Google Sheets: How to find (and count) first occurrences of a string

$
0
0

I have a list of purchases in a spreadsheet (CSV, so I can do the operation in Excel or Google Sheet, doesn't matter), so single lines that include data like:

Date, Customer Email, Customer ID, Product

I'm struggling to find out the number of new customers per month.

I'm familiar with pivot tables, however, I think I need a formula or helper table prior to pivoting the data?!

Basically I need to identify when each Customer Email or Customer ID occurs for the first time.

The ideal desired output would be a (pivot?) table like:

Month, Number of new customers
January 2019, 100
February 2019, 120
...

As you can see I'm struggling a bit to put it into words, which might also be the reason why I'm struggling to find the answer that I'm sure is already out there.

Does anyone know what I mean, and have a hint in regards to how to achieve it?

Thanks in advance.

Cut the shape (image) and paste in another sheet with custom ID

$
0
0

I have a problem.

I would like to cut my shape and paste it on another sheet with the specified ID. Next I want to cut from that target sheet and paste it in the mother sheet (move back).

My code looks as follows:

 Sub Location()
 ActiveSheet.Shapes("Textbox_Location1").Copy
 Sheets("Readme").Range("AA1").PasteSpecial
 Selection.Name = "Location"
 End Sub


 Sub Locationremove()
 Sheets("Readme").Shapes("Location").Cut
 ActiveSheet.Range("F7").PasteSpecial
 Selection.Name = "Textbox_Location1b"
 End Sub

However, I can't do it, because the shape changes the ID every time when pasted in the target sheet. Is there a way to prevent its mother ID or at least the custom one?


Changing a cell value based on today's date

$
0
0

I have not done VB for excel before, but have experience in some other languages.

I am looking to have the person input the amount in Todays Excess and have it automatically key that amount on another cell based on the date (todays date).

enter image description here

Code to return list of file names in a folder and additionally return text from 35th to 40th position on line one each file using VBscript

$
0
0

I am trying to write a script that will read all file names in a folder and list them out, Also at the same time read read text 35th to 45th from first line

Sample file data

 {1:XXXXXXXXXXXXXX0000000000}{2:XXXXXXXXXXXXXXXXX}
{4:
:20:XXXXXXXXXXX
:21:XXXXXXXXXXX

My code

 Dim objFileSystem,wshShell,MainPath,fileCount,fileLIst,FiletoRead, objFile,strline, Newfile


Set objFileSystem = CreateObject("Scripting.FileSystemObject")
Set NewFile = objFileSystem.CreateTextFile("c:\test\FileList.txt", True) 'Text file object
Set NewFile = objFileSystem.CreateTextFile("c:\test\FileList.txt", True) 'Text file object
MainPath="Path Location"


rem inputbox("Enter File Location here")
if objFileSystem.FolderExists(MainPath) then 
msgbox "control here 1"
FindFileRec MainPath
else
msgbox "Path "&  MainPath & "not found"
else if
 msgbox "completed"

Function FindFileRec(ThisFolder) 
Dim fileName,subFolderobj,subFolderList,Folderobj
Set Folderobj=objFileSystem.GetFolder(ThisFolder)
msgbox "control here 2"

For Each fileName In Folderobj.Files 
fileCount=fileCount+1 'update count
UpldateListInTextFile fileName.Name,NewFile
Next 'File
NewFile.Close()
End Function 

Function UpldateListInTextFile(sfile, NewFile) 
NewFile.WriteLine(sfile) 
End function

Create subfolders based on cell value and copy images to same folder

$
0
0

I am working on a big project and the ability to change the code stopped at this point. So help is needed please.

The main folders have subfolders and MSR files inside which are related to eachother with the naming.We have to input this main folder path into D4 on our excel file. The MSR have all the info related to every image. Image folders have all the images inside and we need to sort the all into subfolders. We already have a macro that retrieves a list on which images are correlated to the correct position. ( see third image) What we want do now is creating subfolders into the main folder that corresponds to the "*test" in this case and in this new folder there should be subfolders created based on how many unique places there are. In this case it would result in 18 subfolder. The combination of Column D and E are the unique places (first 2 examples = 13200-9496 and 13213-9506). All the image files that corrospond to this place should be put in the new subfolder.

I hope this is somewhat clear?

Main folder overview

enter image description here

Sub folder overview

enter image description here

Output data

enter image description here

Code:

    Application.DisplayAlerts = False
    Application.ScreenUpdating = False


    Dim WBMacro As Workbook
    Set WBMacro = ActiveWorkbook
    Dim FoName As Range
    Set FoName = WBMacro.Sheets("Instructions").Range("B4")


        FolderName = FoName
        If Right(FolderName, 1) <> Application.PathSeparator Then FolderName = FolderName & Application.PathSeparator
        FName = Dir(FolderName & "*.msr")

        'loop through the files
        Do While Len(FName)

              Dim WBMSR As Workbook
              Set WBMSR = Workbooks.Open(FolderName & FName)

            With WBMSR

    Columns("A:A").Select

        Selection.TextToColumns Destination:=Range("A1"), DataType:=xlDelimited, _
            TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=True, Tab:=False, _
            Semicolon:=False, Comma:=False, Space:=True, Other:=False, FieldInfo _
            :=Array(Array(1, 1), Array(2, 1), Array(3, 1)), TrailingMinusNumbers:=True


     'Create new tab to copy data of interest in
     Dim WsMSR As Worksheet
     Set WsMSR = WBMSR.ActiveSheet
     WsMSR.Name = "MSRData"

     .Worksheets.Add

     Dim wsPictData As Worksheet
     Set wsPictData = WBMSR.Sheets("Sheet1")
     wsPictData.Name = "PictureInfo"'Define where to copy data to

     Dim RngPictName As Range
     Dim RngX As Range
     Dim RngY As Range

     Set RngPictName = wsPictData.Range("A2")
     Set RngXY = wsPictData.Range("B2")
     Set RngChipCoX = wsPictData.Range("D2")
     Set RngChipCoY = wsPictData.Range("E2")

     RngPictName.Offset(-1, 0) = "PictName"
     RngXY.Offset(-1, 0) = "DieX,DieY"
     RngChipCoX.Offset(-1, 0) = "ChipCoX"
     RngChipCoY.Offset(-1, 0) = "ChipCoY"'Find PictureName

     Dim RngPictStart As Range
     Dim RngPictStop As Range
     Dim RngPict As Range


    Dim strImage As String
    strImage = "&mp_image_name"

    Dim strChipNr As String
    strChipNr = "Chip_number"

    Dim strChipCo As String
    strChipCo = "Chip_coordinate"

    With WsMSR.Range("B:B")

     Set image = .Find(strImage, lookat:=xlPart, LookIn:=xlValues)

       If Not image Is Nothing Then
            FirstAddress = image.Address

            Do

                Set pict = image.Offset(0, 2)
                pict.Copy

                    If RngPictName = "" Then
                    RngPictName.PasteSpecial
                    Else
                    RngPictName.Offset(-1, 0).End(xlDown).Offset(1, 0).PasteSpecial
                    End If


                For i = 1 To 15

                    'Do

                        If image.Offset(i, 1).Value = strChipNr Then
                        Set XY = image.Offset(i, 2)
                        XY.Copy

                            If RngXY = "" Then
                            RngXY.PasteSpecial
                            Else
                            RngXY.Offset(-1, 0).End(xlDown).Offset(1, 0).PasteSpecial
                            End If
                        End If

                        If image.Offset(i, 1).Value = strChipCo Then
                        Set ChipX = image.Offset(i, 2)
                        ChipX.Copy

                            If RngChipCoX = "" Then
                            RngChipCoX.PasteSpecial
                            Else
                            RngChipCoX.Offset(-1, 0).End(xlDown).Offset(1, 0).PasteSpecial
                            End If


                        Set ChipY = image.Offset(i, 4)
                        ChipY.Copy

                            If RngChipCoY = "" Then
                            RngChipCoY.PasteSpecial
                            Else
                            RngChipCoY.Offset(-1, 0).End(xlDown).Offset(1, 0).PasteSpecial
                            End If
                        End If

                Next


                Set image = .FindNext(image)
                                    If image Is Nothing Then
                                        GoTo DoneFinding1
                                    End If


             Loop While image.Address <> FirstAddress


         End If

    End With

DoneFinding1:

    End With


    ' change wsPictData Column B with (x,Y) to 2 columns (B = X, C = Y)

    With wsPictData

    Columns("B:B").Select

        Selection.TextToColumns Destination:=Range("B1"), DataType:=xlDelimited, _
            TextQualifier:=xlDoubleQuote, ConsecutiveDelimiter:=True, Tab:=False, _
            Semicolon:=False, Comma:=True, Space:=False, Other:=False, FieldInfo _
            :=Array(Array(1, 1), Array(2, 1), Array(3, 1)), TrailingMinusNumbers:=True



    End With


    WsMSR.Delete
    Dim WBMSRFileName As String
    WBMSRFileName = Left(WBMSR.Name, Len(WBMSR.Name) - 4)
    Dim relativePath As String
    relativePath = WBMSR.Path



    WBMSR.SaveAs Filename:=relativePath & "\"& "Pictures_"& WBMSRFileName & ".xlsx", FileFormat:=xlOpenXMLWorkbook
    WBMSR.Close (False)

      ' go to the next file in the folder

    FName = Dir


    Loop


    Application.DisplayAlerts = True
    Application.ScreenUpdating = True

    MsgBox ("all Files in folder"& relativePath & " are analyzed")

Python Xlsx writing format advice

$
0
0

I've created a list and have created a for loop to iterate over each item in it to print it to a cell in excel. I'm using openpyxl. When i first started using it using easy statements like:

sheet["A1"] = "hello"

results in Cell A1 perfectly representing the hello value, without quotation marks.

I have this code:

workbook = Workbook()
sheet = workbook.active
text = ["Whistle", "Groot", "Numbers", "Mulan", "Buddy Holly"]
other = [5, 8, 100, 120]
for i in range(1,len(text)+1):
    cell_letter = "A"
    cell_number = str(i)
    sheet[str((cell_letter + cell_number))] = str(text[i-1:i])

and it writes to the corresponding cell locations with the iterations over the variable "text". But when i open the file the format is ['Whistle'] and ['Groot']

What am i missing? Should i be passing each iteration to another variable to convert it from a list to a tuple for it to be written in then?

Sorry if my code seems a bit messy, I've literally just learnt this over the past few hours and it's (kind of) doing what I need it to do, with the exception of the writing format.

Avoid copying buttons in range

$
0
0

i have a macro where i copy paste a range, which also has buttons in there. Now i dont want the buttons to get copied. How can i do that?

I copy the whole table and insert it again at A32.

lrow = .Cells(Rows.Count, 1).End(xlUp).row
Do While counter = 0
  For i = 32 To lrow
    If .Cells(i, 1).Value = "Review Participants" And counter = 1 Then
     lastrev = lrowrev
     lrowrev = i - 1 'row where the second last review starts
     aboveR = lrowrev - lastrev
     Exit For
    ElseIf .Cells(i, 1).Value = "Review Participants" And counter <> 1 Then
     counter = counter + 1
     lrowrev = i


     lcol = 11  'hardcode last col ~~ Alt:  'lcol = .Cells(i + 1, .Columns.Count).End(xlToLeft).Column 'last meeting of the review is our reference for lastcol
        ElseIf counter = 1 And i = lrow Then
        lrowrev = i + 2
        aboveR = (i + 2) - 32
        Exit For
End If
Next
Loop

lastcolumn = Split(Cells(, lcol).Address, "$")(1)
Set rngtocopy = .Range("A"& 32 & ":"& lastcolumn & lrowrev)

Debug.Print rngtocopy.Address

'aboveR = .Range("A"& 32 & ":"& lastcolumn & lrowrev - 1).Rows.Count ' amount of rows copied

Set rngins = .Range("A32").EntireRow
Debug.Print rngins.EntireRow.Resize(aboveR + 2).Address


        rngins.EntireRow.Resize(aboveR + 2).Insert xlShiftDown 'insert the amount of rows, we copied
        'Range("A"& lrow).Offset(5).EntireRow.Hidden = False

             Set rngins = .Range("A32")
             Debug.Print rngins.Address
             rngtocopy.Copy
             rngins.PasteSpecial Paste:=xlPasteAll

Filter, print to PDF and save

$
0
0

I want to create a code that will do the following.

From pivot table filter based on a "project number" 0-100 for example. Then print the filtered data to pdf. Then move onto the next project number and repeat.

The issue I'm coming up against is the project numbers are variable each week. so it may only be 1,10,12,14 in week one but then 2,32,42,100 in the following week.

Any suggestion's on this would be great, I've pasted the beginning of what I've got so far but I don't think it's anywhere near correct.

Sub PDF_printer()
'' PDF_printer Macro
''
    ActiveSheet.PivotTables("PivotTable1").PivotFields("Approved (Y)?"). _
        CurrentPage = "(All)"
    With ActiveSheet.PivotTables("PivotTable1").PivotFields("Approved (Y)?")
        .PivotItems("Y").Visible = False
    End With
    ActiveSheet.PivotTables("PivotTable1").PivotFields("Contract Simple"). _
        CurrentPage = "(All)"
    With ActiveSheet.PivotTables("PivotTable1").PivotFields("Contract Simple")
        .PivotItems("0").Visible = False
        .PivotItems("1").Visible = False
        .PivotItems("2").Visible = False
        .PivotItems("3").Visible = False
        .PivotItems("4").Visible = False
        .PivotItems("5").Visible = False
        .PivotItems("6").Visible = False
End With
    ActiveWindow.SelectedSheets.PrintOut Copies:=1, Collate:=True, _
        IgnorePrintAreas:=False
End Sub

I know this has no print function yet, that bit I think I can do.

Concatenate range except for certain cells

$
0
0

I'm trying to concatenate values in a row with ", " as my separator. I want all values except for specific text. In this case, concatenate range except for "Yes", "No", "N/A", and blanks.


Corrupted Data Format in CSV file - Single row data split among 2 rows. Quick fix needed

$
0
0

I have 100's of csv files which appears to be corrupt. All files have the same common problem. Each file has 5 headers but the data is always split among 2 rows e.g.

enter image description here

I was thinking of a python script to correct this and was wondering if there is a function or library that can do this quickly rather than writing a whole script to adjust it. The expected format is below. How can I correct this for all files.

v

Retrieve int value from Excel if it is an int Python

$
0
0

I've got the following data that I am retrieving from an Excel spreadsheet:

enter image description here

As you can see, there are rows that have floats and others that have ints. Using my below program, if I retrieve each value using worksheet.cell_value(row, col), then each int is being retrieved as a float. For example, 321 in the Random Number column is being retrieved as 321.0.

I do not want to have decimal points if the number does not include it. I've seen a couple of examples online, specifically this one, but I've not been successful with any of the answers.

So far, I've got:

import xlrd

workbook = xlrd.open_workbook("demo.xlsx")
worksheet = workbook.sheet_by_name('Sheet1')

num_rows = worksheet.nrows
num_cols = worksheet.ncols

for row in range(num_rows):
    for col in range(num_cols):
        if isinstance(worksheet.cell_value(row, col), float):
            print(worksheet.cell_value(row, col))
        elif isinstance(worksheet.cell_value(row, col), int):
            print(int(worksheet.cell_value(row, col)))
        else:
            print(worksheet.cell_value(row, col))

But this returns the the ints with decimal points:

Version
Name
Random Number
1.1
Smith
321.0
1.2
John
1234.0
2.1
Paul
123456.0
2.2
Rich
98765.0
2.3
Harvey
567.0
2.4
Jones
90909.0

Alternatively, I have tried:

import xlrd

workbook = xlrd.open_workbook("demo.xlsx")
worksheet = workbook.sheet_by_name('Sheet1')

num_rows = worksheet.nrows
num_cols = worksheet.ncols

for row in range(num_rows):
    for col in range(num_cols):
        if worksheet.cell_value(row, col) == int(worksheet.cell_value(row, col)):
            print(int(worksheet.cell_value(row, col)))
        else:
            print(worksheet.cell_value(row, col))

But I get an error:

ValueError: invalid literal for int() with base 10: 'Version'

Else Statement - what is the correct Code?

$
0
0

I am new in here in Stackoverflow I tried to create a VBA Code.

I have these set of data that I wanted to create a macro(vba) for this so here is the scenario and code.

it is something like vlook up without a formula

The Column A is the lookup value, The column E and F is the table array, The Column F is the column index


Sub Nested()
Dim i As Integer
Dim prodID As String
Dim nRows As Integer


For i = 0 To nRows - 1

prodID = Range(a3).Offset(i, 0).Value
rng = Range(“B3”).Offset(i, 0).Value

If rng = "1" Then

If rng <= 1 Then
Range(“C3”).Offset(i, 0).Value = Range(“F1”).Value

ElseIf rng > 1 Then
Range(“C3”).Offset(i, 0).Value = Range(“F2”).Value


End If

End Sub

This is the template

enter image description here

I try to figure out what is the correct for this but I couldn't find it

Import from Excel in Python Pandas and rearrange metadata header as column data

$
0
0

I try to import data from Excel to Pandas, but I have issues with rearranging the meatadata.

The Excel sheet is in the format (simplified here): Original data

But I would like to import the Excel sheet to at Pandas dataframe and then re-arrange in this format in order to simplify statistical plotting in Pandas: Final data

I've tried the following method but I can't get to the correct format:

import numpy as np
import pandas as pd
FNAME = 'Original.xlsx'
df = pd.read_excel(FNAME, sheet_name='Sheet1', header = [0,1,2,3])
mi = pd.MultiIndex.from_frame(df)
dfmi = pd.melt(df, id_vars=[mi.names[0]])
# Add column index
col = list(mi.names[0])
col.insert(0,'temp')
col.append('value')
col[-2]='type'
dfmi.columns = col

df
Out[17]: 
                   A     a1                                     
                   B     b1                    b2               
                   C     c1                    c2               
  Unnamed: 0_level_3 Data 1 Data 2  Data 3 Data 1 Data 2  Data 3
0                NaN      1      7      13      4     10      16
1                NaN      2      8      14      5     11      17
2                NaN      3      9      15      6     12      18

dfmi
Out[18]: 
    temp   A   B   C     type  value
0    NaN  a1  b1  c1   Data 1      1
1    NaN  a1  b1  c1   Data 1      2
2    NaN  a1  b1  c1   Data 1      3
3    NaN  a1  b1  c1   Data 2      7
4    NaN  a1  b1  c1   Data 2      8
5    NaN  a1  b1  c1   Data 2      9
6    NaN  a1  b1  c1   Data 3     13
7    NaN  a1  b1  c1   Data 3     14
8    NaN  a1  b1  c1   Data 3     15
9    NaN  a1  b2  c2   Data 1      4
10   NaN  a1  b2  c2   Data 1      5
11   NaN  a1  b2  c2   Data 1      6
12   NaN  a1  b2  c2   Data 2     10
13   NaN  a1  b2  c2   Data 2     11
14   NaN  a1  b2  c2   Data 2     12
15   NaN  a1  b2  c2   Data 3     16
16   NaN  a1  b2  c2   Data 3     17
17   NaN  a1  b2  c2   Data 3     18

My prefered Pandas format would be:

    A   B   C  Data 1  Data 2  Data 3
0  a1  b1  c1       1       7      13
1  a1  b1  c1       2       8      14
2  a1  b1  c1       3       9      15
3  a1  b2  c2       4      10      16
4  a1  b2  c2       5      11      17
5  a1  b2  c2       6      12      18

But the values in dfmi are unstacked to one column only, I would like to keep the three data columns. Are there any other methods in order to get to my prefered data format?

Link to Excel file: Excel file Original data

Automatically adjust the "RC" in an English formula based on the user's install language

$
0
0

So I was surprisingly getting error reports from many users for a new tool I made. Those users all have the German version of Excel installed. After a quick glance, I figured out the problem:

I used this Formula as a named function to get the color of the adjacent cell (don't ask me why that's important, but things depend on the result):

=GET.CELL(63;OFFSET(INDIRECT("RC";FALSE);0;1))

Now in the German version, the "RC" remains, but would have to change to "ZS" for the formula to not throw a reference error.

It's written the way it is to make the reference the cell the function is in.

Is it possible to rewrite this formula in a way that does not "hard code" the "RC" so it can change depending on the localization of the user (Chinese and Czech would be relevant too)? Or is it possible to replace the named formula with a bit of vba code that can check for the language version of the user? Or do you have a different idea?

If I can't adjust this bit of the tool I'll have to go with a less attractive workaround (Have multiple Y/N checks instead of assigning colors).

Thanks in Advance

Viewing all 88111 articles
Browse latest View live


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