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

VBA to set Range/ Print area in consolidating the Master Sheet

$
0
0

I have this VBA code which is used to consolidate the different tabs to one single sheet.Now the issue here is its taking too long to copy each line item to one single sheet. Need an update so that i could set print area as range and copy the sheets back to one.

 ActiveWorkbook.Worksheets("Master Sheet").Activate
    Rows("2:"& Rows.Count).Cells.ClearContents

    totalsheets = Worksheets.Count
    For i = 1 To totalsheets

    If Worksheets(i).Name <> "Master Sheet"  Then
    lastrow = Worksheets(i).Cells(Rows.Count, 1).End(xlUp).Row


            For j = 2 To lastrow

            Worksheets(i).Activate
            Worksheets(i).AutoFilterMode = False
            Worksheets(i).Rows(j).Select
            Selection.Copy
            Worksheets("Master Sheet").Activate                               

            lastrow = Worksheets("Master Sheet").Cells(Rows.Count, 1).End(xlUp).Row

            Worksheets("Master Sheet").Cells(lastrow + 1, 1).Select
            ActiveSheet.Paste
            Application.CutCopyMode = False

            Next
            End If
            Next
            MsgBox "Completed"
            ActiveWorkbook.Save
End Sub

Cell Formulas Won't Read Unless I Hit Enter

$
0
0

I have a WB with multiple sheets, most sheets have a data-validation dropdown list in cell A4 (for whatever reason there are a couple that are just text). What I’m trying to do seemed relatively easy, whatever sheet I am on, when I select a value from the dropdown list, it will update that value on all of the sheets (except for the 2 I excepted). So if I select “Tom” from sheet 3, and then go to sheet 5 “Tom” will also be selected there.

Using my clunky code, I have managed to get this to (kinda) work. The problem is that the cell formulas that reference this (vlookups mostly) do not read it. I have to go to cell A4 and click into the formula bar, and hit enter. Then the formulas will read it. I have been trolling message boards looking for solutions, but I’ve run out of ideas.

I’ve already:

-made sure autocalculation is on, made sure it isn’t text, made sure it isn’t circular

-made sure EnableCalculation is true (and also did true, then false, then true again), as well as application.calculate and tried various refreshes.

-I did the find a replace “=” of the formulas

I suspect that because the value is based on a variable (active-cell value), it’s got some kind of circular reference problem. In this latest version I tried to mitigate this by declaring it a variable and a string (too be honest, I’m grasping at straws), and before that I tried taking the active cell value, then copying and paste-special as just value. I am very, very new to VBA so I am probably missing something dumb. I would really appreciate any suggestions regarding what I’m missing, because I have really hit a wall regarding things I’ve seen on this and other forums.

My current code is follows:

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)


 If Not Intersect(Target, Range("A4")) Is Nothing Then

 Call SetDropdown

 End If

End Sub

Sub SetDropdown()

    Dim ws As Worksheet
    Dim acv As String

    Application.ScreenUpdating = False
    Application.EnableEvents = False

    acv = ActiveCell.Value
    For Each ws In ThisWorkbook.Sheets
    If ws.Name <> ThisWorkbook.ActiveSheet.Name And ws.Name <> "TEAM LIST" Then

    ws.Range("A4") = acv

    End If
   Next ws

    Application.EnableEvents = True
    Application.ScreenUpdating = True


End Sub

Thank you in advance to anyone who can help point me in the right direction.

Set series collection as range

$
0
0

I have a chart with a collection series. I would like to extend the range of the collection series by one column to the right. The code below works. However, it assumes that I know the range of the collection series ("B36:DA36" in the example below). In fact, I would like the initial range of the collection series (before resizing) to be defined in a dynamic way as it changes every day and defining it as below would not do the job.

Sub resize_collection_series()

Dim NumRows As Long
Dim NumCols As Long
Dim Rng As Range

Set Rng = Range("B36:DA36")

NumRows = Rng.Rows.Count
NumCols = Rng.Columns.Count

Worksheets("Sheet1").Activate
ActiveSheet.ChartObjects("Chart 6").Activate
ActiveChart.SeriesCollection(1).Select
ActiveChart.SeriesCollection(1).Values = Rng.Resize(, NumCols + 1)
ActiveChart.SeriesCollection(1).XValues = Rng.Resize(, NumCols + 1)
End Sub

I tried something like this withouth success:

Set Rng = Worksheets("Sheet1").ChartObjects("Chart 6").SeriesCollection(1)
Set Rng = Worksheets("Sheet1").ChartObjects("Chart 6").SeriesCollection(1).Values

