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

Deleting rows breaks formulas

$
0
0

I am certain that in the past I didn't have this "problem." Let's say I have 3 columns: A, B, and C. I have a lot of rows of numbers for these columns. Columns A and B have numerical data manually entered in their cells. Each cell in column C is a SUM of the cell to the left and the cell above. For example, C15 would have "=SUM(B15,C14)".

What I EXPECT is that when I right-click a row and delete it, such as 15, that the data from rows 16 and beyond would shift up and the "new" C15 cell would maintain the formula of "=SUM(B15,C14)". However, instead, all C cells 15 and below break. C15 looks like this: "=SUM(B15,#REF!)".

Maybe I am losing my mind, but I would bet a year's pay that in the past, deleting a row that had a formula above and below it would not break all formulas below the row I deleted.

I didn't use OFFSET or anything like that. I just remember Excel being smart. I've looked all around the interwebs, including SO, and all the answers to similar questions seem to imply I'm losing my mind.

If someone can help out, that'd be awesome.Thanks for your time.


Find top row and left most column of table

$
0
0

I have several tables, how can I find the left-most column range and top-most row range (not including header)?

Example, table1 occupies A55:E65, how can I return (in separate cells):

  1. A55:E55 (top row)
  2. A55:A65 (left most column)

I can convert it to an address with

=ADDRESS(ROW(table1),COLUMN(table1))&":"&ADDRESS(ROW(table1)+ROWS(table1)-1,COLUMN(table1)+COLUMNS(table1)-1)

Will show up as $A$55:$E$65

Trying to lookup a specific date from the table out of multiple columns:enter image description here

I need to lookup a date (there are no repeats, thankfully) then return the value in a specific column in the table. It has to be from the named table, as there are multiple tables stacked on top of one another with repeat dates.

Unsure of where to go from there, thank you.

Splitbook but with the option to save the nw files worksheet with custom name

$
0
0

i have in one folder a MASTER file where i have one file with multiple sheets inside.

i am using the below code for the split book,

the macro generate multiple files in the same folder of MASTER file with the name of the sheets of the MASTER file.

I have an issue, when i open the generate files they have all the sheet name as file name...

how can i have same result but for all the new generated files the sheet name as for example Sheet1?

here the code i use for splitbook:

Sub Splitbook()Dim myxWs As WorksheetDim myPath As StringSet myxWs = ThisWorkbook.Sheets(1)myPath = Application.ActiveWorkbook.PathApplication.ScreenUpdating = FalseApplication.DisplayAlerts = FalseFor Each myxWs In ThisWorkbook.Sheets    myxWs.Copy    Application.ActiveWorkbook.SaveAs Filename:=myPath & "\"& myxWs.Name & ".xlsx"    Application.ActiveWorkbook.Close FalseNextApplication.DisplayAlerts = TrueApplication.ScreenUpdating = TrueEnd Sub

Convert VBA Macro to Google Sheet to auto save file in Google Drive [closed]

$
0
0

I need a way to translate a VBA Excel macro to Google sheets. It is basically save a copy of my invoice in "Billing" tab of excel to my computer. Now I want same things for Google sheet that will automatically save a copy of my invoice in Google drive.
Here is the code that I used in Microsoft VBA for my excel sheet.

Sub saveinvoice()    Billing.Range("a1:j40").ExportAsFixedFormat xlTypePDF, _        Filename:="D:\Billing Informations\Invoices\"& Billing.Range("c6").Value, _        openafterpublish:=trueEnd Sub

Excel - How to find location (i.e. what columns) of specific PivotFields in a PivotTable?

$
0
0

I am building a routine that automates creating a PivotTable. All is working well...I add my rows, columns, filters and values. As a last step, I want to format the values. I cannot find any property that shows me what "value entry/pivotfield" ends up in which column. Lets assume that I have 2 Value PivotFields...

Pivot1 := fmyPivotTable.AddDataField( 'Revenue', 'Revenue', xlSum );Pivot2 := fmyPivotTable.AddDataField( 'Locations', 'Locations', xlCount );

I am looking for something that will tell me that Pivot1 data is in columns C, E and G while Pivot2 data is in D,F and H. The closest I could find is labelrange and position, but neither of these is really what I need. I am writing this in Delphi, but if someone knows how to do this in VBA, I can convert.

