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

delete rows if there are 2 consecutive empty rows

$
0
0

what i want to do is to delete rows if there are 2 consecutive empty rows and also to have the empty rows between the header and the first set of data row to be deleted as well.This is my original input and what i want to have is this. i have tried to find some codes here and there and come up with this code.

Sub Testing()
    Dim i As Long , lRow As Long
    Dim ws As Worksheet

    Set ws = Activesheet
    With ws
        With .Range("C:C")
            fr = .Find(what:="*", after:=.Cells(1, 1), LookIn:=xlValues).row
            If fr > 2 Then
                .Rows("2:"& fr - 1).EntireRow.Delete
            End If
        End With
        i = 1
        For i = 1 To lRow
            If IsEmpty(Cells(i, 3)) And IsEmpty(Cells(i + 1, 3)) Then
                .Rows(i).EntireRow.Delete
           End If
        Next i
    End With
End Sub

However, there are still some consecutive empty rows in the middle of the data set. I know that is because i am increasing i which will look at the next cell but i am not sure how to solve it. I am new to vba and even newer to SO posting so let me know if there is anything i am doing wrong and thank you for your help.


Excel VBA Compile Error:Sub or Function not defined

$
0
0

this is my code and it keeps getting sub or function not defined error, im pretty sure its a simple fix but i just can't find the solution, big thanks to anyone who offers any help.                     

Sub RDB_Filter_Data()
Dim myFiles As Variant
Dim myCountOfFiles As Long

myCountOfFiles = Get_File_Names( _
                 MyPath:="C:\Users\Desktop\Tryout\", _
                 Subfolders:=True, _
                 ExtStr:="*.txt*", _
                 myReturnedFiles:=myFiles)


If myCountOfFiles = 0 Then
    MsgBox "No files that match the ExtStr in this folder"
    Exit Sub
End If

Get_Filter _
        FileNameInA:=False, _
        SourceShName:="", _
        SourceShIndex:=1, _
        FilterRng:="A1:D3500"& Rows.Count, _
        FilterField:=1, _
        FilterValue:="Ended", _
        myReturnedFiles:=myFiles

End Sub

I want sum of time divide by sum of people of the top two weights in one formula

$
0
0

Excel Sheet Raw Data

I want sum of time divide by sum of people of the top two weights in one formula. The result should give me 0.7857142857.

e.g. The formula should pick up the biggest two weights (30% and 40% of Row A). And then take (C4+C7)/(B4+B7)

Is there a way to express this in one formula?

Button mispositioned

$
0
0

I am having a problem with positioning a button within cell. The button is not positioned correctly.

Public Sub TableDisplayButton()
    Dim cr As Range, cr2 As Range
    With ActiveSheet.Shapes(Application.Caller)
    Set cr = .TopLeftCell
    Set cr2 = .BottomRightCell
    MsgBox cr.Address & ""& cr.Left
    .Left = cr.Left
    .Top = cr.Top
    .Width = Range(cr, cr2).Width
    .Height = Range(cr, cr2).Height
    end with
end sub

The button is slightly shifted left to neighbouring left cell and upon clicking it again it will reposition to another cell. Clicking button runs this subroutine TableDisplayButton.

cr.address displays the correct cell.

Does anyone know what is causing it? Is it possible that .left and .top round decimal places to integer value?

How can I set a worksheet object based on a worksheet's codename?

$
0
0

The worksheet name may change. Because of that I want to set the worksheet object based on the worksheet's codename. How can I do this?

My best attempt so far is:

Sub UpdateNameDropdown()

    Dim wksName As String
    wksName = ThisWorkbook.Sheets(Sheet16).Name

    Dim wks As Worksheet
    Set wks = Sheets(wksName)

End Sub

But I get a type mismatch error on the row wksName = ThisWorkbook.Sheets.Sheet16.Name

Unable to find row no. of cell containing special character along with alphanumeric characters

$
0
0

I have written below code to get row no. from the range("C:C") wherein I find matching value/text as that in cells(3,3). This code works fine as long as cells(3,3) has either pure no. or pure text. But as soon as cells(3,3) has special character e.g.~(as in MBGH3345~123) the code returns error. When I run this code it returns run time error 400. Please help resolve this issue.

Public Sub Find_Row_Number()

Dim wb As Workbook  
Dim ws As Worksheet  
Dim FindCell As Range  
Set wb = ActiveWorkbook  
Set ws = ActiveSheet  

Set FindCell = ws.Range("C:C").Find(cells(3,3))
'value to be searched is in cells(3,3)

If Not FindCell Is Nothing Then
Msgbox (FindCell.Row)
Else
Msgbox ("Error")
End If

