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

VBA Macro worksheet_change does not work properly

$
0
0

I have a problem with properly functioning macro. I wrote a short and simple code to either hide or unhide two last columns, depending on the selected month.

Month selection is possible with a combo box. Each month has assigned a number to it (1 - January, 2 - February, ..., etc.). The number shows in cell A1 and it changes upon selection of a month.

I want my macro to run properly depending on the month number which I choose.

    Private Sub Worksheet_Change(ByVal Target As Range)
          Dim nr_kol As Long
          If Target.Address = "$A$1" Then
            For nr_kol = 32 To 34
                If Month(Cells(6, nr_kol)) = Cells(1, 1) Then
                    Columns(nr_kol).Hidden = False
                Else
                    Columns(nr_kol).Hidden = True
                End If
            Next
        End If

    End Sub

EDIT(sorry, clicked submit too fast)

Cell A1 changes depending on combobox selection (box is located in a different row). What I have noticed is that columns will hide, but only if cell A1 is changed manually. But when I change the cell to month index containing 30 or 31 days, columns will remain hidden, thus I have two issues.

  1. A1 cell needs to be changed manually (macro is not working whatsoever when change is made by a combobox selection)

  2. When I make a manual change to February - two or three last columns will hide (as these are for the first two/three days of March). However, when I change the number to anything but February (2), columns are still hidden even though at least one should re-appear back again (if month contains 30 days).


VBA SQL returning null values

$
0
0

I'm having a problem running a SQL statement on vba excel, the last 3 Columns are for storing numbers separated by commas, but when executed on excel vba it doesn't display these values, while on other Database programs it does

the code is the following

Sub obtainColMachs()    
    Dim cnn1 As New ADODB.Connection
    Dim mrs As New ADODB.Recordset, sqry As String

    Set cnn1 = New ADODB.Connection
        cnn1.ConnectionString = "driver=SQL Server Native Client 11.0;"& _
        "server=server;uid=user;pwd=password;database=DB;"
        cnn1.ConnectionTimeout = 3
        cnn1.Open

    sqry = "select top 1 m.* from recipe r left join RecipeGroup rg on r.RecipeGroupID = rg.RecipeGroupID "& _
    "left join Matricula m on tonalidad_ID = ParentGroupID *100 + rg.RecipeGroupID where Substring(ColorNo,3,3) = 'ZG5'"

    mrs.Open sqry, cnn1
    Range("A26").CopyFromRecordset mrs

    mrs.Close
    cnn1.Close
End Sub

It should return:

Data returned on Database program

But it only returns:

Data returned in VBA Excel

Sumarize a column in 3 different levels in one pivot

$
0
0

I have a table that has the columns below.

Year Month Department Item Category Item Date Sales.

So is it possible in one pivot to have the sales sumarized in 3 different lvls. I mean after adding in columns Month,Department,Item Category and Item i can

  1. The normal summarize of Sales per Item in Month.(this is done)
  2. In another Value column Summarize on Item Category
  3. In another Value column Summarize on Department

By using only one column for values i can summarize to each level by expanding and collapse in each column category, but what i want is to have 3 columns in values and change the way of calculation. Not to use % of something but sum on a different column.

Excel Workbook statistics - Can we see how many time an excel file was viewed and by whom for a certain period?

$
0
0

I have an excel file, which is used by multiple people. Now I want to get an idea of how many are using the file and who are using it. Can I somehow see some workbook statistics?

In file => INFO => VERSION HISTORY I can see when the file was last modified, but I need some statistics on how many time is has been used (opened for a certain period). Is this possible?

Looping through visible rows only not working

$
0
0

I am trying to write a piece of code, that will color all requests which contain only one unique name for each request. Why looping trough visible cells only is not working?

UPDATE: I need to delete rows if there is only one name assigned to a particular request

So for below request I would like to remove Mary H (since her name appears only once in the request)

Request Number  Client Contact Assignee: Full Name
4350257 Eleanor B
4350257 Eleanor B
4350257 Mary H

This request is ok, no need to delete anything

8620428 Kevin M
8620428 Kevin M

In this request I would like to remove Mary H and Julia K since there names appears only once in the request)

7208497 Michael W
7208497 Mary H
7208497 Michael W
7208497 Julia K

My CODE:

Sub Testing()

Sheet1.Select

Dim r As Long, LR As Long
Dim ReqNo As Long, CCFullName As Long
Dim rgn2 As Range

