VBA Excel Issue with Copying Workbook in another Workbook - application hangs on Copy on specific files - excel

I have an issue that is honestly putting me at a loss.
I am copying a set of workbooks within a 'master' workbook (copying all the sheets). There are 2 methods I can use, either going through each sheet in the workbooks to copy each and every one in the master or else copy the workbook as a whole and place in the master workbook. I am using the second method using an array to discard sheets I dont need.
Dim ws() As String ' declare string array
ReDim ws(wb.Worksheets.Count) As String ' set size dynamically
Dim counter As Long ' running counter for ws array
counter = 0
For c = 1 to WS_Count
If wb.Worksheets(c).Name <> "TEST" Then
ws(counter) = wb.Worksheets(c).Name
counter = counter + 1
End If
Next
ReDim Preserve ws(counter-1) As String
wb.Worksheets(ws).Copy Before:=master.Worksheets(master.Worksheets.Count)
Both approaches I have tried work well with certain files however:
1) The first approach is problematic because it leaves a reference to the original file and so i moved to approach 2 which bypasses this issue as no reference is kept.
2) approach 2 is resulting in some sort of infinite loop in a certain file. the funny thing about this is that if i change the order in which they are merged the command doesnt get stuck and with another approx 50 workbooks the codes seems to work just fine. (please note that this issue doesn't occur with method 1 but method 1 has been discarded due to the file links)
The line it simply gets stuck on (no error) is
wb.Worksheets(ws).Copy Before:=master.Worksheets(master.Worksheets.Count)
Did anyone ever encounter this issue with a file not wanting to merge? Did i hit some limit somewhere? I'm at a loss because using 26 different workbooks, my code in its entirity managed to create a master workbook of 896 sheets. In this set that's getting stuck, i'm merging a 164 worksheet file with a new worksheet containing 164 files. I am using Office Professional Plus 2010.
I am currently hiding alerts, however I believe i was getting on of those messages where it asks me if i want to wait for the application.
Anyone can point me in the right direction please?

Since you are skipping "Test" pages have you tried starting with the last page and stepping -1?
For c = WS_Count to 1
If wb.Worksheets(c).Name <> "TEST" Then
ws(counter) = wb.Worksheets(c).Name
counter = counter - 1
End If
Next c

Related

Trying to store user values into an array

I am trying to create an array of a user set length that users can add values to that will be saved and output on multiple sheets. I am very new to VBA so I do not know if what I am trying to do is possible but I have tried a few methods unsuccessfully.
This is the code I have so far
Sub addCost()
Dim costArray() As Variant
ReDim Preserve costArray(1 To Range("b2").Value)
For i = 1 To Range("b2").Value
costArray(i) = 0
Next i
Dim newCost As Variant
Dim costYear As Variant
newCost = InputBox("New cost amount:")
costYear = InputBox("Year new cost is active:")
costArray(costYear) = newCost
End Sub
Here is what the input tab looks like in excel
With the length of the array being the project lifespan and the add new cost activating the code, clear costs are still in progress. Is there a way for the array to store after multiple executions of the addCost sub?
Thanks!
This link Microsoft shows some methods of store values after the macro ending (in your case, sub addCost)
I think the first solution will be good for you.
Other solutions is use Access to store data (specially if you need these data over time) or a new and clean worksheet where you can store array entries in a cell (This is a very practical solution if the number of entries does not get too big)

can you automate the creation of declaration of collections in vba

I'm playing around trying to learn vba and have chosen to create a Sodoku solver.
I've created something that works for easy and medium puzzles but I've cheated a great deal. I'm actually using the sheets to store possible values for cells 1 to 81. So, on a worksheet I have a grid 81 rows by 9 columns(cells*possibles). I use a count function at the end of the row and VBA checks if its 1 (alone) and it puts that alone value in the grid.
However, what I need now is to to start removing possibles from that row if they are made impossible because of the greater picture.
To the code query: I want to know if I can declare 81 collections to store 9 possible items automatically.
pseudo code:
for i = 1 to 81
dim coll(i) as int
next i
Or
dim my obj-coll as object
' ....
dim my obj-coll as collection.

Opening two separate Excel workbooks from a third

I'm attempting to automate something I do each day and I am not getting very far.
We run a report from an HR system each day and then compare the Id's to
1) a list of Id's we are working on this fortnight
2) a list of Id's we worked on last fortnight
3) the report that came out yesterday - so that any that weren't on the first two lists but were picked up by someone yesterday get marked.
I am writing this code in a separate spreadsheet so that this remains each day and the downloaded spreadsheet gets updated.
I thought this would be easy, but it is a couple of years since I've written much vba. But no matter what I try I can't seem to get it to read the third file.
All files are open already.
So the first file is the macro file, which just allows the other files to be selected.
The second file is the Excel document which comes from the HR system. This has "Empl ID" as the first column from A2 up to around to A500 at times.
The third file is the Excel document which details the ID's we are working on this fortnight and has "Emplid" as the first column.
With the code below I can't get the third Excel doc to work, I just get Run time error 9 : subscript out of range.
If I add a watch for Workbooks(txtMSR) I can see the sheet "MSR" as Item1 in Sheets and the name for that is MSR.
Any assistance would be most welcomed.
Dim txtWorkbook As String
Dim vLoop, vLoop2 As Integer
Dim vEID As String
Dim txtMSR As String
Dim txtWork2 As String
'Get workbook name less the .xls bit
'C13 has ps.xls in it
txtWorkbook = Left(Range("C13"), InStr(Range("C13"), ".xls") - 1)
'Next check who has the employees on this MSR
'Set counters to "zero"
vLoop = 2
vLoop2 = 2
'C7 has MSR Fortnight 20190419-20190502.xlsm in it
txtMSR = Left(Range("C7"), InStr(Range("C7"), ".xlsm") - 1)
Do Until Workbooks(txtWorkbook).Sheets("ps").Range("A" & vLoop).Text = ""
vPMKeyS = Workbooks(txtWorkbook).Sheets("ps").Range("A" & vLoop).Value
```
'The line below produces the error.
```
Do Until Workbooks(txtMSR).Sheets("MSR").Range("A" & vLoop2).Text = ""
If (vPMKeyS = Workbooks(txtMSR).Sheets("ps").Range("A" & vLoop2).Value) Then
Workbooks(txtWorkbook).Sheets("ps").Range("N1").Text = "Y"
End If
vLoop2 = vLoop2 + 1
Loop
vLoop = vLoop + 1
Loop