Adding macro to Add-ins tab Custom Toolbars?

$
0
0

I just finished a VBA project, and now I want to add a button for it in the Add-ins tab. I inherited an existing toolbar, so I'll need to incorporate my button into it; here's what it looks like now. I have the .xlam file for the existing macros in the Toolbar.

In my project, I added a module that calls all of the macros I want to run in the button. I'm not sure if this is a necessary step, but here's what I've done. I also downloaded my macros as a .xlam file and .bas files.

I've found plenty of resources for adding a macro button to the Quick Access Toolbar and Developer tab, but that's not what I need to achieve. Any hints or links on how to add the macro to the Add-ins tab?

Here is the CommandBar and msoControl code:

Sub MyCB()    On Error Resume Next    Application.CommandBars(sCB).Delete    On Error GoTo 0    With Application.CommandBars.Add(sCB, , False, True)        With .Controls.Add(msoControlButton)            .Tag = "Compound"            .Caption = "Compound Summary"            .TooltipText = "Create Compound Summary"            .OnAction = "CreateSummaryReport"            .Style = msoButtonCaption       End With       With .Controls.Add(msoControlButton)            .Tag = "HPLC Stability Timetable"            .Caption = "HPLC Stability Timetable"            .TooltipText = "Create HPLC Stability Timetable"            .OnAction = "STBLIncubationTime"            .Style = msoButtonCaption       End With       With .Controls.Add(msoControlButton)            .Tag = "Well Sorting"            .Caption = "Well Sorting"            .TooltipText = "Sort Data Submissions"            .OnAction = "WellSorter"            .Style = msoButtonCaption       End With       With .Controls.Add(msoControlButton)            .Tag = "CLND Data Preparation"            .Caption = "CLND Data Preparation"            .TooltipText = "Formats and copies CLND data for transfer to YTD"            .OnAction = "CLNDdecider"            .Style = msoButtonCaption       End With       With .Controls.Add(msoControlButton)            .Tag = "Grav. Caff. YTD Dump"            .Caption = "Grav. Caff. YTD Dump"            .TooltipText = "Dumps grav. caff. data into YTD"            .OnAction = "gravcafffinder"            .Style = msoButtonCaption       End With       With .Controls.Add(msoControlButton)            .Tag = "Array Assay Platemap to CSV"            .Caption = "Array Assay Platemap to CSV"            .TooltipText = "Converts Array assay platemaps to CSVs"            .OnAction = "AssayPlatemapToCSV"            .Style = msoButtonCaption       End With       With .Controls.Add(msoControlButton)            .Tag = "Array Submission Setup"            .Caption = "Array Submission Setup"            .TooltipText = "Performs initial setup for Array submission file"            .OnAction = "ArraySubmissionWorksheet"            .Style = msoButtonCaption       End With       With .Controls.Add(msoControlButton)            .Tag = "Array Cal. Platemap to CSV"            .Caption = "Array Cal. Platemap to CSV"            .TooltipText = "Converts Array calibration platemaps to CSVs"            .OnAction = "CalPlatemapToCSV"            .Style = msoButtonCaption       End With       With .Controls.Add(msoControlButton)            .Tag = "ElogD Report Formatting"            .Caption = "ElogD Report Formatting"            .TooltipText = "Formats ElogD Table for Reporting"            .OnAction = "ElogDreportformat"            .Style = msoButtonCaption       End With        .Protection = msoBarNoCustomize        .Position = msoBarTop        .RowIndex = msoBarRowLast        .Visible = True    End WithEnd Sub

Excel line break vs VBA line break?

$
0
0

I'm writing VBA codes to read spreadsheet contents and write to a TXT file.

Some of the cells has multi-line text. They are displayed as multi-line in the spreadsheet.

However, when the VBA code read the cell and write to the TXT file, they appear on the same line. This also happens when I copy the cell and past it into Notepad.

For example in spreadsheet, cell A1 appears as:

Text1Text2Text3

But in TXT file, it appears as: Text1Text2Text3.

So I guess CHAR(10) in Excel is not equivalent to vbNewLine in VBA? What do I need to do to get the line breaks into TXT file? Thank you!

Excel VBA Sendkeys stops/pauses on the 2nd loop