LR = Sheet1.Cells(Rows.Count, 1).End(xlUp).Row

'Request Number
ReqNo = Application.Match("Request Number", Sheet1.Rows(1), 0)
'Client Contact Assignee: Full Name
CCFullName = Application.Match("Client Contact Assignee: Full Name", Sheet1.Rows(1), 0)

Set rgn2 = Columns(CCFullName)

Dim cl As Range, rng As Range, x As Long

Set rng = Range("A2:A100")
Dim cell As Range

With Range("A2:A100").SpecialCells(xlCellTypeVisible)
   For x = .Rows.Count To 1 Step -1
       Set cell = Range("A"& x) ' this sets the current cell in the loop
            For Each cl In rng.SpecialCells(xlCellTypeVisible)
                For r = LR To 2 Step -1
                    If Application.WorksheetFunction.CountIf(rgn2, Cells(r, CCFullName).Value) = 1 Then
                        Rows(r).Interior.Color = rgbBlueViolet
                    End If
                Next r
        Next cl
    Next x
End With
End Sub

The code above only colors names that are unique for the whole document, which is Mary H, Anna W and Thomas Y. However, I need the code to include also the 3 below names which occur once only in a particular request. (This is just a sample)

7208497 Kevin M
7208497 Julia K
8138382 Shahida B

Sample data:

Request Number  Client Contact Assignee: Full Name
4350257 Eleanor B
4350257 Eleanor B
4350257 Mary H
8620428 Kevin M
8620428 Kevin M
7208497 Michael W
7208497 Kevin M
7208497 Michael W
7208497 Julia K
7191212 Thomas Y
7191212 Shahida B
7191212 Shahida B
7191212 Shahida B
8138382 Julia K
8138382 Julia K
8138382 Shahida B
8138382 Julia K
8138382 Anna W

VBA: pasting from clipboard unreliable

$
0
0

I am trying to copy a range of cells from Excel and paste it onto a slide of a PowerPoint presentation (both version 2016) with the original formatting.

I tried

Allg.Copy
mySlide2.Shapes.PasteSpecial DataType:=0
myPresentation.Slides(2).Shapes(3).Name = "AllgShape"

and it works most of the time, but not always. The following runtime error happens from time to time:

'-2147188160 (80048240)': Shapes.PasteSpecial: Invalid request. Clipboard is empty or conains data which may not be pasted here

because (I think) the clipboard is not populated in time. Therefore I tried this to just repeat the copying and pasting process if an error happens:

ALLGCOPY:
  Allg.Copy
  On Error GoTo ALLGCOPY:
  mySlide2.Shapes.PasteSpecial DataType:=0
  myPresentation.Slides(2).Shapes(3).Name = "AllgShape"

It seems that the error handler does not exactly what I think it does because sometimes it just pastes the same shape 2 times when running this code.

Then I tried

Allg.Copy
PowerPointApp.CommandBars.ExecuteMso "PasteExcelTableSourceFormatting"
myPresentation.Slides(2).Shapes(3).Name = "AllgShape"

but then sometimes there's an issue with the assigning of the name for the shape, because it does not paste fast enough.

so I added a timer after the pasting

Public Sub Warten(ByVal MilliSekunden As Double)
   Dim i    As Double
   Dim ENDE As Double

   ENDE = Timer + (MilliSekunden / 1000)

   Do While i < ENDE
      DoEvents
      i = Timer
   Loop
End Sub

But this is unreliable because sometimes 100ms are sufficient, but sometimes even 2000ms aren't sufficient and I want the macro to run on most (also older) machines.

Preferably I want to work with the error handler and not with the timer as it is unreliable and depending on CPU usage.

Can someone tell me why the code with the error handler does not work and is sometimes pasting the same shape 2 times?

Thank you

Quality Center Microsoft Excel Add-in Error

$
0
0

I work on Mercury Quality Center 8.2 Build 3406 Entreprise Edition.

In order to write tests within Excel for Test Director, I installed the Excel Add-In. When I try to export the Excel file to Quality Center I get the following message

Quality Center Microsoft Excel Add-in Error

A general error has occured. Restart Microsoft Excel. Class does not support Automation or expected interface'.

I use Excel 2003 (11.5612.5606) part of MS Office Professional Edition 2003.

Could someone tell me how to make work this add-in correctly ?

Thank you.

C# - How to used for StringBuilder in Export Datatable to excel using ClosedXml