End Sub

setting column to num format text instead of general python 3

$
0
0

I was able to change the header to text as the columns but I'm getting a strange error.

Now it still returns NaN but if I got in and manually highlight column B (the vendor name in text) and change the column to text via excel suddenly the second script works perfectly. And I only have to change worksheet 1.

Is there a way to mimic that in python/xlsxwriter?

I have two python scripts. One will take data from an excel sheet and parse it out to separate worksheets depending on a grouping. The second reads the totals and returns a table for an email. I've been manually building this in excel and working on automating it. The second script that builds the html table works just fine with my manual sheet. The workbook I've built with xlsxwriter looks identical save for column B with vendor names is formatted as General instead of Text (the manual sheet is text). My second script now only shows NaN when looking at the newly built sheet. I've tried to set format to text but it's not working. I am able to set format for currency on a different column so I'm not sure why text isn't working.

When I look at the cells I can see cell showing amount which is the same data returns a number but the summed cell doesn't

I'm using python 3.6 and xlsxwriter.

Column B is the one I need to change, it's a vendor name.

worksheet_paygroup.set_column('B:B', 40)

I've searched through the docs for xlsxwriter and found something for 2.7 that was specific to this but doesn't seem to work with 3.

I've tried to set_column, write_column, add_format, add_num_format

import pandas as pd
import numpy as np
import os
import datetime as dt
import pandas.io.formats.excel

df = pd.read_excel(test_sheet)

#this grabs the data from different excel sheet
df_paygroup = df[df['payments'] == 'paygroup']
df_paygroup.drop(columns='unneeded_column')
df_paygroup.insert(3, 'Total', value='') #sets new column
df_paygroup = df_paygroup[['Vendor', 'Name', 'Amount', 'Total']]
df_paygroup = df_paygroup.sort_values(by=['Amount'], ascending=False)


writer = pd.ExcelWriter('new_sheet.xlsx', engine='xlsxwriter')
pandas.io.formats.excel.header_style = None

df_paygroup.to_excel(writer, sheet_name='paygroup', index=False)
#there are 15 of these with different names


workbook = writer.book
money_format = workbook.add_format({'num_format': '[$$-409]#,##0.00'})
text_format = workbook.add_format({'num_format': '@'})

worksheet_paygroup = writer.sheets['paygroup']
worksheet_paygroup.set_column('A:A', 11)
worksheet_paygroup.set_column('B:B', 40)
# worksheet_paygroup.write(text_format) $this returns error
worksheet_paygroup.set_column('C:C', 19, money_format)
worksheet_paygroup.set_column('D:D', 16)
worksheet_paygroup.write_formula('E1', '=SUM(C2:C743)')
worksheet_paygroup.set_column('E:E', 20, money_format)


writer.save()
writer.close()

output in second script should show the dollar value not nan.

With the new sheet it shows: nan np.isnan = True

the old file: 2265.50 (the correct amount) np.isnan = False

<tr>
                            <th>Pay Cycle</th>
                            <th>Description</th>
                            <th>Pay Cycle Amount</th>
                            <th>Daily Total</th>
                        </tr>
                        <tr>
                            <td>paygroup</td>
                            <td>Description</td>
                            **<td>$nan</td>**
                            <td> </td>
                        </tr>

Listing unique values formula taking a long time to process

$
0
0

I have a formula from a previous question that's working fine. It lists the unique values of dynamic column A to column B, starting from B2. Often Column A has several thousand values, then the processing takes a long time. Increasing calculation threads hasn't saved much time. I'm looking for a better method or formula that could save me a lot of time.

=IFERROR(INDEX(A:A;AGGREGATE(15;6;ROW($A$2:INDEX(A:A;MATCH("zzz";A:A)))/(COUNTIF($B$1:B1;$A$2:INDEX(A:A;MATCH("zzz";A:A)))=0);1));"")

enter image description here


Find 2nd Largest Value Based on Another Column

$
0
0

I have a list of emails. There can be duplicates or more of the same email. There is another column with dates. I'm wondering if there is a way to create another column indicating which is the 2nd largest date.

Email             Date               Second Date?
abc@gmail.com     April 2, 2019      No
abc@gmail.com     April 15, 2019     Yes
abc@gmail.com     April 15, 2019     Yes
abc@gmail.com     April 28, 2019     No

I'm thinking there might be a way to use the LARGE function, but can't determine how I would look for only the email in that row. Is there a way to combine this function with the SEARCH function?

How to write dataframe below an existing Excel sheet without losing value of pivot table and ignoring index value of dataframe?

$
0
0