$
0
0

Screenshot

I am filling the webform. and it requires a keyboard press. so I use sendkeys to hit tab. It works perfectly fine for the 1st time but when it loops 2nd time it stops/pauses at Application.SendKeys "{TAB}", True . I have to click inside VBA then it resumes again.

Thank you.

For i = 2 To 3

IE.getElementsByName("recipientName")(0).Value = ActiveSheet.Range("A"& i)   AppActivate ("Internet Explorer"), True        Application.Wait (Now + TimeValue("00:00:03"))    For tabbtn = 1 To 20        Application.SendKeys "{TAB}", True        Application.Wait (Now + TimeValue("00:00:01"))     Next TabbtbNext iEnd Sub

Close all open pdf's (Foxit PhantomPDF) using VBA

$
0
0

I am currently running an auto pdf creator that opens pdf's, inputs data, and prints them to a new pdf then closes the original pdf. The issue I'm running into is that some of the pdf's it creates are corrupt (and its always different which one) so this brings me to believe there is not enough time between saving and closing for the pdf to fully save. My new thought is to close all of the pdf's in the end (which could be around 10 different pdf's).

My code below is how I open the pdf's (using Foxit PhantomPDF). And close them. Does anyone know how I could close all open pdfs?

PDFTemplateFile1 = Sheet4.Range("BU3").Value   PDFTemplateFile2 = Sheet4.Range("BU4").Value   PDFTemplateFile3 = Sheet4.Range("BU5").Value   PDFTemplateFile4 = Sheet4.Range("BU6").Value   PDFTemplateFile5 = Sheet4.Range("BU7").Value  ' In the cell it looks likePDFTemplateFile6 = Sheet4.Range("BU8").Value    ' S:\SavedPDFs\Dogpic.pdfPDFTemplateFile7 = Sheet4.Range("BU9").ValuePDFTemplateFile8 = Sheet4.Range("BU10").Value...If Sheet2.Range("A1") = Dog    ThisWorkbook.FollowHyperlink PDFTemplateFile1...    Application.Wait Now + 0.00005    Application.SendKeys "^(q)", True    Application.SendKeys "{numlock}%s", True            ' Closes the pdf    Application.SendKeys "{Tab}", True    Application.SendKeys "{Enter}", True    Application.Wait Now + 0.00001

I've tried increasing the wait time between the saving and closing but I think this would be a better solution. I've left out much of the unnecessary code but this is the general idea. This is looped for a set number of rows so that is where the other pdf's would be opened.

VBA: Issue adding data from cells to chart labels

$
0
0

I am trying to make a macro that refreshes chart labels from cells automatically instead of having to manually delete the labels and then re-add and re-link them. The following code runs without error but it doesn't place any labels on the chart at all. When I change ShowValue to True it does add the labels but only with the values, not the data from the cells. Any help would be appreciated.

Dim Cht As ChartDim sr As SeriesDim nCharts As LongSet Cht = ActiveSheet.ChartObjects("Chart 5").ChartActiveSheet.ChartObjects("Chart 5").ActivateActiveChart.FullSeriesCollection(2).DataLabels.SelectSelection.DeleteActiveSheet.ChartObjects("Chart 5").ActivateActiveChart.FullSeriesCollection(1).DataLabels.SelectSelection.DeleteActiveSheet.ChartObjects("Chart 5").ActivateActiveChart.FullSeriesCollection(3).DataLabels.SelectSelection.DeleteFor Each sr In Cht.SeriesCollection    sr.ApplyDataLabels    sr.DataLabels.Select    sr.DataLabels.Position = xlLabelPositionAbove    sr.DataLabels.Select    sr.DataLabels.Format.TextFrame2.TextRange. _        InsertChartField msoChartFieldRange, "=Calendar!$L$14:$L$75", 0    sr.DataLabels.ShowRange = True    sr.DataLabels.ShowValue = FalseWith sr.DataLabels.Font        .Size = 9End WithNext sr

VBA progress bar form

$
0
0

I know there are endless posts for this but as my math skills are -100 I am getting issues in calculating the correct percentage. Below I have the loop that runs and then the sub that attempt to calculate the percentage. The issue is that the width of the label is wrong and for recordset with tiny numbers as 2 all is crewed up :-)

