Showing posts with label excel. Show all posts
Showing posts with label excel. Show all posts

Tuesday, October 16, 2018

VBA, Date formatting issue

Leave a Comment

I have a code that

1) compares dates from Col X to Col Y.

2)paste dates to col Y if there is no match between columns.

Column X my format looks like

08/15/2013 09/12/2013 10/03/2013 

But when it pastes to column Y it goes,

15/08/2013 12/09/2013 03/10/2013 

How can I format my paste to go to dd/mm/yyyy.

Added more code to show array:

   ReDim PasteArr(1 To 1, 1 To 6)     subcount = 1      For Cell1 = 1 To UBound(DataArr(), 1)         For Each Cell2 In BusDates()             If DataArr(Cell1, 1) Like Cell2 Then                 Matched = True                 Exit For                                      'if it matches it will exit             ElseIf Cell2 Like BusDates(UBound(BusDates), 1) Then 'if it gets to the end, it's truly unique and needs to be added                  For index = 1 To 6                     PasteArr(subcount, index) = DataArr(Cell1, index)                 Next index                  subcount = subcount + 1                  PasteArr = Application.Transpose(PasteArr)                 ReDim Preserve PasteArr(1 To 6, 1 To subcount)                 PasteArr = Application.Transpose(PasteArr)                  Matched = False              End If         Next Cell2          If Matched = False Then             BusDates = Application.Transpose(BusDates)             ReDim Preserve BusDates(1 To UBound(BusDates) + 1)             BusDates = Application.Transpose(BusDates)             BusDates(UBound(BusDates), 1) = DataArr(Cell1, 1)         End If      Next Cell1     Worksheets("stacks").Range("M" & LastRow + 1 & ":" & Cells(LastRow + UBound(PasteArr, 1) - 1, 18).Address).Value = PasteArr 

What i've tried: Changing the format of cells

enter image description here

15/08/2013 12/09/2013 03/10/2013 

which is now the correct format for column X.

But this is pasting into column Y as:

enter image description here

which is

15/08/2013 - correct 09/12/2013 - incorrect 10/03/2013 - incorrect. 

4 Answers

Answers 1

Check your cell format. It should be:

Number   Custom     dd/mm/yyyy (depending on your locale, in my case (Dutch) it's dd/mm/jjjj) 

Answers 2

Use dd/MM/yyyy as cell format. Lowercase m stands for minutes, uppercase M for months.

Answers 3

Per my comment above, given you're using arrays and not copying ranges/cells directly. If your arrays are declared as string arrays, you will get the issue of transposed days/months. For example:

enter image description here

Could that be the issue?

Answers 4

I live in Portugal and sometimes I have issues of the same nature regarding the date formatting options. Usually, what I do (and normally it works), is using and abusing of the DateSerial function. For instance, if I wanted to populate your PasteArr array I would do:

PasteArr(subcount, index) = DateSerial(Year(DataArr(Cell1, index)), Month(DataArr(Cell1, index)), Day(DataArr(Cell1, index))) 

To write a date on a cell I do the following:

Worksheets("stacks").cells("M" & LastRow + 1).formulaR1C1 = DateSerial(Year(PasteArr(subcount, index)), Month(PasteArr(subcount, index)), Day(PasteArr(subcount, index))) 

Honesty the previous procedure seems a little bit silly. Really, it does! However it solves the problem with the date formatting dd/mm/yyyy vs mm/dd/yyyy problem. If you ask me why, I don't know exactly how it works! But it works every time!

Read More

Friday, October 5, 2018

Hiding the Excel application during run-time

Leave a Comment

I'm trying to hide Excel during a long script in which I do some web-scraping. I'm able to hide the application just fine, the problem is that when I change .Visible back to True, I'm getting 1-2 more additional applications (just empty Excel shells). I'm guessing one of these are my PERSONAL.xlsb workbook, but I'm not sure what the other one is - sometimes I get one extra, sometimes I get two. The only way I can close these shell files is by ending the EXCEL.EXE process via task manager.

I've tried hiding just the main window (Windows(1)) as well to no avail (it just hides the workbook, not the application):

Sub Test()  Windows(ThisWorkbook.Name).Visible = False  Application.Wait (Now + TimeValue("0:00:05"))  Windows(ThisWorkbook.Name).Visible = True  End Sub 

How can I just have my main workbook re-appear?

Sample code:

Sub Test()  Application.Visible = False  Application.Wait (Now + TimeValue("0:00:05"))  Application.Visible = True  End Sub 

enter image description here

Edit: This is on Windows 7, Excel 2016

Edit2: Running just Application.Visible = True by itself also gives me these two phantom applications.

Edit3: The issue definitely has to do with having macros stored in the PERSONAL.xlsb file - when I go onto a fresh computer and add a new macro to this workbook, I can reproduce the issue. However, I'm still not sure how to avoid it...

Task manager:

img1

The script that opens Excel from Filemaker Pro:

Open URL [With dialog:Off; "C:\Users\Username\Desktop\TestFile.xlsm"]

Inside TestFile.xlsm:

Private Sub Workbook_Open()  Application.Visible = False  'Refresh a query in the Excel workbook that is linked to Filemaker Pro  'Webscrape, webscrape, webscrape from a worksheet inside this Excel document 'to a hidden Internet Explorer Window (ewww, IE!)  Application.Wait (Now + TimeValue("0:00:05"))  Application.Visible = True  'Either close Excel completely or reload my main instance of Excel  End Sub 

I've realized that I can just completely quit Excel with Excel.Application.Quit, but I haven't decided if I want to exit out right away, or repaint a UserForm in Excel that summarizes the import process

3 Answers

Answers 1

I was able to reproduce your issue. First, I tested hiding the Application without having PERSONAL.xlsb loaded, and it worked fine. Then I loaded PERSONAL.xlsb and got the same behavior you did: an extra Excel shell became visible after Application.Visible = True.

I'm not sure why you sometimes get two extra shells, but maybe you have another addin (.xlam) loaded? You could try adding some code to unload all addins first, but I have an alternative solution: why not just launch a new instance of Excel, load your macro workbook in it and run the macro? For example, if your workbook is called C:\Book1.xlsb and the macro in it is "MyMacro" then create a second workbook with code that will launch Book1. Like this:

Sub LaunchIt()      Dim xlApp As Excel.Application     Dim wb As Workbook      Set xlApp = New Excel.Application     xlApp.AddIns      With xlApp         Set wb = .Workbooks.Open("C:\Book1.xlsb")         .Run "'" & wb.Name & "'!MyMacro"         wb.Close SaveChanges:=False         .Quit     End With  End Sub 

The new instance of Excel is not visible by default, so no need to set visibility. I tested it and it worked for me.

Answers 2

I can reproduce this behavior also, but setting the Visible-property of the window to false will solve it.

Private Sub Workbook_Open() Dim x As Workbook With Application     .Visible = False     .Wait (Now + TimeValue("0:00:05"))     .Visible = True         For Each x In .Workbooks             If x.Name = "PERSONAL.XLSB" Then 'maybe also other addins(?)                 x.Windows(1).Visible = True                 x.Windows(1).Visible = False 'toggle                 x.Saved = True 'for not getting save-alerts             End If         Next End With End Sub 

Edit:

or changing the for each loop to:

    For Each myAdd In AddIns         myAdd.Installed = False     Next myAdd 

works on my side (But: on closing you've to set your previous installed addins back to True)

Answers 3

If I have understood you correctly, you wish to go invisible to the user during a particular operation then reappear once that operation has completed?

If so, then take a look at the code I used to make my application actually start with Excel invisible with only a particular form on show:

When the user has finished and wishes to quit the application, he presses cmdQuit command button. The code behind this would make Excel re-appear: Code pasted below. I hope this helps to inspire you to find the solution for your situation.

Notes:
1. Ideally we would like to make the entire excel invisible! So, if there is only one instance of Excel open on the machine, then use Application.visible = true. However, it may be that other spreadsheets are open. If this is the case, then only hide the current workbook. Hence ThisWorkbook.Windows(1).Visible = False is used after in the Else block.

2. Once Excel has been made invisible, we load up our forms. These are windows which provide a front end GUI for interaction with the user. I am thus able to create a proper application from Excel almost without any indication that Excel is running behind the scenes.

3. Once the user has finished, he presses an exit button which I have called cmdExit. You can see the code bend this button below. It unloads the GUI forms and makes Excel visible again for the user. This is similar to what you want to achieve.

Private Sub Workbook_Open()      Stop      ' Hide Excel... '    ActiveWorkbook.Windows(1).Visible = False     If Workbooks.Count < 2 Then         Application.Visible = False     Else         ThisWorkbook.Windows(1).Visible = False     End If      Load frmMain     frmMain.Show vbModal  End Sub   Private Sub cmdQuit_Click()      'ThisWorkbook.Windows(1).Visible = True     Application.Visible = True     Unload frmMoreOccupationLines     Unload Me  End Sub 


I think the reason you might be seeing more than one workbook may be because you have inadvertantly left previous instances of Excel still open but hidden (invisible). They have not been unloaded and still remain in memory. Does that make sense? So when you do Application.visible=true, you are seeing all the previous instances which you did not properly quit. So a solution for m you may be to ensure you implement a proper unload and exit strategy in your code.

So I guess you might be looking for a solution like as shown below:

Sub Test()     If Workbooks.Count < 2 Then         Application.Visible = False     Else         ThisWorkbook.Windows(1).Visible = False     End If      Application.Wait (Now + TimeValue("0:00:05"))      If Workbooks.Count < 2 Then         Application.Visible = True     Else         ThisWorkbook.Windows(1).Visible = True     End If End Sub   Private Sub cmdQuit_Click()     Application.Visible = True     'Unload Me     Application.Quit End Sub 
Read More

Thursday, September 27, 2018

Unable to create a loop to compare the content of two sheets

Leave a Comment

I've written a script which is supposed to compare the content of column A between two sheets in a workbook to find out if there are partial matches. To be clearer: If any of the content of any cell in coulmn A in sheet 1 matches any of the content of any cell in coulmn A in sheet 2 then that will be a match and the script will print that in immediate window.

This is my attempt so far:

Sub GetPartialMatch()     Dim paramlist As Range      Set paramlist = Sheets(1).Range("A2:A" & Cells(Rows.Count, 1).End(xlUp).Row)      For Each cel In Sheets(2).Range("A2:A" & Cells(Rows.Count, 1).End(xlUp).Row)         If InStr(1, cel(1, 1), paramlist, 1) > 0 Then  'I used "paramlist" here as a placeholder as I can't use it            Debug.Print cel(1, 1)         End If     Next cel End Sub 

The thing is I can't make use of this paramlist defined within my script. I just used it there as a placeholder.

5 Answers

Answers 1

You want a double loop.

Sub GetPartialMatch()     Dim paramlist As Range     Dim cel as Range, cel2 as Range ; declare all variables!      Set paramlist = Sheets(1).Range("A2:A" & Cells(Rows.Count, 1).End(xlUp).Row)      For Each cel In Sheets(2).Range("A2:A" & Cells(Rows.Count, 1).End(xlUp).Row)         For Each cel2 in paramlist 'Sheets(1).Range("A2:A" & Cells(Rows.Count, 1).End(xlUp).Row)             If InStr(1, cel(1, 1), cel2, 1) > 0 Then                   Debug.Print cel(1, 1)             End If         Next cel2     Next cel End Sub 

Always use Option Explicit. Always.

This may be easier using a helper column and a formula, where the row in the helper column indicates TRUE if a MATCH is found. No VBA then. And it will be inherently faster.

Answers 2

a very fast approach is given by the use of arrays and Application.Match() function:

Sub GetPartialMatch()     Dim paramlist1 As Variant, paramlist2 As Variant     Dim cel As Range     Dim i As Long      paramlist1 = Sheets(1).Range("A2", Sheets(1).Cells(Rows.Count, 1).End(xlUp)).Value ' collect all sheets(1) column A values in an array     paramlist2 = Sheets(2).Range("A2", Sheets(2).Cells(Rows.Count, 1).End(xlUp)).Value ' collect all sheets(2) column A values in an array      For i = 1 To UBound(paramlist1) ' loop through paramlist1 array row index         If Not IsError(Application.Match(paramlist1(i, 1), paramlist2, 1)) Then Debug.Print paramlist1(i, 1) ' if partial match between current paramlist1 value and any paramlist2 value, then print it     Next End Sub 

if you want an exact match just use 0 as the last parameter in Match() function, i.e.:

If Not IsError(Application.Match(paramlist1(i, 1), paramlist2, 0)) Then Debug.Print paramlist1(i, 1) ' if exact match between current paramlist1 value and any paramlist2 value, then print it 

BTW, if you need an exact match you could also use Autofilter() method of Range object with xlFilterValues as its Operator parameter:

Sub GetPartialMatch2()     Dim paramlist As Variant     Dim cel As Range      paramlist = Application.Transpose(Sheets(1).Range("A2", Sheets(1).Cells(Rows.Count, 1).End(xlUp)).Value) ' collect all sheets(1) column A values in an array      With Sheets(2).Range("A1", Sheets(2).Cells(Rows.Count, 1).End(xlUp)) ' reference sheets(2) column A cells from row 1 (header) down to last not empty one         .AutoFilter field:=1, Criteria1:=paramlist, Operator:=xlFilterValues ' filter referenced range with 'paramlist'         If Application.WorksheetFunction.Subtotal(103, .Cells) > 1 Then ' if any filtered cell other then header             For Each cel In .Offset(1).Resize(.Rows.Count - 1).SpecialCells(xlCellTypeVisible) ' loop through all sheets(2) filtered cells but the header                 Debug.Print cel.Value2             Next         End If         .Parent.AutoFilterMode = False 'remove filter     End With End Sub 

Answers 3

Have you tried adding in:

Application.Screenupdating = false Application.Calculation = xlCalculationManual  ...Code...  Application.Screenupdating = true Application.Calculation = xlCalculationAutomatic 

These turn off the screen updating and automatic calculation of formulas within your instance of excel which can help speed up code a lot, you just have to remember to turn them back on at the end or you might give yourself a bit of a headache. It should be noted, though, that if you turn off screenupdating you won't be able to see the results roll in. You'll have to scroll backwards at the end

Another thing to consider would be store the data in an array before hand and doing the operations to the array and simply pasting it back in to the sheet. Accessing the sheet excessively slows down code drastically. Working with the accepted answer provided by @AJD, I made a few changes that will hopefully speed it up.

Sub macro()  Dim paramlist() As Variant Dim DataTable() As Variant Dim cell1 As Variant Dim cell2 As Variant  paramlist() = Sheets(1).Range("A2:A" & Worksheets(1).Cells(Rows.Count, 1).End(xlUp).Row).Value DataTable() = Sheets(2).Range("A2:A" & Worksheets(2).Cells(Rows.Count, 1).End(xlUp).Row).Value   For Each cell1 In paramlist     For Each cell2 In DataTable         If InStr(1, cell2, cell1, 1) > 0 Then             Debug.Print cell1             exit for         End If     Next cell2 Next cell1  End Sub 

I would have suggested this under the accepted answer as a suggestion, but unfortunately, I don't have enough rep to comment yet.

Edit: switching the order of the for loops allows you to insert a more efficient exit for and can allow you to skip large portions of data within the search array

Answers 4

Not sure if this is any faster (it uses pretty much the same algorithm, a loop inside of a loop), but I would argue it's a bit clearer:

Sub SearchForPartialMatches()     Dim needle1 As Range, needle2 As Range      Set needle1 = Excel.Worksheets(1).Range("$B$2")      Do While needle1.Value <> ""         Set needle2 = Excel.Worksheets(2).Range("$B$2")          Do While needle2.Value <> ""             If InStr(1, needle1.Value, needle2.Value) > 0 Then                 Debug.Print needle1.Value, needle2.Value             End If             Set needle2 = needle2.Offset(rowoffset:=1)         Loop         Set needle1 = needle1.Offset(rowoffset:=1)     Loop  End Sub 

The main difference is it's not looping over the entire column, but instead starts at the top, and uses the offset method until there are no more rows (with data).

Of course, you'll need to change the starting cell for needle1 and needle2.

I ran this with the EFF large word list copied into both sheets, and it ran in about 4 minutes (which was less time than with @AJD, but that might've been a fluke). YMMV.

Answers 5

Just one more option. Not much different from any suggestions above ... The concept is to speed up processing by minimizing VBA - Excel interactions by loading the values to arrays and processing arrays like this:

Dim cel as String, cel2 as String Dim arr1() as String, arr2 As String  arr1 = Sheets(1).Range("A2:A" & Cells(Rows.Count, 1).End(xlUp).Row) arr2 = Sheets(2).Range("A2:A" & Cells(Rows.Count, 1).End(xlUp).Row)  For Each cel In arr1     For Each cel2 in arr2         If InStr(1, cel, cel2, 1) > 0 Then               Debug.Print cel         End If     Next cel2 Next cel 

I'd like to know if it helps at all :)

Read More

Thursday, September 13, 2018

Why, when passing an array element to a function through a ParamArray, does a varpointer arrive in the function?

Leave a Comment

I have noticed an oddity in VBA when using ParamArray and passing array elements through it. In some cases it is not the value of the array element that arrives in a function, but the var pointer. (Excel 2016, 32-bit).

After some plodding I found that the definition of the function as a variant array - in combination with a parameter list combined with a ParamArray - seems to be where the unexpected behaviour originates, but I can't see any feasible reasons why this would be so.

The behaviour reverts to normal when:
1) the variable r is removed in the function declarations
2) b is declared with Dim b()
3) the function returns a Variant, rather than a Variant()