I am using openpyxl module to append pandas dataframe below an existing excel sheet. But problem is my pivot table is getting destroyed while doing this task. I have tried many ways to find the solution of it, but I think there is no way available with openpyxl to avoid this situation.

I am using following method to achieve it with openpyxl-

#HELPER FUNCTION TO APPEND DATAFRAME BELOW EXCEL FILE
def append_df_to_excel(filename, df, sheet_name='Sheet1', startrow=None,
                       truncate_sheet=False,
                       **to_excel_kwargs):
    """
    Append a DataFrame [df] to existing Excel file [filename]
    into [sheet_name] Sheet.
    If [filename] doesn't exist, then this function will create it.

    Parameters:
      filename : File path or existing ExcelWriter
                 (Example: '/path/to/file.xlsx')
      df : dataframe to save to workbook
      sheet_name : Name of sheet which will contain DataFrame.
                   (default: 'Sheet1')
      startrow : upper left cell row to dump data frame.
                 Per default (startrow=None) calculate the last row
                 in the existing DF and write to the next row...
      truncate_sheet : truncate (remove and recreate) [sheet_name]
                       before writing DataFrame to Excel file
      to_excel_kwargs : arguments which will be passed to `DataFrame.to_excel()`
                        [can be dictionary]

    Returns: None
    """
    from openpyxl import load_workbook

    import pandas as pd

    # ignore [engine] parameter if it was passed
    if 'engine' in to_excel_kwargs:
        to_excel_kwargs.pop('engine')

    writer = pd.ExcelWriter(filename, engine='openpyxl', index=False)

    # Python 2.x: define [FileNotFoundError] exception if it doesn't exist
    try:
        FileNotFoundError
    except NameError:
        FileNotFoundError = IOError


    try:
        # try to open an existing workbook
        writer.book = load_workbook(filename,data_only=True)

        # get the last row in the existing Excel sheet
        # if it was not specified explicitly
        if startrow is None and sheet_name in writer.book.sheetnames:
            startrow = writer.book[sheet_name].max_row

        # truncate sheet
        if truncate_sheet and sheet_name in writer.book.sheetnames:
            # index of [sheet_name] sheet
            idx = writer.book.sheetnames.index(sheet_name)
            # remove [sheet_name]
            writer.book.remove(writer.book.worksheets[idx])
            # create an empty sheet [sheet_name] using old index
            writer.book.create_sheet(sheet_name, idx)

        # copy existing sheets
        writer.sheets = {ws.title:ws for ws in writer.book.worksheets}
    except FileNotFoundError:
        # file does not exist yet, we will create it
        pass

    if startrow is None:
        startrow = 1

    # write out the new sheet
    df.to_excel(writer, sheet_name, startrow=startrow, **to_excel_kwargs)

    # save the workbook
    writer.save()

I have seen that xlwings and win32com is available to do it, but not sure how to do it with these libraries. I want to ask how to append dataframe below existing excel file without losing the pivot table and data? The way by which we can do it without using openpyxl because I think there is no way available with openpyxl.

Tableau is adding numbers that appear more than once. How can i fix this?

$
0
0

I am working with a data set that has numbers that appear more than once and Tableau is automatically adding them together. For exanple, the numbers 45 and 50 appears twice in my data set so when i try making a bar graph(or any other graph for that matter) it is automatically addind them together. How can i fix this?

Texbox to setup google chrome path?

$
0
0

I have a commandbutton, when clicked, it opens google. Here is the code I am using.

    Private Sub CommandButton1_Click()
    Dim chromePath As String
    chromePath = """C:\Program Files\Google\Chrome\Application\chrome.exe"""
      Shell (chromePath & " -url https://google.com"), vbNormalFocus
      Unload Me
    End Sub

This workbook is shared with other people however it doesn't work on their PC as some of them have a different chrome path and also no idea how to go to the VB editor to make the necessary changes.

My question: Would it be possible to enter the chromepath in a textbox in a userform which then makes the changes in VBE without going to VBE?

Simple Visual basic If for images

$
0
0

I think it's too easy, but I'm just new in visual basic and I'm having problems solving this.

If a1 => 1 then in b1 show green.jpg

If a1 = 0 then in b1 show red.jpg

Image.FromFile, LoadPicture? How do I reference it in cell b1?

using a variable in an R1C1 formula

$
0
0

This formula works: ActiveCell.FormulaR1C1 = "=SUM(R[-14]C:R[-1]C)" it returns =sum(c1:c14)

This formula does not work: ActiveCell.FormulaR1C1 = "=SUM(R[-"& nrows & "]C:R[-1]C)" It returns =SUM(C14:C1048576)

I have this statement

Dim nrows as Integer

why does the formula with the nrows variable not work