LOOP CODE

'loop until the end of the recordset      Do While Not Glob_RecSet.EOF'inner loop to get each record fields         For FieldCount = 0 To Glob_RecSet.Fields.Count - 1            Glob_Sheet.Range(GLobWorkSheetRange).Offset(loopCounter, FieldCount).value = Glob_RecSet.Fields(FieldCount).value         Next'start progress bar calculations the form show and unload is called on the form code apply changes button            RunProgressBar loopCounter, TotalRows, "Runningquery for "& Glob_RecSetRunning'Next record         Glob_RecSet.MoveNext'advance counter         loopCounter = loopCounter + 1      Loop

SUB CODE FOR PROGRESS BAR

Public Sub RunProgressBar(loopCounter As Variant, TotalRecords As Variant, FormTitle As String)   Dim LblDonewidth As Variant   Dim ProgBarCaption As Variant   Dim ProgresPercentage As Variant   If (TotalRecords < 100) Then      TotalRecords = 100   End If   ProgresPercentage = Round(loopCounter / TotalRecords * 100, 0)'to avoid to give the progress bar a percentage greater than 100   If (ProgresPercentage > 100) Then      ProgresPercentage = 100   End If   ProgBarCaption = Round(ProgresPercentage, 0) & "%"   FrmProgBar.Caption = FormTitle   FrmProgBar.LblDone.Width = ProgresPercentage * 2   FrmProgBar.LblText.Caption = ProgBarCaption'The DoEvents statement is responsible for the form updating   DoEventsEnd Sub

Clear drop down cell content depend on another cell value change

$
0
0

want clear C1 cell value (Drop down cell) after I change A2 value to grater than 2.I have list box for A2 cell change.I followed below vba code.Need to modify it.

  Private Sub Worksheet_Change(ByVal Target As Range)    If Not Intersect(Target, Range("A2")) Is Nothing Then    If Me.Range("A2").Value > 2 Then        Range("C1").ClearContents    End IfEnd Sub

Image

How can I use VBScript to refresh data of several Excel in different path?

$
0
0

I have a code to refresh one report using VBScript and run the other batch file to run this refresh.

Below is my VBScript

Set objExcel = CreateObject("Excel.Application")On Error Resume NextobjExcel.Visible = FalseSet objWorkbook = objExcel.Workbooks.Open("C:\Users\Desktop\Test.xlsx")objWorkbook.RefreshAllobjExcel.DisplayAlerts = TrueobjWorkbook.SaveobjWorkbook.close FalseobjExcel.Quit

and below is my Batch Script

cscript refresh_excel.vbsdate /T Time /Tpause.

Now I need to refresh several Excel reports on different paths. The reports are all located in different paths; some of them are located in the shared folder, which I already test this combination can refresh file in share folder too.

The current solution I have is to create a speared VBScript for each file and run a multi .vbs file using my batch file.

Any more adequate and effective idea of doing this?

How to Create Excel Pivot Table to R

$
0
0

I want to create a pivot table from my data set in excel to R. I have been following this tutorial on how to do this: http://excel2r.com/pivot-tables-in-r-basic-pivot-table-columns-and-metrics/ . I have used the codes mentioned in this tutorial by replacing it with my own data variables, but I keep getting an error message noting: Error: select() doesn't handle lists.

What does this error message mean and how I can I fix this?

The R-Script I have been using from the tutorial is:

library(dplyr)library(tidyr)

pivot <- df %>%        select(Product.Category, Region, Customer.Segment, Sales)%>%        group_by(Product.Category, Region, Customer.Segment) %>%        summarise(TotalSales = sum(Sales))

Thank you in advance for the help!

runtime error 462 with internet explorer

$
0
0

I am trying to access a webpage from excel using VBA. I can get internet explorer to launch, and I see the webpage come up, but I get a runtime error 462 when I hit the Do Until internet.ReadyState >= 4 line of code. any ideas? ultimately I want to be able to parse a site and get a list of the links on that site and pick one, and then "click" on that link. suggestions and help would be great. here is the function (that I found on the web) that I am using:

Public Sub clicklick()Dim internet As ObjectDim internetdata As ObjectDim div_result As ObjectDim header_links As ObjectDim link As ObjectDim URL As StringSet internet = CreateObject("InternetExplorer.Application")internet.Visible = TrueURL = "https://www.google.co.in/search?q=how+to+program+in+vba"internet.Navigate URLDo Until internet.ReadyState >= 4    DoEventsLoopApplication.Wait Now + TimeSerial(0, 0, 5)Set internetdata = internet.DocumentSet div_result = internetdata.getelementbyid("res")Set header_links = div_result.getelementsbytagname("h3")For Each h In header_links    Set link = h.ChildNodes.Item(0)    Cells(Range("A"& Rows.count).End(xlUp).row + 1, 1) = link.hrefNextMsgBox "done"End Sub

thank you,alan


How to read two tables from single excel sheet using python?

Excel worksheet events won't fire on colleague's computer

$
0
0

I have a macro-enabled workbook that runs fine on my machine, but when my colleague tries to use it, the worksheet events won't fire.

I've done as much searching as I can and I'm still baffled.

The following conditions are true:

  • The events are named correctly (I didn't change the names) and are in the correct location (worksheet code) (as mentioned, everything works correctly on my machine, so these must be true)
  • Application.Events = True (I tested this in the Immediate window while testing on my colleague's machine)
  • Security settings: 'Enable all macros' and 'Trust access to the VBA project object model' are both selected on my colleague's machine

I've put a MsgBox as the first line for each event handler. These don't appear, that's how I know the event isn't firing.

If I launch a MsgBox from the Immediate window, it does appear.

Edit: We've tried re-launching Excel and rebooting the whole computer. These did not help.

This is the code for each of the handlers, including the MsgBox test lines:

Private Sub Worksheet_Activate()    MsgBox "worksheet activate"    Me.Protect Password:=WORKSHEET_PASSWORD, UserInterfaceOnly:=TrueEnd SubPrivate Sub Worksheet_Change(ByVal Target As Range)    MsgBox "worksheet change"    Application.ScreenUpdating = False    FermDataWorksheetChange Target    Application.ScreenUpdating = TrueEnd Sub

I really hope someone can help me, as this is a business-critical application for my colleague.

Thank you!

Running Total With Negative to Positive X Axis Reflects Incorrect Running Total When No Data

$
0
0

I have a period of four years I am comparing. Each day the amount of positive and negative gains of sales is reflected in the data.

The raw data looks as such:

[Raw Data

My dax calculation is:

Actions running total in From Start = CALCULATE(    SUM('Total Data'[Actions]),    FILTER(        ALLSELECTED('Total Data'[From Start]),        ISONORAFTER('Total Data'[From Start], MAX('Total Data'[From Start]), DESC)    ))

This is what my chart looks like:

[Problem Chart

But the chart should look more aligned as such:

[Similar Chart

The problem chart lies on a negative to a positive axis. Centered around a central important date. Each negative date is that many days before the date. Each positive date is reflected after the date of importance. This axis comes from the "From Start" Column in my raw data.

However, if the axis is positive, such as in the similar chart, the running total is just from the start of data.

Every time an entry of data does not display data (Example: The raw data for 4/2/2017 didn't have any values so it just doesn't exist) the chart displays a large total value. I need to find a way to reflect this data with a negative to a positive axis while evening the line out to look similar to the similar chart.

Copy & Paste when userform textbox is in a frame

$
0
0

As copying & pasting within a userform is only possible via keyboard shortcuts, I've been using the code at the link below to bring up the copy/ paste menu for textboxes. I've managed to adapt it for use with a combobox. All working great.

Except for a textbox within a frame. The menu comes up but paste is greyed out.

https://wordmvp.com/FAQs/Userforms/AddRightClickMenu.htm

Any help appreciated.

Thanks!

How to pass a parameter in a SQL query in MS SQL Server from an Excel sheet

$
0
0

Let's say I have this query in SQL Server:

select * from Table1 where Column1 IN ('01061120192T') 

I want to pass the values for Column1 from a column in an Excel sheet.

I'm able to pass a single value to the query as mentioned here. But parenthesis of IN can accept multiple values so I want to pass 1000 values in the parenthesis from a column in an Excel sheet.

Tried to pass multiple values to the parameter as below, but that's not working.

=Sheet1!$G$1:$G$5

enter image description here

Viewing all 87999 articles
Browse latest View live


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