Excel allows adding rows manually, but not from VBA

This has been asked already, but none of the answers available helps me. I am trying to add a row to a small worksheet. I am allowed to add the row with Alt-I, R manually, but if I try to do it from a macro, I get this:
I have tried, without effect, the following suggestions I have found on the Internet:
Check that data isn’t ridiculously long. Ctrl-End takes me to G40. The last available row is 1048576.
Unfreeze panes.
Execute “ActiveSheet.UsedRange” in the Immediate window.
Unmerge cells in row above the one I was inserting.
Rows("1048500:1048576").Delete. This ought to free up 76 rows, yet immediately after it attempting to insert just one row is forbidden.
Application.CutCopyMode = False
Selecting all the rows below those used and choosing “Clear Content”, save, close and reopen.
I am using Excel 2016. The only solution that looks at all plausible is using Application.SendKeys to do Alt-I, R, but I would rather not do that if I can help it. Neither the sheet nor the workbook containing it is protected. If you want to know what the offending code is:
For iWorksheetCounter = 2 To wbkFinal.Worksheets.Count
Set wksPartial = wbkFinal.Worksheets(iWorksheetCounter)
lngCurrentRow = iWorksheetCounter + iRowOffset ' iRowOffset = 3
wksTotals.Rows.Insert (lngCurrentRow + 1) ' this is not allowed for a reason I don't understand
wksTotals.Cells(lngCurrentRow, 1).Value = wksPartial.Name
Next ' iWorksheetCounter

Having trouble populating a variable range

I have dabbled in vba for a little while, but its uses are mainly to save myself work and make easy things that are not easy to do in vanilla excel. I use SQL a lot and many things that are fascinatingly easy to get in SQL are surprisingly difficult in excel.
I recently made a new file to follow the costs that are generated when someone takes an item from our warehouse. Assuming that everything gets registered correctly I have made an SQL report that spits out different data; among which are pertinent to this question:
An article number
A cost centre
Now, I thought I would improve my file with some autogenerated lists, so I can use it for whatever department not just my own. The difference is that I know roughly the correct article numbers and cost centers of my department.
What I would like to do.
With a list of cost center numbers:
Generate a list of article numbers that are taken from the dump (~10.000 rows) that have been listed on each (specific) cost center. Unique, of course
Use the count of cost centers and the count of article numbers to copy formulas from a sheet with a template...
...then populate the fresh sheet with the cost centers and article numbers. The formulas will then fetch with sumifs from the dump and make nice monthly graphics of it all.
This is getting out of hand with the explanation, because I stranded pretty early doing this:
'-----------------------------------------------
Dim Myworkbook As Workbook
Set Myworkbook = ThisWorkbook
'-
Dim Sheet1 As Worksheet
Dim Sheet2 As Worksheet
Dim Sheet3 As Worksheet
Dim Rgensheet As Worksheet
'-
Set Sheet1 = Myworkbook.Sheets("Sheet1")
Set Sheet2 = Myworkbook.Sheets("00 Underlag")
Set Sheet3 = Myworkbook.Sheets("01 Dump")
Set Rgensheet = Myworkbook.Sheets("RGenInput")
'-
Dim Dump As Range
Set Dump = Sheet3.Range("A:M")
'------------------------------------------------
Dim antkat As Long
antkat = WorksheetFunction.Count(Rgensheet.Range("C:C"))
Dim kat As Range
Set kat = Myworkbook.Sheets("RGenInput").Range("C1:C" & antkat)
Dim kst As Long
kst = 242020
'To make matters easy I try to get the macro work for a single cost centre first...
'I plan to have a For-loop around that covers all of them, with the antkat variable
Dim artnos As Range
Dim artno As Long
Dim n As Integer
n = 1
For Each Row In Dump.Rows
If IsNumeric(Sheet3.Range("M" & Row.Row)) Then
If Sheet3.Range("M" & Row.Row) = kst Then
artno = Cells(Row.Row, 6)
On Error Resume Next
If IsError(Application.Match(artno, artnos, False)) Then
' I used the same code once to create a list of unique values from a huge list but I am unsure wether I can do this to a range that has no dimensions...
Set artnos.Range(1, n).Value = artno
n = n + 1
End If
End If
End If
Next Row
Now - this is ugly and very not up to my code standard but it has been a bigger project than what I normally do.
The question is twofold.
Is it possible to define a range variable that is completely flexible as to dimensions? This is what I am used to, you can just add rows to a variable table in sql like nothing but I am starting to think this is not possible the way I am trying to do it
Is this a reasonable way to execute the plan I made beforehand? If my code is to messy to read or the errors I make too many - can you please help me find a plan of execution or steps that can perform what I need? I can - with the help of google - figure out how to do the steps. That has worked for me in the past... =P
I found the answer, by chance, browsing through some microsoft help files. Who would have thought.
I was mistaken in thinking that a variable range can be used as the array. For future users having issues giving a variable several values - do read up on arrays which are defined by adding closed parentheses to your variable
Dim variable as integer
Dim variablearray() as integer

Resources