Win32com Module Problems

$
0
0

I want to convert .xls to .xlsx, so I use win32com module

this is my code:

    import os
    import win32com.client as win32
    address = address = os.getcwd()

    fname = address + "\\Bundles.xls"
    fname2 = address + "\\searchresults.xls"
    excel = win32.gencache.EnsureDispatch('Excel.Application')
    excel2 = win32.gencache.EnsureDispatch('Excel.Application')
    wb = excel.Workbooks.Open(fname)
    wb5 = excel.Workbooks.Open(fname2)

    wb.SaveAs(fname+"x", FileFormat = 51)
    wb5.SaveAs(fname2+"x", FileFormat = 51)    #FileFormat = 51 is for .xlsx extension
    wb.Close()
    wb5.Close()                               #FileFormat = 56 is for .xls extension
    excel.Application.Quit()
    excel2.Application.Quit()
    print('File .xls convert .xlsx successful!!')

then I got the error,here it is the traceback:

Traceback (most recent call last): File "c:/Users/shenshuaic/Desktop/SFP Program/win32test.py", line 7, in excel = win32.gencache.EnsureDispatch('Excel.Application') File "C:\Users\shenshuaic\AppData\Roaming\Python\Python37\site-packages\win32com\client\gencache.py", line 527, in EnsureDispatch disp = win32com.client.Dispatch(prog_id) File "C:\Users\shenshuaic\AppData\Roaming\Python\Python37\site-packages\win32com\client__init__.py", line 96, in Dispatch return WrapDispatch(dispatch, userName, resultCLSID, typeinfo, clsctx=clsctx) File "C:\Users\shenshuaic\AppData\Roaming\Python\Python37\site-packages\win32com\client__init.py", line 37, in __WrapDispatch klass = gencache.GetClassForCLSID(resultCLSID) File "C:\Users\shenshuaic\AppData\Roaming\Python\Python37\site-packages\win32com\client\gencache.py", line 183, in GetClassForCLSID mod = GetModuleForCLSID(clsid) File "C:\Users\shenshuaic\AppData\Roaming\Python\Python37\site-packages\win32com\client\gencache.py", line 226, in GetModuleForCLSID mod = GetModuleForTypelib(typelibCLSID, lcid, major, minor) File "C:\Users\shenshuaic\AppData\Roaming\Python\Python37\site-packages\win32com\client\gencache.py", line 266, in GetModuleForTypelib AddModuleToCache(typelibCLSID, lcid, major, minor) File "C:\Users\shenshuaic\AppData\Roaming\Python\Python37\site-packages\win32com\client\gencache.py", line 552, in AddModuleToCache dict = mod.CLSIDToClassMap AttributeError: module 'win32com.gen_py.00020813-0000-0000-C000-000000000046x0x1x9' has no attribute 'CLSIDToClassMap'

Want to hyperlink to a certain cell

$
0
0

I am trying to build a dynamic hyperlink. My data validation has numbers 1 - 222. The row is 8, this does not change.

When the user selects 57 from the drop down I want a link that takes them to Row 8 Column 57.

Any ideas on how to build this?

How to Filter a range of Cells having a particular value [closed]

$
0
0

I need to filter and show only the range of cells having MAX value to all values between (MAX-15) values in a column.

For example, if I there is a column having Nos to 1 to 100, I want to filter the cells from 100 to 85. Kindly help.

Is there an easy way to set one cell's specially formatted contents equal to another's?

$
0
0

I would like to fill individual cells with "rich" text. By this I mean that the cells contain several newlines, bullet points, and individual words varying in font, color, size, italic, etc.

I would like the on SelectionChange event to set one cell's contents equal to everything that the target cell contains (colors, fonts, etc.). Setting "Range("A1").Value = Target.Value" or "Range("A1").Value = "="& Target.Address" doesn't work as none of the special cell formatting is added.

I have some ideas of a very complex way of achieving this by looping through each word, checking it's color, font, size, and adding that word with those attributes, but I want to believe there's a better way. Any help is greatly appreciated, thanks!

Excel - bar chart w series overlapp

$
0
0

Currently I have a grouped bar chart with a value on the y-axis (total guest nights in an area), and the months on the x-axis. I have 2 series as of now: 2020 and 2019 - they are quite close to each other for each months so that you see that these relate to one another.

NOW I wanted to break each of these series into a more detailed aggregate. The total guest nights each bar represent I now want the bar to aggregate the value for each market - whether domestic or abroad (so 2 components should now constitute the earlier total sum)