$
0
0

I am Using the this code below in

 private void Form1_Load(object sender, EventArgs e)
 {
        System.Data.DataTable dt;
        SqlConnection con=new SqlConnection("Data Source=sanjay;Initial Catalog=Login;Integrated Security=True");
        SqlCommand cmd=new SqlCommand("select * from login",con);
        SqlDataAdapter sda=new SqlDataAdapter(cmd);
         dt=new System.Data.DataTable();
        sda.Fill(dt);
        int srno = 1;

        StringBuilder stb = new StringBuilder();

        ClosedXML.Excel.XLWorkbook wb = new ClosedXML.Excel.XLWorkbook();
        String Todaysdate1 = DateTime.Now.ToString("dd-MM-yyyy");

        string appPath = Path.Combine(Environment.CurrentDirectory + "\\");
        if (!Directory.Exists(appPath + "\\" + Todaysdate1 + "\\TD"))
        {
            Directory.CreateDirectory(appPath + "\\" + Todaysdate1);
        }

        if (dt.Rows.Count > 0)
        {
           stb.Append("<html>");
             stb.Append("<head>");
             stb.Append("</head>");
             stb.Append("<body>");
             stb.Append("Sanju");
             stb.Append("<table border=2>");
             stb.Append("<tbody>");
             stb.Append("<tr style='height:25px'>");
             stb.Append("<td  colspan='18' style='text-align:center;font-size:18px;font-weight:bold;min-width:50px'>");
             stb.Append("<center> Form III - DEAF Voucher Preparation</center>");
             stb.Append("</td>");
             stb.Append("</tr>");
             stb.Append("<tr style='height:21px'>");
             stb.Append("<td colspan='18' style='text-align:center;font-size:16px;font-weight:bold;min-width:50px'>");
             stb.Append("<center>2018-05-01</center>");
             stb.Append("</td>");
             stb.Append("</tr>");
             stb.Append("<tr style='height:100px;font-weight:bold'>");
             stb.Append("<td style='text-align:center;font-size:14px'>No.</td>");
             stb.Append("</tr>");

             for (int i = 0; i < dt.Rows.Count; i++)
             {
                 stb.Append("<tr>");
                 stb.Append("<td>" + srno++ + "</td>");
                 stb.Append("<td nowrap>" + dt.Rows[i][0].ToString() + "</td>");
                 stb.Append("<td style='background-color:#ff99cc'></td>");
                 stb.Append("<td style='background-color:#ff99cc'></td>");
                 stb.Append("<td style='background-color:#ff99cc'></td>");
                 stb.Append("</tr>");
                 wb.Worksheets.Add(srno.ToString(), i);//Add worksheet
             }
             stb.Append("</tbody>");
             stb.Append("</table>");
             stb.Append("</body>");
             stb.Append("</html>");

            using (System.IO.StreamWriter file = new System.IO.StreamWriter(appPath + "\\" + Todaysdate1 + "\\TD_Results_From.XLS"))
            {
                file.WriteLine(stb.ToString());   
            }
            System.Diagnostics.Process.Start(appPath + "\\" + Todaysdate1 + "\\TD_Results_From.XLS");
        }

I am used the Wb.SavaAs() only show the add worksheet but first worksheet not open i will access workbook and all worksheet each recede create the worksheet. Add Multiple worksheet I am Using wb.Worksheets.Add(srno.ToString(), i); this statement I am also using the closedXml

The problem is a only create the main worksheet but never open the all worksheet

Any Body Help Me Advance Thank You


Insert a formula for specific cells

$
0
0

Due to beginner for VBA, I am in a difficult to find this codes. I need to create 'Command Button' to insert formula according to current cell location. example: I have these cells that has data C3, C5, C10 so as you can see the C4, C6, C7, C8, C9, C11, C12, C13 has no data so here is the thing that the result I want.

So for C4 I wanted to get the data in C3

in C6, C7, C8, C9 I wanted to get the data in C5

in C11, C12, C13 I wanted to get the data for C10.

Modify excel if function with cumulative sum into python dataframe column

$
0
0

I wan't to rewrite function from excel to column in python dataframe.

the function is

A2=IF((SUM($P$2:P2)+HelpTables!$D$2)<=500000,10,IF((SUM($P$2:P2)+HelpTables!$D$2)<=1000000,20,30))

It is second row, the third looks like

A3=IF((SUM($P$2:P3)+HelpTables!$D$2)<=500000,10,IF((SUM($P$2:P3)+HelpTables!$D$2)<=1000000,20,30))

and so on.

The HelpTables!$D$2 is only number, but I have to keep it as variables.

I want to apply this function into dataframe in python script, but I don't know how do it. Let's say Column P is names as 'Price' in dataframe, Column A as 'Line' and the variable is as float64 variable named as 'SUM'

Can you please help me how o do it? Thank you.

VBA Excel: Get the clicked cell´s adress on another workbook

$
0
0

I have an excel file A with a macro and I have to retrive a cell´s adress in another excel file B by the user´s click on it.

The macro looks like this.

In the Class:

Public WithEvents appevent As Application

Private Sub appevent_SheetBeforeDoubleClick(ByVal Sh As Object, ByVal Target As Range, Cancel As Boolean)
ClickedCell = ActiveCell.Address
End Sub

In the Module

Sub ClickedCellSub()
Dim WbA As Variant, WbB As Variant
WbA = ThisWorkbook.Name
WbB = "B.xlsx"
MsgBox "Please double click on the Assembly SS 00 you want to compare"
Set myobject.appevent = Application
Workbooks(WbB).Sheets(1).Activate
Set myobject.appevent = Nothing
MsgBox ClickedCell
Workbooks(WbA).Activate
End Sub

The problem is, the macro doesn´t wait for the event DoubleClick on the other excel sheet and goes to the end.

How can I stop the macro until the event happens?

Many thanks in advance!

Hyperlink loop in VBA

$
0
0

I have a problem, because I want to make program with make hyperlink for folders, I already have this part:

Dim a As String
Dim i As Long
Dim ark1 As Worksheet
Set ark1 = Arkusz1

For i = 1 To 3
    ark1.Cells(i, "A").Select
    a = "TR_"& i
    ActiveCell.Hyperlinks.Add Anchor:=Selection, Address:="C:/"& a, _
    SubAddress:="", ScreenTip:="a", TextToDisplay:=a
Next i

End Sub

But I have folders: TR_1_Jon TR_2_Allex etc. And it is possible to make this loop that excel will be recognize only first part: "TR_1_******"?

Runtime Error 13 when TextBox containing a Date is empty

$
0
0

Despite of checking many questions relating error 13, I could not find answers to my problem, so I am giving a shot here:

I am building my code to save information from a userform, but first I am testing to see if mandatory textboxes are empty. Since I am using a 64 bits machine I have used Trevor Eyre´s CalendarForm.

However while testing the code I hit a problem with the empty textboxes that receives the dates from CalendarForms:

In this line:

Dim dteCompraDataOps As Date: dteCompraDataOps = Me.txtTesouro_Compra_DataOps.value

This part is highlighted and returns Runtime Error 13:

dteCompraDataOps = Me.txtTesouro_Compra_DataOps.value 

When I check the values coming from empty TextBoxes I get:

dteCompraDataOps = "00:00:00"` 

Which is correct since it should be treated as Date, but this:

Me.txtTesouro_Compra_DataOps.value = ""

Is coming as a string.

I did a little search and noticed that Date data types are tricky when the textbox they come from are empty.

I could find a solution: creating a Select Case to test the mandatory fields before declaring the variables but I would like o learn how to deal with the empty textboxes that are supposed to be empty.

Any chance you can shed some light into my conundrum?

Thanks in advance. Cub4_RJ

Where find information about We found a problem with some content in

$
0
0

I generated an Excel file with Java code.

But when I want to open it, I'm facing this issue:

We found a problem with some content in 'file.xlsx'. Do you want us to try to recover as much as we can? If you trust the source of the workbook, Click Yes.

How can I have more information about the issue? To know the reason of openning problem.

Thank you.

Set series collection as range - VBA - Excel

$
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

Excel 2016/2013 crashes running SaveAs method 2 times

$
0
0

I'd like to create several new workbooks. The VBA code below runs fine with Excel 365 and 2010. BUT with Excel 2013 or 2016, it runs fine the first time (and create the files)... and on the second run, Excel crashes without any error message.

If I run it step by step, I see that it's the SaveAs line that causes the crash.

I tried to kill the file before saving, too. To use a timer...

I tried to repair Office, to rename a HKEY (Identities), I tried to run it on 2 different windows (7 or 10). Nothing helps :/

Sub ExtraireType()
Dim shVentes As Worksheet
Dim rngVentes As Range
Dim rngTypes As Range
Dim shNew As Worksheet
Dim wkbNew As Workbook
Dim strPath As String
Dim zaza As Range

Application.DisplayAlerts = False
Set shVentes = ThisWorkbook.Worksheets("Ventes")
Set rngVentes = shVentes.Range("A1").CurrentRegion
Set rngTypes = ThisWorkbook.Worksheets("Liste").Range("A2:A4")
strPath = ThisWorkbook.Path

For Each zaza In rngTypes
    rngVentes.AutoFilter
    rngVentes.AutoFilter field:=3, Criteria1:=zaza.Value
    rngVentes.Copy
    Set shNew = ThisWorkbook.Worksheets.Add
    shNew.Paste
    Application.CutCopyMode = False
    shNew.Move
    Set wkbNew = ActiveWorkbook
    wkbNew.SaveAs strPath & "\Type"& zaza.Value & Format(Date, "yyyymmdd")
    wkbNew.Close
    Set shNew = Nothing
    Set wkbNew = Nothing
Next zaza

Set rngVentes = Nothing
Set shVentes = Nothing
Set rngTypes = Nothing
Application.DisplayAlerts = False
End Sub

This code runs well with Excel 2010 or 2019/365. But I have to use it with 2013 or 2016 :(

What am I doing wrong? Thanks for any help !

VBA to import 10 most recently created text file to Excel

$
0
0

I currently have VBA code that opens each text file in a given location and imports data into Excel. The problem is that I have 1000's of text file in the location and I do not want to import them all. I only want to import the 10 most recently created text files. How do I change my Do While loop to achive this?

Sub LoopThroughTextFiles()
' Defines variables
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim Text As String
Dim Textline As String
Dim LastCol As Long
Dim RowCount As Long

' Optimize Macro Speed
Application.ScreenUpdating = False
Application.EnableEvents = False

Sheets("26").Select
Cells.Select
Selection.ClearContents
Range("A1").Select

' Defines LastCol as the last column of data based on row 1
LastCol = ActiveSheet.Cells(1, Columns.Count).End(xlToLeft).Column

' Sets the folder containing the text files
myPath = "C:\26"& "\"' Target File Extension (must include wildcard "*")
myExtension = "*.dat"' Target Path with Ending Extention
myFile = Dir(myPath & myExtension)

' Loop through each text file in folder
Do While myFile <> ""' Sets variable "RowCount" To 1
    RowCount = 1
    ' Sets variable "Text" as blank
    Text = ""' Set variable equal to opened text file
    Open myPath & myFile For Input As #1
    ' Do until the last line of the text file
    Do Until EOF(1)
        ' Add each line of the text file to variable "Text"
        Line Input #1, Textline
        Text = Textline
        ' Update RowCount row of the current last column with the content of variable "Text"
        Cells(RowCount, LastCol).Value = Text
        ' Increase RowCount by 1
        RowCount = RowCount + 1
    Loop

    ' Close the text file
    Close #1

    ' Increase LastCol by 1 to account for the new data
    LastCol = LastCol + 1

    ' Get next text file name
    myFile = Dir
Loop

Loading data from local file into Excel Add In

$
0
0

I am trying to load data from a local CSV file into into my Excel add in, in order to populate a worksheet with the data from said CSV file. Here is the current code that I have...

function readTextFile(file) {
    var rawFile = new XMLHttpRequest();
    rawFile.open("GET", file, false);
    rawFile.onreadystatechange = function () {
        if (rawFile.readyState === 4) {
            if (rawFile.status === 200 || rawFile.status == 0) {
                return rawFile.responseText;
            }
        }
    }
    rawFile.send(null);
}

When this code is called, I receive an "Access in denied" error in the rawFile.Open("GET... line. How do I fix this?

The file parameter passed in is:

"file:///C:/path/to/file/data.csv"

How to change code upgrade from 2.x to 3.x in maatwebsite/excel

$
0
0

I migrated my application to laravel 6.0 .When installing the packages in the composer.json i upgraded from "maatwebsite/excel:~2.1.0" to "maatwebsite/excel": "^3.1".So now my export function does not work anymore.I tried to follow the upgrade in https://docs.laravel-excel.com/3.1 but didn't work for me.this is the old code that used to work in the old version:

Excel::create($bang,function($excel) use ($array_Data ,$bang)
        {
            $excel->setTitle($bang);
            $excel->sheet($bang,function($sheet) use($array_Data,$bang){
            $sheet->fromArray($array_Data,null,'A1',false,false);   
            });
        })->download('xlsx');

Exit For Each Loop on Cancel of Save Dialog Box

$
0
0

I am new to VBA and as part of my own development I'm currently in the process of re-writing some automation I wrote to completion some 6+ months ago. I have the below code which identifies the sheet name based on which sheet a button is pushed (there are two different sheet names similar to CustName_CALC and two buttons). It then goes through the remaining sheets in the workbook to find "similar" sheets.

Please note that this is a WIP so there are some variables which aren't being used ie Set wb = ThisWorkbook

The below sub PDF_Bill() is applied to the before mentioned buttons:

Public vPDFilename As Variant
Public wb As Workbook
Public ws As Worksheet
Public wsBill As Worksheet
Public wsCalc As Worksheet
Public wsStatement As Worksheet
Public sLocation As String, sCustName As String, myTitle As String, myMsg As String, InitialFileName As String, Response As String, C_Response As String

Sub PDF_Bill()

sCustName = Left(ActiveSheet.Name, InStr(ActiveSheet.Name, "_") - 1)

Set wb = ThisWorkbook
Set wsCalc = wb.Sheets(sCustName & "_CALC")

myTitle = "Save Invoice"
myMsg = "Are you sure you would like to save the "& wsCalc.Cells(1, 2).Value2 & " invoice?"
Response = MsgBox(myMsg, vbQuestion + vbOKCancel, myTitle)
Select Case Response
    Case Is = vbOK

For Each wsBill In ThisWorkbook.Worksheets
        If wsBill.Name Like sCustName & "_BILL"& "*" Then
                    Call Module1_PDF.PDF_Procedure
        End If       
    Next wsBill

    Case Is = vbCancel
        'user cancels the first popup message
        myTitle = "Invoice Cancelled!"
        myMsg = "You've cancelled the request to save the invoice!"
        C_Response = MsgBox(myMsg, vbOKOnly, myTitle)

End Select
End Sub

The above calls this:

Sub PDF_Procedure()

sCustName = Left(ActiveSheet.Name, InStr(ActiveSheet.Name, "_") - 1)
sLocation = "S:DRIVELOCATION"& wsCalc.Cells(1, 2).Value2 & "\Invoices\"

vPDFilename = Application.GetSaveAsFilename( _
InitialFileName:=sLocation _
                    & wsCalc.Cells(1, 2).Value2 _
                    & "" _
                    & MonthName(Month(Date)) _
                    & " Invoice", _
FileFilter:="PDF, *.pdf", _
Title:="Save as PDF")

If vPDFilename <> False Then
    With wsBill
        '.Visible = xlSheetVisible '[will be hidden at later state]
        '.Activate
        'predefined area for 5 page invoice - this may need to change in future.
        .PageSetup.PrintArea = "A1:S300"
    End With

    'creates the PDF
    wsBill.ExportAsFixedFormat _
    Type:=xlTypePDF, _
    Filename:=vPDFilename, _
    OpenAfterPublish:=False

    'wsBill.Visible = xlSheetHidden 'bill sheet HIDE [WILL BE USED LATER NOT SET UP]
    Else
      'if user cancels save dialog box
      myTitle = "Invoice Cancelled!"
      myMsg = "You've cancelled the request to save the invoice!"
      C_Response = MsgBox(myMsg, vbOKOnly, myTitle)
      wsCalc.Activate
      GoTo CancelProcess    
End If
CancelProcess:
Exit Sub
End Sub

The above code (with the exception of the GoTo CancelProcess since that is what I'm struggling with) works perfectly for one sheet called CustName_Bill but I also need it to work for the below scenario.

I have reviewed the following pages and more without success:

I know I need an exit statement somewhere, but I'm struggling to understand where it goes. A lot of the examples I've seen aren't complex enough to lead me to a conclusion how to resolve my issue.

My issue currently is that I have two sheets which are named similar (on purpose):

  • CustName_Bill_Type
  • CustName_Bill_Type1

the loop continues onto the next sheet ie CustName_Bill_Type1 when the user cancels the Application.GetSaveAsFilename but I need the for each loop to exit when the user cancels the firstApplication.GetSaveAsFilename dialog box.

So my question is, where do I need to put my exit to get the code to stop as soon as the user clicks cancel on the first save dialog box.

Viewing all 88150 articles
Browse latest View live


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