VBA Searching and extracting specifc line from mulitple files in folder

$
0
0

so i have this code right here that loops through a folder and the files inside, it is able to extract specified ranges e.g A18, however not all of the information i want to extract is in fixed position, how do i locate and search for string inside the file and then extract it out to my formatted table? also it occurs 2 to 3 times inside a file, and i only want to extract it once.

Option Explicit

Sub ScanFiles()

    Application.ScreenUpdating = False

    Dim wks As Worksheet
    Set wks = Worksheets.Add

    ' New worksheet for question 2
    Dim wksFSO As Worksheet

    ' Add headers data
    With wks
        .Range("A1:J1") = Array("TestP", "Temp", "Start", "Type", "FileName", "Smart")
    End With

    ' Set your copy ranges
    Dim CopyRange(1 To 4) As String
    CopyRange(1) = "A18"
    CopyRange(2) = "A14"
    CopyRange(3) = "A19"
    CopyRange(4) = "A19"' Early Binding - Add "Microsoft Scripting Runtime" Reference
    Dim FSO As New Scripting.FileSystemObject

    ' Set FolderPath
    Dim FolderPath As String
    FolderPath = "c:\Users\Desktop\Tryout\"' Set Folder FSO
    Dim Folder As Scripting.Folder
    Set Folder = FSO.GetFolder(FolderPath)

    ' Loop thru each file -> Assuming only 6 files
    Dim File As Scripting.File
    For Each File In Folder.Files

        Dim wkbData As Workbook
        Set wkbData = Workbooks.Open(File.Path)

        Dim wksData As Worksheet
        ActiveSheet.Name = "Control"
        Set wksData = wkbData.Worksheets("Control") ' -> Assume this file has only 1 worksheet

        Dim BlankRow As Long
        BlankRow = wks.Range("A"& wks.Rows.Count).End(xlUp).Row + 1

        Dim i As Long
        For i = 1 To 4
            wks.Cells(BlankRow, i).Value = wksData.Range(CopyRange(i)).Value
        Next i

        ' Write filename in col E
        wks.Cells(BlankRow, 5).Value = File.Name

        wkbData.Close False

    Next File

    Range("A:J").EntireColumn.AutoFit
    Application.ScreenUpdating = True

End Sub

Really appreciate any help regarding this issue, even a small part of a code is very appreciated.


Is there any way of putting filter in excel using xlwings in Python?

$
0
0

I am working on an Excel which has some items in column A and their cost in column B. Out of this extensive list of items and their cost, i want to copy only some of the items with cost in new excel. For identifying the items, I am using column C and putting a value 'a' against the items which i need to copy. Is there any way how can i put a filter in column number 'c' using xlwings?

How to set cell format always in negative in specific column?

$
0
0

enter image description here

I would like to make a simple tracking sheet for onhand stock Qty. Column F is the actual stock Qty will sum up all row cell value. the column incl. "export" (e.g. column H & J.) should be a negative value.

I have tried the following code.

Private Sub Worksheet_Change(ByVal Target As Range)

Dim isect As Range
Set isect = Application.Intersect(Target, Range("I:I"))
If Not (isect Is Nothing) Then
    If Target.Value > 0 Then Target.Value = 0 - Target.Value
End If

End Sub

it will turn the column "I" to negative automatically. However, I will add more batches in the future. Is any way automatically turn negative if the column contains "export"?

how to count number of sheet excel in node js

$
0
0

I have an excel file, how can I count total of sheets in that file use node js ?

I use the xlsx library, but in the documentation I did not find to see the total sheets in the file excel

VBA split filename into different rows

$
0
0

i have this string right here in Col E or my worksheet, may i know how i can extract "01" and "201912032345000" out into Row F and Row G respectively?

For "2019120324500", i hope to add a space in between as well, resulting in "20191203 234500"

The numbers will be the only variable that is always changing, the characters,delimeter,words will never change, only sometimes comes with file extension. I need it in Vba coding , thank you so much!!

E.g 1

hometeastrash_beehivetester01trash_tepotts20191203234500tepotsFile

E.g 2

hometeastrash_beehivetester01trash_tepotts20191203234500tepotsFile.txt

Below shows the picture of what should be the final result.

FinalResult

Password Protection for Exported Data from Google Sheet

$
0
0

I saved my data Google Sheet, I can limit access to this data with Sharing feature available at all Google Docs (Sheet). Is there any solution for me to protect exported document from Google Docs (and Sheet)?.

What I can think of right now, password protection on file level as we can found at Microsoft Excel file. I am okay if I need to do some coding in Google Script found at GSuite.

Viewing all 88257 articles
Browse latest View live


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