My idea doing this was (which I know work if I had just 1 year - e.g. 2019), is to put the e.g. abroad as the total amount and the domestic as domestic - then just use 100% series overlap. BUT if I do this now - of course this happens to both may series related to e.g. 2019 but also for 2020 (which I do not want). I tried making use of the scondary y-axis for the 2020 series - but that didn't help at all - Excel still relate series overlap (on the x-axis) the same regardless of me making use of the 2nd-y-axis.

Do you understand my question? I essence I want a stacked bar chart for 2 series (or in practicality 4).


How to send text to some HTML elements?

$
0
0

I have been having trouble on referring to a search box on a website through Selenium in VBA. The HTML code of the box is:

<input type = "search" class ="form-control input-sm"
placeholder aria-controls="result_table"> ==$0

I have tried

bot.findElementByCssSelector(".form-control").SendKeys ("werresf")
bot.findElementByCssSelector(".form-control.input-sm").SendKeys ("werresf")
bot.findElementByCssSelector(".input-sm").SendKeys ("werresf")
bot.findElementByCssSelector(".form-control input-sm").SendKeys ("werresf")
bot.findElementByClassName("form-control input-sm").SendKeys ("werresf")

But none of them seems to work. Any help is greatly appreciated.

Create a Yes No list only if a cell is not empty in google excel sheets [closed]

$
0
0

I want my Yes/No list to show up in column C only if there is text in column A.

In the attached image i don't want C6 to show the drop down list. Is it possible to achieve this in Google Sheets.

Below is the attached image

Example Image for the excel sheet

Hoping someone can help me with this.

Regards

I have defined a number of variables and ranges inside a Sub, but the modules that it references do not use them [closed]

$
0
0

Like the title says. I have decided it would be easier to follow and diagnose issues with some code I am working on if I were to have a number of modules to split the code up so it would be easier follow.

When I call a Sub within the module why is it not using the predefined variables and ranges from the Sub to which it has been called? Do I need to redefine all of the variables in every module? Should I just combine all the modules into one longer code block? Do I just need to put "Call" in front of the Sub name in order for it to work, as I think I saw in an older thread?

I know this is a pretty general knowledge type of question so I apologize if it is super easy to find the answer, but I'm having a hard time finding the answer.

I am trying to create a crossword generator algorithm/code. The specifications are stated in the description [closed]

$
0
0

Here are some specifications. This software/ program should automatically generate a crossword like the one in New York Times (the grid one and not the random octopus one).

This should preferably be generated in MS Excel/spreadsheets. The reason is as follows.

This will be given to a librarian of a local community in Melbourne who sends weekly quizzes to his clients in the form of crosswords to keep them in touch with the cultural values.

Since there are multiple clients, I want to use excel/google spreadsheets in order allow them to complete the same crossword generated. Each client will have one sheet and will be given a username and password in order to access that sheet.

After filling the crossword in a day (the clients are given 24 hours to complete the task), the librarian should be able to evaluate the same. Most importantly, the crossword should be generated in a local Indian language (Hindi/Tamil/Telugu).

I have tried generating crosswords using the crossword puzzle generator tools like puzzle-maker.com, crosswordlabs.com, puzzlemaker.discoveryeducation.com etc. For starters, I am also trying to integrate the crossword generated by these tools in my website for the project.

Excel copy(Destination:=) failed in VB.NET

$
0
0

I'm using copy(Destination:=) and would like to copy whole records in one excel to another excel file but failed to execute. Could it because of need to use range? Because there is not necessary to use range as i would like to copy all and paste into another excel file

oWorkBook.Sheets(1).Cells.Copy(Destination:=oWorkBookOri.Sheets(1).Range("A"& oWorkBookOri.Sheets(1).UsedRange.SpecialCells(XlCellType.xlCellTypeLastCell).Row + 1))

It mentioned error as below.

"Copy method of Range class failed".

My Previous code are as below

oWorkBook.Sheets(1).Cells.Copy()
oWorkBookOri.Sheets(1).Range("A"& oWorkBookOri.Sheets(1).UsedRange.SpecialCells(XlCellType.xlCellTypeLastCell).Row + 1).Select()
oWorkBookOri.Sheets(1).Paste

and it keep occur error message "System.Runtime.InteropServices.COMException (0x800A03EC): Paste method of Worksheet class failed" and despite on this, i changed to copy destination syntax and occur error as mentioned above.

Check if datetime is between two datetimes