I appreciate that it's a rather esoteric question, and it appears to be controllable for in various ways, but is there an explanation out there that elucidates this behaviour?

Sub Variantarraybug()    Dim b: b = [{1, 2, 3}]     Debug.Print farray1(2, b(1))(0)    Debug.Print Application.WorksheetFunction.Sum(farray1(2, b(1)))    Debug.Print Join(farray1(2, b(1)), " ")     Debug.Print farray2(2, b(1))(0)    Debug.Print Application.WorksheetFunction.Sum(farray2(2, b(1)))    Debug.Print Join(farray2(2, b(1)), " ")    Debug.Print  VarPtr(b(1)), VarPtr(b(2)) End Sub  Function farray1(r, ParamArray plop()) As Variant    farray1 = Array(plop(0), 3) End Function Function farray2(r, ParamArray plop()) As Variant()    farray2 = Array(plop(0), 5) End Function 

Result in the debug window:

 1    4   1 3    1    6   358808368 5    358808368     358808384  

Note 1: My understanding is that the VarPtr function returns the memory location of the start address of the memory required by that variable. Here it is used only to demonstrate that the unexpected number (358808368) that was seen by the farray2 function, is in fact the address of that element.

Note 2: This happens independent of how you generate the array (e.g. b=array(1,2,3), b=[1,2,3], etc.) and how b is declared (b, b(1 to 3), etc.). However, if you declare b with Dim b(), the unexpected behaviour disappears. (You can't print VarPtr(b) in that case, as VarPtr cannot accept array variables.)

0 Answers

Read More

Monday, September 10, 2018

Excel as inlay frame in WPF has disabled ExcelWorksheet

Leave a Comment

I found a solution to setup Excel instance in WPF by using the SetParent() function of Windows.

Problem is, that mouse and keyboard is not reacting to the sheet but to the Workbook it does.

Full sample Project Download here

I also tried with WindowsFormsHost but it has the same effect.

XAML

<Window x:Class="ExcelEditor.SimpleWindow"     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"     xmlns:d="http://schemas.microsoft.com/expression/blend/2008"     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"     xmlns:local="clr-namespace:ExcelEditor"     mc:Ignorable="d" Loaded="Window_Loaded" Closing="Window_Closing"     Title="SimpleWindow" Height="450" Width="800"> <Grid x:Name="LayoutRoot">  </Grid> 

C# code

    using System;     using System.Windows;   namespace ExcelEditor {     /// <summary>     /// Interaktionslogik für SimpleWindow.xaml     /// </summary>     public partial class SimpleWindow : Window     {         private Microsoft.Office.Interop.Excel.Application ExcelApplication;          public SimpleWindow()         {             InitializeComponent();         }          private void Window_Loaded(object sender, RoutedEventArgs e)         {             System.Windows.Forms.Integration.ElementHost.EnableModelessKeyboardInterop(this); // <- testing only (no success)             ExcelApplication = new Microsoft.Office.Interop.Excel.Application();             ExcelApplication.DisplayAlerts = false;             System.Windows.Interop.HwndSource hwnd = (System.Windows.Interop.HwndSource)System.Windows.Interop.HwndSource.FromVisual(this.LayoutRoot);             var excelWnd = Microsoft.Win32.Interop.FindWindow("XLMAIN", null);             GenerateTestData(ExcelApplication);             var successOfParentSetup = Microsoft.Win32.Interop.SetParent(excelWnd, hwnd.Handle);             var isMovedToLeftTop = Microsoft.Win32.Interop.MoveWindow(excelWnd, 10, 10, 800, 600, true);             ExcelApplication.Visible = true;         }          private void GenerateTestData(Microsoft.Office.Interop.Excel.Application excelApplication)         {             var excelWorkbook = excelApplication.Workbooks.Add();             var excelWorksheet = excelWorkbook.Worksheets[1] as Microsoft.Office.Interop.Excel.Worksheet;             excelWorksheet.Cells[1, 1] = "Today";             excelWorksheet.Cells[2, 1] = DateTime.Now.ToString();         }          private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)         {             if (ExcelApplication != null)             {                 ExcelApplication.ActiveWorkbook.Close();                 ExcelApplication.Visible = false;                 ExcelApplication.Quit();                 ExcelApplication = null;             }         }     } } 

Api calls

    [DllImport("user32.dll", EntryPoint = "SetWindowPos")]     public static extern bool SetWindowPos(         IntPtr hWnd,               // handle to window         IntPtr hWndInsertAfter,    // placement-order handle         int X,                  // horizontal position         int Y,                  // vertical position         int cx,                 // width         int cy,                 // height         uint uFlags             // window-positioning options     );      [DllImport("user32.dll", EntryPoint = "MoveWindow")]     public static extern bool MoveWindow(         IntPtr hWnd,         int X,         int Y,         int nWidth,         int nHeight,         bool bRepaint     );     [DllImport("USER32.DLL", SetLastError = true)]     public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);      //Sets a window to be a child window of another window     [DllImport("USER32.DLL", SetLastError = true)]     public static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent); 

Question is, how to enable the mouse and keyboard handling in Excel to allow editing the worksheet?

Excel not working propert as parent

*Tested at: Windows 10 x64, Single screen (optional dual screen) Excel 2016 MSO 32-Bit (16.0.10325.20082) out of Office 365

This issue is also reported on Microsoft Forum to check if there is a solution.

In the following video you see how the click sometimes will select cells and sometimes it will not recognize the mouse.

Excel

1 Answers

Answers 1

You need to make sure Excel has been shown once before you can call SetParent. Of course, it looks ugly, so you also need to hide Excel UI somehow from the end-user. For example:

    private void Window_Loaded(object sender, RoutedEventArgs e)     {         ...         // get excel window         var excelWnd = Microsoft.Win32.Interop.FindWindow("XLMAIN", null);          // move excel somewhere outside the screen (of course you should compute it, not hardcode it)         Microsoft.Win32.Interop.MoveWindow(excelWnd, -10000, -10000, 800, 600, true);          // show it so it's initialized properly         ExcelApplication.Visible = true;         GenerateTestData(ExcelApplication);          // now call SetParent         Microsoft.Win32.Interop.SetParent(excelWnd, hwnd.Handle);          // move it to parent         Microsoft.Win32.Interop.MoveWindow(excelWnd, 10, 10, 800, 600, true);     } 
Read More

Saturday, September 1, 2018

Excel as inlay frame in WPF has disabled ExcelWorksheet

Leave a Comment

I found a solution to setup Excel instance in WPF by using the SetParent() function of Windows.

Problem is, that mouse and keyboard is not reacting to the sheet but to the Workbook it does.

Full sample Project Download here

I also tried with WindowsFormsHost but it has the same effect.

XAML

<Window x:Class="ExcelEditor.SimpleWindow"     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"     xmlns:d="http://schemas.microsoft.com/expression/blend/2008"     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"     xmlns:local="clr-namespace:ExcelEditor"     mc:Ignorable="d" Loaded="Window_Loaded" Closing="Window_Closing"     Title="SimpleWindow" Height="450" Width="800"> <Grid x:Name="LayoutRoot">  </Grid> 

C# code

    using System;     using System.Windows;   namespace ExcelEditor {     /// <summary>     /// Interaktionslogik für SimpleWindow.xaml     /// </summary>     public partial class SimpleWindow : Window     {         private Microsoft.Office.Interop.Excel.Application ExcelApplication;          public SimpleWindow()         {             InitializeComponent();         }          private void Window_Loaded(object sender, RoutedEventArgs e)         {             System.Windows.Forms.Integration.ElementHost.EnableModelessKeyboardInterop(this); // <- testing only (no success)             ExcelApplication = new Microsoft.Office.Interop.Excel.Application();             ExcelApplication.DisplayAlerts = false;             System.Windows.Interop.HwndSource hwnd = (System.Windows.Interop.HwndSource)System.Windows.Interop.HwndSource.FromVisual(this.LayoutRoot);             var excelWnd = Microsoft.Win32.Interop.FindWindow("XLMAIN", null);             GenerateTestData(ExcelApplication);             var successOfParentSetup = Microsoft.Win32.Interop.SetParent(excelWnd, hwnd.Handle);             var isMovedToLeftTop = Microsoft.Win32.Interop.MoveWindow(excelWnd, 10, 10, 800, 600, true);             ExcelApplication.Visible = true;         }          private void GenerateTestData(Microsoft.Office.Interop.Excel.Application excelApplication)         {             var excelWorkbook = excelApplication.Workbooks.Add();             var excelWorksheet = excelWorkbook.Worksheets[1] as Microsoft.Office.Interop.Excel.Worksheet;             excelWorksheet.Cells[1, 1] = "Today";             excelWorksheet.Cells[2, 1] = DateTime.Now.ToString();         }          private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)         {             if (ExcelApplication != null)             {                 ExcelApplication.ActiveWorkbook.Close();                 ExcelApplication.Visible = false;                 ExcelApplication.Quit();                 ExcelApplication = null;             }         }     } } 

Api calls

    [DllImport("user32.dll", EntryPoint = "SetWindowPos")]     public static extern bool SetWindowPos(         IntPtr hWnd,               // handle to window         IntPtr hWndInsertAfter,    // placement-order handle         int X,                  // horizontal position         int Y,                  // vertical position         int cx,                 // width         int cy,                 // height         uint uFlags             // window-positioning options     );      [DllImport("user32.dll", EntryPoint = "MoveWindow")]     public static extern bool MoveWindow(         IntPtr hWnd,         int X,         int Y,         int nWidth,         int nHeight,         bool bRepaint     );     [DllImport("USER32.DLL", SetLastError = true)]     public static extern IntPtr FindWindow(string lpClassName, string lpWindowName);      //Sets a window to be a child window of another window     [DllImport("USER32.DLL", SetLastError = true)]     public static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent); 

Question is, how to enable the mouse and keyboard handling in Excel to allow editing the worksheet?

Excel not working propert as parent

*Tested at: Windows 10 x64, Single screen (optional dual screen) Excel 2016 MSO 32-Bit (16.0.10325.20082) out of Office 365

1 Answers

Answers 1

You need to make sure Excel has been shown once before you can call SetParent. Of course, it looks ugly, so you also need to hide Excel UI somehow from the end-user. For example:

    private void Window_Loaded(object sender, RoutedEventArgs e)     {         ...         // get excel window         var excelWnd = Microsoft.Win32.Interop.FindWindow("XLMAIN", null);          // move excel somewhere outside the screen (of course you should compute it, not hardcode it)         Microsoft.Win32.Interop.MoveWindow(excelWnd, -10000, -10000, 800, 600, true);          // show it so it's initialized properly         ExcelApplication.Visible = true;         GenerateTestData(ExcelApplication);          // now call SetParent         Microsoft.Win32.Interop.SetParent(excelWnd, hwnd.Handle);          // move it to parent         Microsoft.Win32.Interop.MoveWindow(excelWnd, 10, 10, 800, 600, true);     } 
Read More

Tuesday, August 7, 2018

How to automate a power query in VBA?

Leave a Comment

I have data in sheet 1. Normally I go to power query and do my transformations, then close, and load to an existing sheet 2.

I would like to automate this using VBA, where I can just run my power query automatically and populate the transformation to sheet 2.

Macro recorder doesn't seem to allow me to record the steps. And there isn't much online about doing this.

Trying some simpler code:

Sub LoadToWorksheetOnly()  'Sub LoadToWorksheetOnly(query As WorkbookQuery, currentSheet As Worksheet)     ' The usual VBA code to create ListObject with a Query Table     ' The interface is not new, but looks how simple is the conneciton string of Power Query:     ' "OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=" & query.Name      query = Sheets("Sheet6").Range("A1").value 'here is where my query from power query is. I put the text from power query avanced editor in another sheet cell.     currentSheet = ActiveSheet.Name     With ActiveSheet.ListObjects.Add(SourceType:=0, Source:= _         "OLEDB;Provider=Microsoft.Mashup.OleDb.1;Data Source=$Workbook$;Location=" & query.Name _         , Destination:=Sheets("target").Range("$A$1")).QueryTable         .CommandType = xlCmdDefault         .CommandText = Array("SELECT * FROM [" & query.Name & "]")         .RowNumbers = False         .FillAdjacentFormulas = False         .PreserveFormatting = True         .RefreshOnFileOpen = False         .BackgroundQuery = True         .RefreshStyle = xlInsertDeleteCells         .SavePassword = False         .SaveData = True         .AdjustColumnWidth = True         .RefreshPeriod = 0         .PreserveColumnInfo = False         .Refresh BackgroundQuery:=False     End With  End Sub 

Here is my issue when trying to load to new sheet manually.

enter image description here

1 Answers

Answers 1

WIP:

So how to write this to be sufficient? The bottom line is you should set your query up using the inbuilt tools. Not VBA. You load your data via the appropriate method which can be from file, looping files in a folder, web, database.... the list goes on. You can import from external sources as well as load from internal. Have a look here for more information on loading from external sources.

Once you have secured your source and it is loaded you will be presented with the query editor where you can perform your transformation steps.

The point being that as you perform your steps using the UI, M code is written in the background and forms the basis of a re-usable query provided you don't change the source format or location.

In your case, when you have performed your steps and have a query as you wish you then close and load to sheet2.

At this step, the first time you are setting this up you will select sheet 2 as your close and load destination:

Close and load

NB: When you select existing sheet, ensure Sheet 2 already exists and you can manually edit Sheet2! in front of the suggested range.


You are experiencing issues because you keep trying to recreate all of this with code. Don't. Set it up using the UI and load to sheet2. From then on, either open the query editor to edit the steps and/or refresh the query to load the existing sheet2 with new/refreshed data.


Some of the available methods for refreshing your query:

The query will be refreshed by VBA/Manual refreshes to the sheet it resides in (Sheet2), or to the workbook itself e.g. Sheet2.Calculate , ThisWorkbook.RefreshAll, manually pressing the refresh workbook button in the data tab (these are all overkill really)

Refresh all tab

More targeted methods:

VBA for the query table in sheet 2:

ThisWorkbook.Worksheets("Sheet2").ListObjects(1).QueryTable.Refresh BackgroundQuery:=False    

Change the above to the appropriate table etc.

Right clicking in the querytable itself and selecting refresh:

Refresh

Click on the refresh button in the workbook queries window on the right hand side for the query in question (icon with green circling arrows)

Refresh


The Ken Pulls VBA way (minor edit from me)

Option Explicit Public Sub UpdatePowerQueries()     ' Macro to update my Power Query script(s)      Dim lTest As Long, cn As WorkbookConnection     On Error Resume Next     For Each cn In ThisWorkbook.Connections         lTest = InStr(1, cn.OLEDBConnection.Connection, "Provider=Microsoft.Mashup.OleDb.1", vbTextCompare)         If Err.Number <> 0 Then             Err.Clear             Exit For         End If         If lTest > 0 Then cn.Refresh     Next cn     On Error GoTo 0 End Sub 

There shouldn't be any real need for you to doing all of this work via VBA. You may have some tricky data manipulation you feel more comfortable doing with VBA and then having powerquery access that processed data as source. You can fire of the whole lot by having a sub that call the processing routine and then uses one of the vba command methods listed above. There are more methods and I will add them when I have more time.


Calculations:

If you have calculations that depend on the powerquery output you have 4 obvious immediate options:

  1. Add these calculations where possible into powerquery. It supports calculated columns, user defined functions and lots more.
  2. Add the powerquery output to the data model and use the data model to perform calculations including calculated fields. This will give you access to time intelligence functions aswell.
  3. Use VBA to add the calculations to the appropriate areas in sheet 2 if the range changes on refresh
  4. If range doesn't change on refresh simply put your formulas out of the way.
Read More

Thursday, August 2, 2018

Getting a series trend line equation to a shape text box

Leave a Comment

I'm attempting to get the trend line equation from the first series in my chart to a shape text box placed elsewhere on the worksheet - however, I can only get the textbox to populate correctly when I'm stepping through the code line by line - during run-time it has no effect:

For Each chtObj In ActiveSheet.ChartObjects      Set cht = chtObj.Chart      For Each srs In chtObj.Chart.SeriesCollection         srs.Trendlines(1).DisplayEquation = True 'Display the labels to get the value         ThisWorkbook.Worksheets("MyDataSheet").Shapes(slopetextboxes(k)).TextFrame.Characters.Text = srs.Trendlines(1).DataLabel.Text         srs.Trendlines(1).DisplayEquation = False 'Turn it back off         Exit For     Next srs      k = k + 1 ' for the slope textboxes  Next chtObj 

Note that slopetextboxes is an array containing the names of ~6 shape text boxes.

As far as I know there's no way to get the trend line data label without stopping to display it. I've tried storing it in a string first, DoEvents, and turning Application.ScreenUpdating back on, all to no avail. I'm stumped here.

EDIT: It appears that by placing DoEvents after .DisplayEquation = True I'm able to have some of my shapes populate correctly, but not all. Still appears to be some kind of run-time issue.

BOUNTY EDIT: I've moved ahead to grab the slopes with a formula ran into the data itself, but I still don't understand why I can't grab the chart's .DataLabel.Text during run-time. I can grab it when stepping through, not during run-time. It appears to just take the PREVIOUS series slope and place it in the shape (or a cell, it doesn't even matter where the destination is). DoEvents placed in different spots yields different outcomes, so something must be going on.

4 Answers

Answers 1

Updated with better understanding of the bug. This works for me in excel 2016 with multiple changes to the source data (and therefore the slope)

I tried myChart.refresh - didnt work. I tried deleting and then re-adding the entire trendline, also didnt work.

Option Explicit Sub main() Dim ws                                  As Worksheet Dim txtbox                              As OLEObject Dim chartObject                         As chartObject Dim myChart                             As Chart Dim myChartSeriesCol                    As SeriesCollection Dim myChartSeries                       As Series Dim myChartTrendLines                   As Trendlines Dim myTrendLine                         As trendline      Set ws = Sheets("MyDataSheet")     Set txtbox = ws.OLEObjects("TextBox1")      For Each chartObject In ws.ChartObjects         Set myChart = chartObject.Chart         Set myChartSeriesCol = myChart.SeriesCollection         Set myChartSeries = myChartSeriesCol(1)          Set myChartTrendLines = myChartSeries.Trendlines         Set myTrendLine = myChartTrendLines(1)          myTrendLine.DisplayEquation = True         myTrendLine.DataLabel.Delete         myChartTrendLines.Add          Set myChartTrendLines = myChartSeries.Trendlines         Set myTrendLine = myChartTrendLines(1)          myTrendLine.DisplayEquation = True         txtbox.Object.Text = myTrendLine.DataLabel.Text      Next chartObject End Sub 

enter image description here

enter image description here

Answers 2

Here's my code that seems to definitely work when just pressing F5:

Basically, I store the text in a collection, then iterate through all of the textboxes to add the text to the textboxes. If this wasn't precisely what you were asking for, then I hope this helps in any way.

Sub getEqus()     Dim ws As Worksheet     Dim cht As Chart     Dim srs As Variant     Dim k As Long     Dim i As Long     Dim equs As New Collection     Dim shp As Shape     Dim slopetextboxes As New Collection      Set ws = Excel.Application.ThisWorkbook.Worksheets(1)      'part of the problem seemed to be how you were defining your shape objects     slopetextboxes.Add ws.Shapes.Range("TextBox 4")     slopetextboxes.Add ws.Shapes.Range("TextBox 5")      For Each chtObj In ActiveSheet.ChartObjects         Set cht = chtObj.Chart          For Each srs In chtObj.Chart.SeriesCollection             srs.Trendlines(1).DisplayEquation = True 'Display the labels to get the value              equs.Add srs.Trendlines(1).DataLabel.Text              srs.Trendlines(1).DisplayEquation = False 'Turn it back off         Next srs      Next chtObj       For i = 1 To slopetextboxes.Count          'test output i was trying         ws.Cells(i + 1, 7).Value = equs(i)         slopetextboxes(i).TextFrame.Characters.Text = equs(i)     Next End Sub 

Pictures of what the output looks like when i just press the button

Before

After

Good luck!

Answers 3

This worked for me - I loop through multiple charts on Sheet1, toggling DisplayEquation and then writing the equation to a textbox/shape on the different worksheet. I used TextFrame2.TextRange but TextFrame worked as well, if you prefer that. I wrote to both a regular text box, as well as a shape, which was probably overkill as the syntax is the same for both.

This gets the trendline equation from the first Series - it sounded like you didn't want to loop through all the Series in the SeriesCollection.

Sub ExtractEquations()     Dim chtObj As ChartObject     Dim slopeTextBoxes() As Variant     Dim slopeShapes() As Variant     Dim i As Integer      slopeTextBoxes = Array("TextBox 1", "TextBox 2", "TextBox 3")     slopeShapes = Array("Rectangle 6", "Rectangle 7", "Rectangle 8")      For Each chtObj In ThisWorkbook.Sheets("Sheet1").ChartObjects          With chtObj.Chart.SeriesCollection(1).Trendlines(1)             .DisplayEquation = True             ThisWorkbook.Sheets("MyDataSheet").Shapes(slopeTextBoxes(i)).TextFrame2.TextRange.Characters.Text = .DataLabel.Text             ThisWorkbook.Sheets("MyDataSheet").Shapes(slopeShapes(i)).TextFrame2.TextRange.Characters.Text = .DataLabel.Text             .DisplayEquation = False             i = i + 1         End With     Next chtObj End Sub 

Answers 4

If it works when you step through, but not when it runs then it's an issue with timing and what Excel is doing in between steps. When you step through, it has time to figure things out and update the screen.

FYI, Application.Screenupdating = False doesn't work when stepping through code. It gets set back to True wherever the code pauses.

When did you give it a chance to actually do the math and calculate the equation? The answer is that, you didn't; hence why you get the previous formula.

If you add a simple Application.Calculate (in the right spot) I think you'll find that it works just fine.

In addition, why should Excel waste time and update text to an object that isn't visible? The answer is, it shouldn't, and doesn't.

In the interest of minimizing the amount of times you want Excel to calculate, I'd suggest creating two loops.

  1. The first one, to go through each chart and display the equations
  2. Then force Excel to calculate the values
  3. Followed by another loop to get the values and hide the equations again.

' Display the labels on all the Charts For Each chtObj In ActiveSheet.ChartObjects     Set cht = chtObj.Chart     For Each srs In chtObj.Chart.SeriesCollection         srs.Trendlines(1).DisplayEquation = True 'Display the labels to get the value         ' I take issue with the next line         ' Why are you creating a loop, just for the first series?         ' I hope this is just left over from a real If condition that wan't included for simplicity         Exit For     Next srs Next chtObj  Application.ScreenUpdating = True Application.Calculate Application.ScreenUpdating = False  ' Get the Equation and hide the equations on the chart For Each chtObj In ActiveSheet.ChartObjects     Set cht = chtObj.Chart     For Each srs In chtObj.Chart.SeriesCollection         ThisWorkbook.Worksheets("MyDataSheet").Shapes(slopetextboxes(k)).TextFrame.Characters.Text = srs.Trendlines(1).DataLabel.Text         srs.Trendlines(1).DisplayEquation = False 'Turn it back off         Exit For     Next srs     k = k + 1 ' for the slope textboxes Next chtObj Application.ScreenUpdating = True 

Update:

I added a sample file based on your description of the issue. You can select 4 different options in an ActiveX ComboBox which copies values to the Y-Values of a chart. It shows the trend-line equation below, based on the formula & through copying the value from the chart into a Textbox shape.

Maybe 2016 is different, but it works perfectly in 2013. Try it out...

Shape Text Box Example.xlsm

Read More

Monday, July 23, 2018

VBA/Formula, Mapping among sheets

Leave a Comment

I have a code that I am having trouble running on excel 2013. 2010 works fine.

I've been contemplating just doing formulas because I cannot get this to work.

Here is the logic

  1. Only fill values in sheet X if this condition exists: In Sheet A , If column a = value 1 , value 2, or value 3 and column b <> value 4, <> value 5

  2. Then lookup headers from sheet X into sheet Y. These headers will be in sheet Y column c.

  3. for the headers that are matched to sheet Y col c, find like data of sheet X. column c, and sheet Y. column d. Going to use these as lookup for next column in sheet Y. For where there are mismatches use 'OTHERS' as value.

  4. for matched headers/columns return sheet Y column e (value) and multiply by sheet X. column d. minus one.

  5. return all these values to sheet a where the headers are like.

Sheet X (below formulas in stack and overflow cols would actually be calculated)

+-------------+-------------+------------+-------+-----------------+-------------+ |  conditions | condition 2 | currency   | value |     stack       |  overflow   | +-------------+-------------+------------+-------+-----------------+-------------+ | value 1     | value 10    | USD        |   100 | 100 * (.75 - 1) |             | | value 2     | value 7     | XRP        |   200 | 200 * (.50 - 1) |             | | value 3     | value 8     | USD        |   300 |                 | 300*(.65-1) | | value 1     | value 9     | XRP        |   400 |                 | 400*(.24-1) | +-------------+-------------+------------+-------+-----------------+-------------+ 

Sheet Y

+----------+----------+--------+ | header   | currency |  value | +----------+----------+--------+ | stack    | USD      |    .75 | | stack    | OTHER    |    .50 | | overflow | USD      |    .65 | | overflow | OTHER    |    .24 | +----------+----------+--------+ 

This code gets slow at the for loop at the bottom of the code.

Here is my code:

Public Sub calc()      Application.ScreenUpdating = False      Dim i As Long, thisScen As Long, nRows As Long, nCols As Long          Dim stressWS As Worksheet     Set stressWS = Worksheets("EQ_Shocks")     Unprotect_Tab ("EQ_Shocks")     nRows = lastWSrow(stressWS)     nCols = lastWScol(stressWS)      Dim readcols() As Long     ReDim readcols(1 To nCols)     For i = 1 To nCols         readcols(i) = i     Next i      Dim eqShocks() As Variant     eqShocks = colsFromWStoArr(stressWS, readcols, False)       'read in database columns     Dim dataWs As Worksheet     Set dataWs = Worksheets("database")      nRows = lastrow(dataWs)     nCols = lastCol(dataWs)      Dim dataCols() As Variant     Dim riskSourceCol As Long     riskSourceCol = getWScolNum("condition 2", dataWs)      ReDim readcols(1 To 4)     readcols(1) = getWScolNum("value", dataWs)     readcols(2) = getWScolNum("currency", dataWs)     readcols(3) = getWScolNum("condition", dataWs)     readcols(4) = riskSourceCol      dataCols = colsFromWStoArr(dataWs, readcols, True)      'read in scenario mappings     Dim mappingWS As Worksheet     Set mappingWS = Worksheets("mapping_ScenNames")      Dim stressScenMapping() As Variant     ReDim readcols(1 To 2): readcols(1) = 1: readcols(2) = 2     stressScenMapping = colsFromWStoArr(mappingWS, readcols, False, 2) 'include two extra columns to hold column number for IR and CR shocks      For i = 1 To UBound(stressScenMapping, 1)         stressScenMapping(i, 3) = getWScolNum(stressScenMapping(i, 2), dataWs)         If stressScenMapping(i, 2) <> "NA" And stressScenMapping(i, 3) = 0 Then             MsgBox ("Could not find " & stressScenMapping(i, 2) & " column in database")             Exit Sub         End If     Next i      ReDim readcols(1 To 4): readcols(1) = 1: readcols(2) = 2: readcols(3) = 3: readcols(4) = 4     stressScenMapping = filterOut(stressScenMapping, 2, "NA", readcols)      'calculate stress and write to database     Dim thisEqShocks() As Variant      Dim keepcols() As Long     ReDim keepcols(1 To UBound(eqShocks, 2))     For i = 1 To UBound(keepcols)         keepcols(i) = i     Next i      Dim thisCurrRow As Long      For thisScen = 1 To UBound(stressScenMapping, 1)          thisEqShocks = filterIn(eqShocks, 2, stressScenMapping(thisScen, 1), keepcols)          If thisEqShocks(1, 1) = "#EMPTY" Then             For i = 2 To nRows                 If dataCols(i, 4) <> "value 4" And dataCols(i, 4) <> "value 5" And (dataCols(i, 1) = "value 1" Or dataCols(i, 1) = "value 2") Then                     dataWs.Cells(i, stressScenMapping(thisScen, 3)).value = "No shock found"                 End If             Next i         Else 'calculate shocks             Call quicksort(thisEqShocks, 3, 1, UBound(thisEqShocks, 1))             For i = 2 To nRows                 If dataCols(i, 4) <> "value 5" And dataCols(i, 4) <> "value 6" And (dataCols(i, 1) = "value 1" Or dataCols(i, 1) = "value 2" Or dataCols(i, 1) = "value 3") Then                     thisCurrRow = findInArrCol(dataCols(i, 3), 3, thisEqShocks)                     If thisCurrRow = 0 Then 'could not find currency so use generic shock                         thisCurrRow = findInArrCol("OTHERS", 3, thisEqShocks)                     End If                     If thisCurrRow = 0 Then                         dataWs.Cells(i, stressScenMapping(thisScen, 3)).value = "No shock found"                     Else                         dataWs.Cells(i, stressScenMapping(thisScen, 3)).value = Replace(dataCols(i, 2), "-", 0) * (thisEqShocks(thisCurrRow, 4) - 1)                     End If                 End If             Next i         End If      Next thisScen      Application.ScreenUpdating = True  End Sub 

3 Answers

Answers 1

Here is a formula only solution, using a helper column to lookup 2 criteria (header & column) at once:

  1. Add a helper column in Sheet Y column E like shown below. Use the following formula in E:

    =C:C&D:D 

    enter image description here

  2. Use the following formula in E2 and copy it down and right:

    =IF(AND(OR($A:$A="value 1",$A:$A="value 2",$A:$A="value 3"),$B:$B<>"value 4",$B:$B<>"value 5"),$D:$D*(IFNA(VLOOKUP(E$1&$C:$C,'Sheet Y'!$E:$F,2,FALSE),VLOOKUP(E$1&"OTHER",'Sheet Y'!$E:$F,2,FALSE))-1),"") 

    enter image description here

    The calculation part of the formula

    $D:$D*(IFNA(VLOOKUP(E$1&$C:$C,'Sheet Y'!$E:$F,2,FALSE),VLOOKUP(E$1&"OTHER",'Sheet Y'!$E:$F,2,FALSE))-1) 

    looks up a combination of "header" and column C in the helper column. If it finds the combination it returns its value if not it looks up a combination of "header" and "OTHER" and returns its value to perform the calculation.

    The IF(AND(OR part is the condition of your point 1 in your question.

Answers 2

I read a rubber duck post and was inspired to turn this from script like code into code like code. My comment below still stands though. I tested on 5000 cells and this coded executed in under a second on average.

INSIDE THIS WORKBOOK:

Option Explicit  Sub main()     Dim startTime As Long         startTime = Tests.GetTickCount      Dim ws As Worksheet         Set ws = Sheets("Sheet1")      Dim lastRow As Integer         lastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).row      With ws.Sort         .SortFields.Clear         .SortFields.Add Key:=Range("A4:A" & lastRow), Order:=xlAscending         .SortFields.Add Key:=Range("B4:B" & lastRow), Order:=xlAscending         .Header = xlYes         .SetRange Range("A4:F" & lastRow)         .Apply     End With      Dim colOfItems As Collection         Set colOfItems = New Collection      Dim cell As Range      For Each cell In ws.Range("A4:A" & lastRow)         Dim item As Items         If cell.value <> 1 And cell.value <> 2 And cell.value <> 3 Then             Exit For         Else             Set item = Factories.newItem(ws, cell.row)             colOfItems.Add item             Set item = Nothing         End If     Next cell      Set ws = Nothing      Dim wsTwo As Worksheet         Set wsTwo = Sheets("Sheet2")      Dim row As Integer         row = 4     Dim itemcheck As Items      For Each itemcheck In colOfItems         If Tests.conditionTwoPass(itemcheck) Then             With wsTwo                 .Range("A" & row) = itemcheck.conditionOne                 .Range("B" & row) = itemcheck.conditionTwo                 .Range("C" & row) = itemcheck.CurrencyType                 .Range("D" & row) = itemcheck.ValueAmount                 .Range("E" & row) = itemcheck.Stack                 .Range("F" & row) = itemcheck.OverFlow             End With             row = row + 1         End If     Next itemcheck      Dim endTime As Long         endTime = Tests.GetTickCount      Debug.Print endTime - startTime End Sub 

INSIDE MODULE NAMED FACTORIES:

Public Function newItem(ByRef ws As Worksheet, ByVal row As Integer) As Items         With New Items             .conditionOne = ws.Range("A" & row)             .conditionTwo = ws.Range("B" & row)             .CurrencyType = ws.Range("C" & row)             .ValueAmount = ws.Range("D" & row)             .Stack = ws.Range("E" & row)             .OverFlow = ws.Range("F" & row)             Set newItem = .self         End With End Function 

INSIDE MODULE NAMED TESTS:

Public Declare Function GetTickCount Lib "kernel32" () As Long  Function conditionTwoPass(ByVal itemcheck As Items) As Boolean     conditionTwoPass = False     If itemcheck.conditionTwo <> 4 And itemcheck.conditionTwo <> 5 Then             conditionTwoPass = True     End If End Function 

INSIDE CLASS MODULE NAMED ITEMS:

Private pConditionOne As Integer Private pConditionTwo As Integer Private pCurrencyType As String Private pValueAmount As Integer Private pStack As String Private pOverflow As String  Public Property Let conditionOne(ByVal value As Integer)     pConditionOne = value End Property  Public Property Get conditionOne() As Integer     conditionOne = pConditionOne End Property Public Property Let conditionTwo(ByVal value As Integer)     pConditionTwo = value End Property  Public Property Get conditionTwo() As Integer     conditionTwo = pConditionTwo End Property  Public Property Let CurrencyType(ByVal value As String)     If value = "USD" Then         pCurrencyType = value     Else         pCurrencyType = "OTHER"     End If End Property  Public Property Get CurrencyType() As String     CurrencyType = pCurrencyType End Property  Public Property Let ValueAmount(ByVal value As Integer)     pValueAmount = value End Property  Public Property Get ValueAmount() As Integer     ValueAmount = pValueAmount End Property  Public Property Let Stack(ByVal value As String)     pStack = value End Property  Public Property Get Stack() As String     Stack = pStack End Property  Public Property Let OverFlow(ByVal value As String)     pOverflow = value End Property  Public Property Get OverFlow() As String     OverFlow = pOverflow End Property  Public Property Get self() As Items     Set self = Me End Property 

enter image description here

enter image description here

enter image description here

enter image description here

enter image description here

Answers 3

  1. the loop gets slow because it's too much interaction between excel and VBA. Put the entire loop within the VBA , filling in the 2D array and dump the result out like so:

    Sheets(1).cells(1,1).Resize(Ubound(arr2D),Ubound(arr2D,2)).value2 = arr2D 
  2. on the contrary, quicksort call is probably slow in VBA, so it may make sense to sort in Excel AFTER the array is pasted back to a sheet using native Range.Sort method.

Read More

Tuesday, July 17, 2018

how to debug a c++ excel plugin's exception during excel exiting

Leave a Comment

I have an excel xll plug-in built in c++ (and with the help of xlw), which, runs pretty well except, when excel exits, exception happens occasionally.

My headache is that though it looks like some destructor issue, I can't see where it went wrong.

Excel window just closes then a Windows system error message pops out.

Even if I run it in Visual Studio debug mode, when the exception happened, it's already in the STL c++ code, also I can't see which part of my code, such as a destructor, is the root cause of the failure.

To be precise, Call Stack shows [External Code] -> Excel.Exe -> [External Code] -> MSO.DLL ... repeat... OART.DLL... repeat ... ntdll.cll -> [External Code] -> _cexit() -> common_exit -> __acrt_lock_and_call -> ...

The first step with source visible is exit.cpp in C:\Program Files (x86)\Windows Kits\10\Source\10.0.16299.0\ucrt\startup\exit.cpp,

extern "C" void __cdecl _cexit() {     common_exit(0, _crt_exit_full_cleanup, _crt_exit_return_to_caller); } 

1 Answers

Answers 1

Have you tried setting a conditional breakpoint in Visual Studio settings to break on any exception (or the specific exception you are getting)? You can enable this just before you exit Excel. This might help track down the problem and give you the call stack in the call stack window when the breakpoint hits.

Also make sure to check if your symbol files (.pdb) are getting loaded for your code and any third party dependencies. Another thing that can help is to specify the Microsoft public symbol servers so that the Microsoft system pdb’s are loaded as well as mentioned in this article.

Read More

Tuesday, July 10, 2018

Excel VBA, “Unpivoting” Data leads to crashing of excel

Leave a Comment

I have a code that crashes my excel, it takes the data from one sheet and transforms it from a tabular view to vertical. I believe it is slow because it is taking it from a database view to over 45k rows.

does anyone have any tips for optimizing this code? Crashes my excel at the next c loop

Also I tried running this in excel 2010, get an overflow error, but usually 2010 runs better and 2013 is slow or not responding. But I want to get it working for 2013.

Sub Unpivot()     Call ReversePivotTable("Sheet1", "A", "C", "Sheet2", "Name") End Sub    Sub ReversePivotTable(source_sheet, from_col, to_col, target_sheet, Optional type_header = "type", Optional value_header = "value")      Application.ScreenUpdating = False     LAST_ROW = Sheets(source_sheet).Cells(Rows.count, 1).End(xlUp).Row     If LAST_ROW > 1 Then         Sheets(target_sheet).Cells.ClearContents     Else         Exit Sub     End If      pvt_type_col = Sheets(target_sheet).Range(to_col & 1).Offset(0, 1).column 'D     pvt_value_col = Sheets(target_sheet).Range(to_col & 1).Offset(0, 2).column 'E      'get headers     Sheets(source_sheet).Range(from_col & ":" & to_col).copy     Sheets(target_sheet).Range("A1").PasteSpecial xlPasteValues     Sheets(target_sheet).Cells(1, pvt_type_col).Value = type_header     Sheets(target_sheet).Cells(1, pvt_value_col).Value = value_header        'tranform data     curr_row = 2     With Sheets(source_sheet)         last_col = .Cells(1, Columns.count).End(xlToLeft).column             For Each c In .Range("A2", .Range("A" & Rows.count).End(xlUp))                 Set rng = .Range(.Cells(c.Row, pvt_type_col), .Cells(c.Row, last_col))                 numbers = Application.WorksheetFunction.CountIf(rng, "<>""")                 If numbers > 0 Then                     Sheets(source_sheet).Range(from_col & c.Row & ":" & to_col & c.Row).copy                     Sheets(target_sheet).Range(from_col & curr_row & ":" & from_col & curr_row + numbers - 1).PasteSpecial Paste:=xlPasteValues                     Application.CutCopyMode = False                     b = curr_row                     For a = pvt_type_col To last_col Step 1                         If IsNumeric(.Cells(c.Row, a).Value) Then                         'If .Cells(c.Row, a).Value <> "" Then                             Sheets(target_sheet).Cells(b, pvt_type_col) = .Cells(1, a)                             Sheets(target_sheet).Cells(b, pvt_value_col) = .Cells(c.Row, a)                             b = b + 1                         End If                     Next a                     curr_row = curr_row + numbers                     If curr_row Mod 10 = 0 Then DoEvents                 End If             Next c     End With     Sheets(target_sheet).Select     Application.CutCopyMode = False     Application.ScreenUpdating = True  End Sub 

Adding sample data, before:

+---------+------------------+-----------------+--------------+-------------+--------------+-------------+--------------+--------------+-------------+-------------+-------------+--------------+--------------+-------------+-------------+--------+--------+--------+--------------+--------------+-------------+--------------+-------------+-------------+-------------+-------------+--------------+-------------+--------------+-------------+--------------+-------------+--------+--------+--------+--------+--------+--------+--------+--------+--------+--------+--------+--------+--------+--------+--------+--------+ |  col 1  |      col 2       |      col 3      |    col 4     |    col 5    |    col 6     |    col 7    |    col 8     |    col 9     |   col 10    |   col 11    |   col 12    |    col 13    |    col 14    |   col 15    |   col 16    | col 17 | col 18 | col 19 |    col 20    |    col 21    |   col 22    |    col 23    |   col 24    |   col 25    |   col 26    |   col 27    |    col 28    |   col 29    |    col 30    |   col 31    |    col 32    |   col 33    | col 34 | col 35 | col 36 | col 37 | col 38 | col 39 | col 40 | col 41 | col 42 | col 43 | col 44 | col 45 | col 46 | col 47 | col 48 | col 49 | +---------+------------------+-----------------+--------------+-------------+--------------+-------------+--------------+--------------+-------------+-------------+-------------+--------------+--------------+-------------+-------------+--------+--------+--------+--------------+--------------+-------------+--------------+-------------+-------------+-------------+-------------+--------------+-------------+--------------+-------------+--------------+-------------+--------+--------+--------+--------+--------+--------+--------+--------+--------+--------+--------+--------+--------+--------+--------+--------+ | stack   | questions forums | excel questions | -540.0689323 | 1543.570725 | -144.7954348 | 2298.261951 | -9019.970702 | -14669.27805 |  2400.31011 | 642.2459256 | 5573.176935 | -19167.60096 | -17070.78503 | 2884.343252 |   2262.2904 |      0 |      0 |      0 | -4866.524221 | -5470.616311 | 6722.889306 | -6749.153327 | 8483.707603 | 7513.052842 | 3768.659869 | 8600.703543 | -8642.799155 | 1322.251923 | -1323.911031 | 3651.739593 | -259.3401823 | 9369.890794 |      0 |      0 |      0 |      0 |      0 |      0 |      0 |      0 |      0 |      0 |      0 |      0 |      0 |      0 |      0 |      0 | | stack   | questions forums | excel questions | -325.5117945 | 641.8568521 | -58.21010305 | 977.4626836 | -3505.695779 | -7455.410001 | 777.9341271 | 385.2714806 | 1932.531773 | -8861.136183 | -6679.463121 | 1177.775583 | 881.2548725 |      0 |      0 |      0 | -1813.822794 | -2266.860562 | 2278.669772 | -2361.758467 | 3356.446385 | 2741.992369 | 1461.950204 | 3289.154294 |  -3469.10217 | 804.7989704 | -816.9003551 | 1907.515323 |  432.8435868 | 3074.256129 |      0 |      0 |      0 |      0 |      0 |      0 |      0 |      0 |      0 |      0 |      0 |      0 |      0 |      0 |      0 |      0 | | stack   | questions forums | excel questions | -36.42618332 | 65.26139258 | -6.513963305 | 99.38442773 | -435.0485137 | -1047.099199 | 79.09717611 | 39.17283622 | 186.7060257 | -1272.372107 |  -922.750792 | 118.3261869 | 89.60240903 |      0 |      0 |      0 | -210.3183182 | -267.1376584 | 214.6223869 | -280.0000537 | 293.4738136 | 248.5196226 | 144.0720039 | 288.5506437 | -430.0886416 | 81.82868405 | -91.41469707 | 184.4395708 |  44.00977438 | 272.8284368 |      0 |      0 |      0 |      0 |      0 |      0 |      0 |      0 |      0 |      0 |      0 |      0 |      0 |      0 |      0 |      0 | | stack   | questions forums | excel questions | -582.3647427 | 1316.573479 | -165.4555206 | 1925.519573 | -7138.977944 | -17532.94829 | 1404.004642 | 930.6126154 | 3648.013625 | -19585.55834 |  -13758.8035 | 2376.319408 |   1898.9449 |      0 |      0 |      0 | -3625.886962 | -4833.808881 | 4232.764078 | -4449.956081 | 6883.584715 |  5398.12044 | 4048.773452 | 6632.405148 | -7240.871663 | 1959.676076 | -2008.657583 | 4413.431721 |  1360.661107 | 5484.849776 |      0 |      0 |      0 |      0 |      0 |      0 |      0 |      0 |      0 |      0 |      0 |      0 |      0 |      0 |      0 |      0 | +---------+------------------+-----------------+--------------+-------------+--------------+-------------+--------------+--------------+-------------+-------------+-------------+--------------+--------------+-------------+-------------+--------+--------+--------+--------------+--------------+-------------+--------------+-------------+-------------+-------------+-------------+--------------+-------------+--------------+-------------+--------------+-------------+--------+--------+--------+--------+--------+--------+--------+--------+--------+--------+--------+--------+--------+--------+--------+--------+ 

desired after:

+---------+------------------+-----------------+-----------+--------------+ |  col 1  |      col 2       |      col 3      | Attribute |    Value     | +---------+------------------+-----------------+-----------+--------------+ | stack | questions forums | excel questions | col 4     | -540.0689323 | | stack | questions forums | excel questions | col 5     |  1543.570725 | | stack | questions forums | excel questions | col 6     | -144.7954348 | | stack | questions forums | excel questions | col 7     |  2298.261951 | | stack | questions forums | excel questions | col 8     | -9019.970702 | | stack | questions forums | excel questions | col 9     | -14669.27805 | | stack | questions forums | excel questions | col 10    |   2400.31011 | | stack | questions forums | excel questions | col 11    |  642.2459256 | | stack | questions forums | excel questions | col 12    |  5573.176935 | | stack | questions forums | excel questions | col 13    | -19167.60096 | | stack | questions forums | excel questions | col 14    | -17070.78503 | | stack | questions forums | excel questions | col 15    |  2884.343252 | | stack | questions forums | excel questions | col 16    |    2262.2904 | | stack | questions forums | excel questions | col 17    |            0 | | stack | questions forums | excel questions | col 18    |            0 | | stack | questions forums | excel questions | col 19    |            0 | | stack | questions forums | excel questions | col 20    | -4866.524221 | | stack | questions forums | excel questions | col 21    | -5470.616311 | | stack | questions forums | excel questions | col 22    |  6722.889306 | | stack | questions forums | excel questions | col 23    | -6749.153327 | | stack | questions forums | excel questions | col 24    |  8483.707603 | | stack | questions forums | excel questions | col 25    |  7513.052842 | | stack | questions forums | excel questions | col 26    |  3768.659869 | | stack | questions forums | excel questions | col 27    |  8600.703543 | | stack | questions forums | excel questions | col 28    | -8642.799155 | | stack | questions forums | excel questions | col 29    |  1322.251923 | | stack | questions forums | excel questions | col 30    | -1323.911031 | | stack | questions forums | excel questions | col 31    |  3651.739593 | | stack | questions forums | excel questions | col 32    | -259.3401823 | | stack | questions forums | excel questions | col 33    |  9369.890794 | | stack | questions forums | excel questions | col 34    |            0 | | stack | questions forums | excel questions | col 35    |            0 | | stack | questions forums | excel questions | col 36    |            0 | | stack | questions forums | excel questions | col 37    |            0 | | stack | questions forums | excel questions | col 38    |            0 | | stack | questions forums | excel questions | col 39    |            0 | | stack | questions forums | excel questions | col 40    |            0 | | stack | questions forums | excel questions | col 41    |            0 | | stack | questions forums | excel questions | col 42    |            0 | | stack | questions forums | excel questions | col 43    |            0 | | stack | questions forums | excel questions | col 44    |            0 | | stack | questions forums | excel questions | col 45    |            0 | | stack | questions forums | excel questions | col 46    |            0 | | stack | questions forums | excel questions | col 47    |            0 | | stack | questions forums | excel questions | col 48    |            0 | | stack | questions forums | excel questions | col 49    |            0 | | stack | questions forums | excel questions | col 4     | -325.5117945 | | stack | questions forums | excel questions | col 5     |  641.8568521 | | stack | questions forums | excel questions | col 6     | -58.21010305 | | stack | questions forums | excel questions | col 7     |  977.4626836 | | stack | questions forums | excel questions | col 8     | -3505.695779 | | stack | questions forums | excel questions | col 9     | -7455.410001 | | stack | questions forums | excel questions | col 10    |  777.9341271 | | stack | questions forums | excel questions | col 11    |  385.2714806 | | stack | questions forums | excel questions | col 12    |  1932.531773 | | stack | questions forums | excel questions | col 13    | -8861.136183 | | stack | questions forums | excel questions | col 14    | -6679.463121 | | stack | questions forums | excel questions | col 15    |  1177.775583 | | stack | questions forums | excel questions | col 16    |  881.2548725 | | stack | questions forums | excel questions | col 17    |            0 | | stack | questions forums | excel questions | col 18    |            0 | | stack | questions forums | excel questions | col 19    |            0 | | stack | questions forums | excel questions | col 20    | -1813.822794 | | stack | questions forums | excel questions | col 21    | -2266.860562 | | stack | questions forums | excel questions | col 22    |  2278.669772 | | stack | questions forums | excel questions | col 23    | -2361.758467 | | stack | questions forums | excel questions | col 24    |  3356.446385 | | stack | questions forums | excel questions | col 25    |  2741.992369 | | stack | questions forums | excel questions | col 26    |  1461.950204 | | stack | questions forums | excel questions | col 27    |  3289.154294 | | stack | questions forums | excel questions | col 28    |  -3469.10217 | | stack | questions forums | excel questions | col 29    |  804.7989704 | | stack | questions forums | excel questions | col 30    | -816.9003551 | | stack | questions forums | excel questions | col 31    |  1907.515323 | | stack | questions forums | excel questions | col 32    |  432.8435868 | | stack | questions forums | excel questions | col 33    |  3074.256129 | | stack | questions forums | excel questions | col 34    |            0 | | stack | questions forums | excel questions | col 35    |            0 | | stack | questions forums | excel questions | col 36    |            0 | | stack | questions forums | excel questions | col 37    |            0 | | stack | questions forums | excel questions | col 38    |            0 | | stack | questions forums | excel questions | col 39    |            0 | | stack | questions forums | excel questions | col 40    |            0 | | stack | questions forums | excel questions | col 41    |            0 | | stack | questions forums | excel questions | col 42    |            0 | | stack | questions forums | excel questions | col 43    |            0 | | stack | questions forums | excel questions | col 44    |            0 | | stack | questions forums | excel questions | col 45    |            0 | | stack | questions forums | excel questions | col 46    |            0 | | stack | questions forums | excel questions | col 47    |            0 | | stack | questions forums | excel questions | col 48    |            0 | | stack | questions forums | excel questions | col 49    |            0 | | stack | questions forums | excel questions | col 4     | -36.42618332 | | stack | questions forums | excel questions | col 5     |  65.26139258 | | stack | questions forums | excel questions | col 6     | -6.513963305 | | stack | questions forums | excel questions | col 7     |  99.38442773 | | stack | questions forums | excel questions | col 8     | -435.0485137 | | stack | questions forums | excel questions | col 9     | -1047.099199 | | stack | questions forums | excel questions | col 10    |  79.09717611 | | stack | questions forums | excel questions | col 11    |  39.17283622 | | stack | questions forums | excel questions | col 12    |  186.7060257 | | stack | questions forums | excel questions | col 13    | -1272.372107 | | stack | questions forums | excel questions | col 14    |  -922.750792 | | stack | questions forums | excel questions | col 15    |  118.3261869 | | stack | questions forums | excel questions | col 16    |  89.60240903 | | stack | questions forums | excel questions | col 17    |            0 | | stack | questions forums | excel questions | col 18    |            0 | | stack | questions forums | excel questions | col 19    |            0 | | stack | questions forums | excel questions | col 20    | -210.3183182 | | stack | questions forums | excel questions | col 21    | -267.1376584 | | stack | questions forums | excel questions | col 22    |  214.6223869 | | stack | questions forums | excel questions | col 23    | -280.0000537 | | stack | questions forums | excel questions | col 24    |  293.4738136 | | stack | questions forums | excel questions | col 25    |  248.5196226 | | stack | questions forums | excel questions | col 26    |  144.0720039 | | stack | questions forums | excel questions | col 27    |  288.5506437 | | stack | questions forums | excel questions | col 28    | -430.0886416 | | stack | questions forums | excel questions | col 29    |  81.82868405 | | stack | questions forums | excel questions | col 30    | -91.41469707 | | stack | questions forums | excel questions | col 31    |  184.4395708 | | stack | questions forums | excel questions | col 32    |  44.00977438 | | stack | questions forums | excel questions | col 33    |  272.8284368 | | stack | questions forums | excel questions | col 34    |            0 | | stack | questions forums | excel questions | col 35    |            0 | | stack | questions forums | excel questions | col 36    |            0 | | stack | questions forums | excel questions | col 37    |            0 | | stack | questions forums | excel questions | col 38    |            0 | | stack | questions forums | excel questions | col 39    |            0 | | stack | questions forums | excel questions | col 40    |            0 | | stack | questions forums | excel questions | col 41    |            0 | | stack | questions forums | excel questions | col 42    |            0 | | stack | questions forums | excel questions | col 43    |            0 | | stack | questions forums | excel questions | col 44    |            0 | | stack | questions forums | excel questions | col 45    |            0 | | stack | questions forums | excel questions | col 46    |            0 | | stack | questions forums | excel questions | col 47    |            0 | | stack | questions forums | excel questions | col 48    |            0 | | stack | questions forums | excel questions | col 49    |            0 | | stack | questions forums | excel questions | col 4     | -582.3647427 | | stack | questions forums | excel questions | col 5     |  1316.573479 | | stack | questions forums | excel questions | col 6     | -165.4555206 | | stack | questions forums | excel questions | col 7     |  1925.519573 | | stack | questions forums | excel questions | col 8     | -7138.977944 | | stack | questions forums | excel questions | col 9     | -17532.94829 | | stack | questions forums | excel questions | col 10    |  1404.004642 | | stack | questions forums | excel questions | col 11    |  930.6126154 | | stack | questions forums | excel questions | col 12    |  3648.013625 | | stack | questions forums | excel questions | col 13    | -19585.55834 | | stack | questions forums | excel questions | col 14    |  -13758.8035 | | stack | questions forums | excel questions | col 15    |  2376.319408 | | stack | questions forums | excel questions | col 16    |    1898.9449 | | stack | questions forums | excel questions | col 17    |            0 | | stack | questions forums | excel questions | col 18    |            0 | | stack | questions forums | excel questions | col 19    |            0 | | stack | questions forums | excel questions | col 20    | -3625.886962 | | stack | questions forums | excel questions | col 21    | -4833.808881 | | stack | questions forums | excel questions | col 22    |  4232.764078 | | stack | questions forums | excel questions | col 23    | -4449.956081 | | stack | questions forums | excel questions | col 24    |  6883.584715 | | stack | questions forums | excel questions | col 25    |   5398.12044 | | stack | questions forums | excel questions | col 26    |  4048.773452 | | stack | questions forums | excel questions | col 27    |  6632.405148 | | stack | questions forums | excel questions | col 28    | -7240.871663 | | stack | questions forums | excel questions | col 29    |  1959.676076 | | stack | questions forums | excel questions | col 30    | -2008.657583 | | stack | questions forums | excel questions | col 31    |  4413.431721 | | stack | questions forums | excel questions | col 32    |  1360.661107 | | stack | questions forums | excel questions | col 33    |  5484.849776 | | stack | questions forums | excel questions | col 34    |            0 | | stack | questions forums | excel questions | col 35    |            0 | | stack | questions forums | excel questions | col 36    |            0 | | stack | questions forums | excel questions | col 37    |            0 | | stack | questions forums | excel questions | col 38    |            0 | | stack | questions forums | excel questions | col 39    |            0 | | stack | questions forums | excel questions | col 40    |            0 | | stack | questions forums | excel questions | col 41    |            0 | | stack | questions forums | excel questions | col 42    |            0 | | stack | questions forums | excel questions | col 43    |            0 | | stack | questions forums | excel questions | col 44    |            0 | | stack | questions forums | excel questions | col 45    |            0 | | stack | questions forums | excel questions | col 46    |            0 | | stack | questions forums | excel questions | col 47    |            0 | | stack | questions forums | excel questions | col 48    |            0 | | stack | questions forums | excel questions | col 49    |            0 | +---------+------------------+-----------------+-----------+--------------+ 

2 Answers

Answers 1

Sorry, but i don't want to analyse your code and even use it for set of reasons...

First of all, a common error within VBA programming is to used unspecified (undeclared) variables. This causes several issues, especially when a programmer have made a spelling mistake (typing error), for example instead of myvariable he used myvairable. So...
It's strongly recommended to use Option Explicit statement, because... as MSDN documentation states:

If you do not specify a data type, the Variant data type is assigned by default.

(...)

Variables of type Variant require more memory resources than most other variables

(...)

If a module includes the Option Explicit statement, a compile-time error will occur when Visual Basic encounters a variable name that has not been previously declared, or that has been spelled incorrectly.

For further details, please see:
Wikipedia: Visual Basic for Applications
VBA: Declaring Variables
Runtime vs Compile time
Office Talk: Working with VBA in the 32-bit and 64-bit Versions of Office 2010

Second of all, an Overflow error occurs when you try to make an assignment that exceeds the limitations of the target of the assignment. That error might be the reason of Excel crush.

Third of all, you should use code in context. Un-contextual usage of code might be the reason of several issues, such as loss of data.
Imagine: there are 2 opened workbooks. Both of them have the same set of sheets: Sheet1, Sheet2 and Sheet3. When you use Sheets("Sheet1").Range("A1") = "whatever" changes are made in active workbook, let's say Workbook1, but you wanted to make changes in Workbook2. Got it?
BTW: note, that Sheet is not the same as Worksheet
Sheets vs. Worksheets
So, a proper way to use code-in-context is:

Dim srcWsh As Worksheet Dim trgWsh As Worksheet  Set srcWsh = ThisWorkbook.Worksheets("Sheet1") 'you can use index too, see: Set trgWsh = Workbooks("Workbook2").Worksheets(2)  trgWsh.Range("A1") = srcWsh.Range("A1")  'finally, you have to clean up Set srcWsh = Nothing Set trgWsh = Nothing 

The same rules have to be used when you create or call procedure or function

Finally...
As to the method to reverse (unpivot) data...
I did use an example from MSDN: Using PIVOT and UNPIVOT, where these data:

VendorID    Emp1    Emp2    Emp3    Emp4    Emp5 1           4       3       5       4       4 2           4       1       5       5       5 3           4       3       5       4       4 4           4       2       5       5       4 5           5       1       5       5       5 

have to be "converted" into this form:

VendorID    Employee    Orders ----------- ----------- ------ 1            Emp1       4 1            Emp2       3  1            Emp3       5 1            Emp4       4 1            Emp5       4 2            Emp1       4 2            Emp2       1 2            Emp3       5 2            Emp4       5 2            Emp5       5 ... 

My code:

Option Explicit  Sub Test()     UnpivotData ThisWorkbook.Worksheets("Arkusz1"), _         ThisWorkbook.Worksheets("Arkusz2"), _         "A1", "B1:F1" End Sub   Sub UnpivotData(ByVal srcWsh As Worksheet, ByVal trgWsh As Worksheet, ByVal unpvtFor As String, ByVal pivotedColumns As String, _     Optional ByVal commonHeader As String = "Employee", Optional ByVal pvtValuesToCol As String = "Orders")      'declare variables     Dim lastrow As Long, r As Long, trgr As Long     Dim c As Long, cName As String      'on error go to error handler     On Error GoTo Err_UnpivotData      'find last row     lastrow = srcWsh.UsedRange.Rows.Count      'context!     With trgWsh         'clear         .Cells.Clear         'add headers         .Range("A1") = srcWsh.Range(unpvtFor)         .Range("B1") = commonHeader         .Range("C1") = pvtValuesToCol         '"convert" values         r = 1         trgr = 0         'loop through the collection of rows in srcWsh         Do While r < lastrow             'loop through the collection of pivoted columns in srcWsh             For c = 0 To srcWsh.Range(pivotedColumns).Columns.Count - 1                 'unpivot value of 1. column                 .Range("A2").Offset(RowOffset:=trgr, ColumnOffset:=0) = srcWsh.Range(unpvtFor).Offset(RowOffset:=r, ColumnOffset:=0)                 'unpivot header                 cName = srcWsh.Range(pivotedColumns).Columns(c + 1).Address                 .Range("A2").Offset(RowOffset:=trgr, ColumnOffset:=1) = srcWsh.Range(cName).Rows(1)                 'unpivot value                 .Range("A2").Offset(RowOffset:=trgr, ColumnOffset:=2) = srcWsh.Range(unpvtFor).Offset(RowOffset:=r, ColumnOffset:=c + 1)                 'increase target counter                 trgr = trgr + 1             Next             'increase source counter             r = r + 1         Loop     End With  Exit_UnpivotData:     On Error Resume Next     'clean up      Exit Sub  Err_UnpivotData:     MsgBox Err.Description, vbExclamation, Err.Number     Resume Exit_UnpivotData End Sub 

Feel free to change it to your needs...

Working example: Unpivot.xlsm - available to download between 7:01AM and 11:59PM Central Europe (Warsaw) Time

I hope i've explained in details what's wrong with your code.

[EDIT]
Assuming that data are in Sheet1 and target sheet is Sheet2...

Option Explicit  Sub Test()      UnpivotData ThisWorkbook.Worksheets("Sheet1"), _         ThisWorkbook.Worksheets("Sheet2"), _         "A1:C1", "D1:AW1" End Sub   Sub UnpivotData(ByVal srcWsh As Worksheet, ByVal trgWsh As Worksheet, ByVal unpvtFor As String, ByVal pivotedColumns As String, _     Optional ByVal commonHeader As String = "Attribute", Optional ByVal pvtValuesToCol As String = "Value")      'declare variables     Dim lastrow As Long, r As Long, trgr As Long     Dim c As Long, cName As String     Dim cc As Range      'on error go to error handler     On Error GoTo Err_UnpivotData      'find last row     lastrow = srcWsh.UsedRange.Rows.Count      'context!     With trgWsh         'clear         .Cells.Clear         'add headers         For Each cc In srcWsh.Range(unpvtFor).Cells             .Range("A1").Offset(ColumnOffset:=c) = Trim(cc)             c = c + 1         Next         Set cc = .Range("A2").Offset(ColumnOffset:=c)         .Range("A1").Offset(ColumnOffset:=c) = commonHeader         c = c + 1         .Range("A1").Offset(ColumnOffset:=c) = pvtValuesToCol         '"convert" values         r = 1         trgr = 0         'loop through the collection of rows in srcWsh         Do While r < lastrow             'loop through the collection of pivoted columns in srcWsh             For c = 0 To srcWsh.Range(pivotedColumns).Columns.Count - 1                 'copy original data                 srcWsh.Range(unpvtFor).Offset(RowOffset:=r).Copy .Range("A2").Offset(RowOffset:=trgr)                 'unpivot data - attribute                 cName = srcWsh.Range(pivotedColumns).Columns(c + 1).Address                 cc.Offset(RowOffset:=trgr, ColumnOffset:=0) = Trim(srcWsh.Range(cName).Rows(1))                 'unpivot data - value                 cc.Offset(RowOffset:=trgr, ColumnOffset:=1) = Trim(srcWsh.Range(cName).Offset(RowOffset:=r))                 'increase target counter                 trgr = trgr + 1             Next             'increase source counter             r = r + 1         Loop     End With  Exit_UnpivotData:     On Error Resume Next     'clean up     Set cc = Nothing     Exit Sub  Err_UnpivotData:     MsgBox Err.Description, vbExclamation, Err.Number     Resume Exit_UnpivotData End Sub 

Good luck!

Answers 2

Try this:

Sub Unpivot()     Call ReversePivotTable("Sheet1", "A", "C", "Sheet2", "Name") End Sub    Sub ReversePivotTable(source_sheet, from_col, to_col, target_sheet, Optional type_header = "type", Optional value_header = "value")      Application.ScreenUpdating = False     LAST_ROW = Sheets(source_sheet).Cells(Rows.Count, 1).End(xlUp).Row     If LAST_ROW > 1 Then         Sheets(target_sheet).Cells.ClearContents     Else         Exit Sub     End If      pvt_type_col = Sheets(target_sheet).Range(to_col & 1).Offset(0, 1).Column 'D     pvt_value_col = Sheets(target_sheet).Range(to_col & 1).Offset(0, 2).Column 'E      'get headers     Sheets(source_sheet).Range(from_col & ":" & to_col).Copy     Sheets(target_sheet).Range("A1").PasteSpecial xlPasteValues     Sheets(target_sheet).Cells(1, pvt_type_col).Value = type_header     Sheets(target_sheet).Cells(1, pvt_value_col).Value = value_header      'tranform data     curr_row = 2     With Sheets(source_sheet)         last_col = .Cells(1, Columns.Count).End(xlToLeft).Column             For Each c In .Range("A2", .Range("A" & Rows.Count).End(xlUp))                 Set Rng = .Range(.Cells(c.Row, pvt_type_col), .Cells(c.Row, last_col))                 numbers = Application.WorksheetFunction.CountIf(Rng, "<>""")                 If numbers > 0 Then                     Sheets(target_sheet).Range(from_col & curr_row & ":" & from_col & curr_row + numbers - 1).Value = Sheets(source_sheet).Range(from_col & c.Row & ":" & to_col & c.Row).Value                     Application.CutCopyMode = False                     b = curr_row                     For a = pvt_type_col To last_col Step 1                         If IsNumeric(.Cells(c.Row, a).Value) Then                         'If .Cells(c.Row, a).Value <> "" Then                             Sheets(target_sheet).Cells(b, pvt_type_col) = .Cells(1, a)                             Sheets(target_sheet).Cells(b, pvt_value_col) = .Cells(c.Row, a)                             b = b + 1                         End If                     Next a                     curr_row = curr_row + numbers                     If curr_row Mod 10 = 0 Then DoEvents                 End If             Next c     End With     Sheets(target_sheet).Select     Application.CutCopyMode = False     Application.ScreenUpdating = True  End Sub 
Read More