$
0
0

Hi i am trying to create a macro with vba An example would be

DATETIMEA  is  "20/11/2018 11:00:00 AM"

DATETIMEB is "20/11/2018 08:00:00 AM"

DATETIME  is "21/11/2018 07:59:00 AM"

I would like to check if the datetimeA falls between datetimeb and datetimec the code below doesn't work.

The values are stored in Date variables.

If datetimeb >=  datetime And datetimea  <= datetimec

How to select just the year for dates older than 1900? [closed]

$
0
0

I need a function in Excel that can extract just the year from dates like 27.02.1872. I have read that YEAR only works from 1900 to 9999.


Subtracting a comma separated string from another [closed]

$
0
0

If I have A1= 1,2,3,4,5,6,7,8,9

A2=2,6,9

My desired result should be in cell A3 After substation (A1-A2) =1,3,4,5,7,8

while it was very easy when A2=2,3,4 (serially) via substitute function.

Need to transpose the vertical data to horizontal format, but few cells in Vertical format can have more than 2 or 3 sub categories in Excel VBA

$
0
0

Before

Before image

After

After image

i wrote the code, but the next items is starting from just below the 1st used cell. i need it to start where the first entered item list ends.

Sub transposevbaaaa()

Sheets("Sheet1").Range("B1:B90").Copy



With Sheets("sheet2")
    .Cells(.Rows.Count, 1).End(xlUp).Offset(1).PasteSpecial Transpose:=True

End With

End Sub

Excel VBA: Copy, Paste and delete row from one worksheet to another

$
0
0

please can someone help me?? I have been trying lots of different codes for weeks and it seems as though I am getting no where as I don't know what I am doing.

I have 5 worksheets. From worksheet1 I would like entire rows to be copied to worksheet5 if column G says "Discharged" I would like the row that is copied from worksheet 1 to be deleted after it is copied If possible can the new copied row in worksheet5 go to the next available blank row

This is the same for all worksheets 1-4, eventually data rows will end up on worksheet5 when column G states "Discharged"

I had a working code which worked well but as soon as I had it applied to all 4 worksheets it would intermittently freeze, is this just because I have too many macros applied?

Any suggestions would be greatly appreciated :)

How to calculate rolling 3 day volatility of returns data using Exponential Weighted Moving Average? [closed]

$
0
0

I have a dataset that consists of the closing price and date for 10 years. I want to calculate the rolling 3-day volatility of returns data using Exponential Weighted Moving Average. Please mention how to approach this problem and if possible give the solution in excel. The data look like this:

    Date        ClosingPrice  Logreturns     Squaredlogretuns  Weights   
   1-01-2000    50              -                 -               -
   2-01-2000    51            0.008600172     7.3963E-05        0.28    
   3-01-2000    52            0.008433168     7.11183E-05       0.2016  
   4-01-2000    52.5          0.00415596      1.7272E-05        0.145152    
   5-01-2000    53            0.004116566     1.69461E-05       0.10450944  
   6-01-2000    59            0.046576142     0.002169337       0.075246797 


Weights * Squaredlog returns      Volatility

2.07096E-05                              -
1.43375E-05                              -
2.50707E-06                               -
1.77103E-06                        0.006270979
0.000163236                        0.013485222

In the above table, I took lambda (weights) =0.72 and used a formula to decrease the weights exponentially. Finally, I multiplied the weights with squared log returns.

I added up all the rows of weightssquaredlogreturn to calculate the overall variance of the EWMA for this data but how to do it for a rolling 3 day period. Above I added up the last 3 rows of (weightsquaredlogreturns) column for each day to get the variance and took a square root of it to get the Standard Deviation or Volatility of rolling 3-day period.

Run Time Error '1004': Select method of Range Class failed VBA 2003

$
0
0

I am trying to copy a column from one sheet to another. The code I am using is a recorded macro and it works fine until I connect it to a button. When I do so, it gives a "Run Time Error '1004': Select method of Range Class failed"

Here is the code and I can see nothing wrong with it. When I hit debug it highlights the second line.

Sheets("Count").Select
Columns("C:C").Select
Selection.Copy
Sheets("Add Invintory").Select
Range("b1").Select
ActiveSheet.Paste
Sheets("Count").Select
Sheets("Count").Columns("A:A").Select
Columns("A:A").Select
Selection.Copy
Sheets("Add Invintory").Select
Range("A1").Select
ActiveSheet.Paste

I have no clue what the problem is. Please help

Viewing all 88150 articles
Browse latest View live


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