Subscript out of range in VBA when running this code - excel

When i initially run the code below in debug mode, there is no problems. However when i stop and rerun it again, it says Subscript out of range. Why is that so? Not sure why such error is popping out.
Dim date1 As Double
strDate1 = Sheets("Part2").Cells(i, 1).Value
matchEndRow = Application.Match(CDbl(strDate1), Sheets("1.A").Range("A:A"), 1)
MsgBox matchEndRow
matchEndRow = matchEndRow - 1
MsgBox matchEndRow
Need some guidance.

As follow up from comments, there was another workbook opened when code runs.
So changing
Sheets("Part2") and Sheets("1.A")
to
ThisWorkbook.Sheets("Part2") and ThisWorkbook.Sheets("1.A") solves the problem.

Related

Method "PasteSpecial" of object "TextRange2" failed when copying from Excel to PPT

I've been searching for quite a while and can't seem to find a solution. I'm trying to copy multiple cells from Excel into a PPT textbox, keeping text only. The code I have seems to work well, but it will randomly error out with the message 'Method "PasteSpecial" of object "TextRange2" failed' When I hit debug, and play, it will continue as normal.
I've tried adding a delay wait since I know the clipboard can get flaky sometimes, but that hasn't seemed to help.
I also came across this post and have tried it but it still randomly errors out: https://answers.microsoft.com/en-us/msoffice/forum/all/powerpoint-vba-flaky-clipboard/3aee03af-b0be-4664-8d17-79e0507210e7
Does anyone know why this error happens randomly and it doesn't even seem to be a real error given I can just hit "play" and it will continue normally.
Here's a snippet of the code:
Sub AddText()
Set oPPTApp = GetObject(, "PowerPoint.Application")
oPPTApp.Visible = True
For x = 1 to 3
ActiveWorkbook.Worksheets("OpenEndChartingNEW").Range("A" & x & ":A" & x * 2).Copy
Application.Wait Now + TimeValue("00:00:05")
oPPTApp.ActivePresentation.slides(6).Shapes("OpenEnd").TextFrame2.TextRange.PasteSpecial msoClipboardFormatPlainText
Next x
Set oPPTApp = Nothing
End Sub
Thank you!

"Run-time error '-2147221040 (800401d0)' happen sometimes after excel upgrade from 2010 to 2016

I used VBA to generate the pictures before and the code is shown below, it never happened any error. But when I upgraded the Micro-Soft office version from 2010 to 2016, it happens
"Run-time error '-2147221040 (800401d0)'
occasionally, and it will ok if i try to re-run the same macro. Is there a way to fix this? Thanks in advance~~
Sub Chart_generate()
Dim j As Byte
Dim Max As Byte
Dim TOOL As String
Dim WCpath As String
Sheets("pivot").Select
ActiveSheet.PivotTables("PivotTable1").PivotCache.Refresh
ActiveSheet.PivotTables("PivotTable2").PivotCache.Refresh
ActiveWindow.Zoom = 130
Max = Range("AO1")
For j = 2 To Max + 1
TOOL = Range("AN" & j)
ActiveSheet.PivotTables("PivotTable1").PivotFields("TOOL").CurrentPage = TOOL
ActiveSheet.ChartObjects("Chart1").Activate
WCpath = "D:\users\Picture\" & TOOL & "_Pressure.png"
ActiveChart.ChartArea.Select
ActiveChart.Export (WCpath)
Next j
ActiveWindow.Zoom = 100
Range("A2").Select
End Sub
I have a similar issue when moving graphs generated on hidden worksheets over to a visible worksheet, and then resizing them.
My code is repeated multiple times in a large loop (not seen in code below), and it works more often than not but will periodically fail. If I use the debugger and single step it always works perfectly; it's only a problem when running full speed.
I've tried solutions from the web including DoEvents and the On Error tricks. I added a While loop and some verbal feedback to help identify the code causing the problem.
I hear "runtime 2" more often than "runtime 1". It always works fault-free single stepping in the debugger, but fails occasionally on some computers. During a fail, if I click on the pictures, the name of the object doesn't appear in the upper left box of the worksheet where it normally would.
Of the eleven machines tested, I've seen problems on three of them. Mine works better than most, which is a problem for a code developer!
histogram second
Sheets("Histogram").Activate
ActiveSheet.Shapes.Range(Array("pi_Histogram")).Select
DoEvents
On Error Resume Next
errflag = 0
Selection.Copy
While Err.Number = 1004 And errflag < 10
Err.Number = 0
Application.Speech.Speak "runtime 1"
Selection.Copy
errflag = errflag + 1
Wend
Sheets("Raw Data").Select
Range("V23").Select 'start insertion point for coefficients table
ActiveCell.Offset(1, 10 + segment).Select
DoEvents
errflag = 0
ActiveSheet.Pictures.Paste.Select
While Err.Number <> 0 And errflag < 10
Err.Number = 0
Application.Speech.Speak "runtime 2"
ActiveSheet.Pictures.Paste.Select
errflag = errflag + 1
Wend
On Error GoTo 0
Finally! The answer has been found by my companies IT professional. This issue has nothing to do with the actual VBA code chosen, the problem comes when Windows is managing the virtual memory. Office 2016 is a memory hog and the allocated virtual memory was not high enough. The problem completely goes away when on a machine with 16GB of memory the VM settings are manually changed to Custom size, Initial size=24000 and Maximum size=48000. Apparently when moving/resizing graphs and/or pictures there is a lot of memory being used, and the default setting of "Automatically manage paging file size for all drives" is just NOT the correct setting.
Turning off the clipboard function will help to resolve the problem:

Function throws Compile Error: Can't Find Project or Library on Dim lines

According to my peers this macro once worked in pasting numbers onto PDFs from a query in access. Just a guess but I am assuming since COVID-19 with everyone being home and that being the time this macro stopped working maybe this could be an issue of being on the wireless serves. I'm no expert but if that seems right and you know maybe I can bring it up.
When running this macro, which is the printing section of the macro (pasting PO numbers onto a PDF Invoice) this error seems to come up. Again, 2 months ago this worked fine. Any ideas what could be the issue? Nothing has changed in this macro from when it worked to now. The error message reads "Compile Error: Can't Find Project or Library" and it highlights the first line in yellow and highlights the 3rd line as well.
Private Function Print2PDF(FileName As String, Path As String) As String
Dim oSheet As Worksheet
Dim oPDF As PdfDistiller
Dim TmpPSFile As String
Dim PDFFile As String
Set oSheet = ActiveSheet
Set oPDF = New PdfDistiller
TmpPSFile = Path & "TmpPSFile.ps"
Path = Path & FileName & ".pdf"
PDFFile = Path
oSheet.PrintOut copies:=1, preview:=False, _
ActivePrinter:="Acrobat Distiller", printtofile:=True, _
collate:=True, PrToFileName:=TmpPSFile
oPDF.FileToPDF TmpPSFile, PDFFile, ""
Kill TmpPSFile
Print2PDF = Path
End Function
Has anyone used a macro in a similar way that could help me find out what the issue could be?
Thank you so much for your help!

Object doesn't support this property/method in an IF statement within a loop

I have a workbook that is used to organize daily orders for many customers into one sheet. The information that is entered into this sheet is then used to generate invoices for the customers.
This workbook has worked without any bugs for several months. However, recently it has started throwing up an error. I do not recall changing any of the code that could have caused this bug.
I have tried to figure this out by myself however, I am running out of ideas, here are a few things that I have found out:
The error ALWAYS pops up on the 7th iteration of the loop below (i.e when x=27).
The error ONLY has a problem with the (CheckBox " & x + 10) checkbox. I have tried running the loop avoiding checking the value of that particular checkbox and it works for all other checkboxes.
I read on another post that it might be a problem with using the dreaded .Select. So I got rid of it from everywhere that it might have been used.
My code
With ThisWorkbook.Worksheets("Invoice")
For x = 21 To 35
If .Shapes("Check Box " & x + 10).ControlFormat.Value = 1 And .Shapes("Check Box " & x + 25).ControlFormat.Value = 1 Then
MsgBox "Please only select one from the options (Return OR Discount)"
Exit Sub
Else
End If
Next x
End With
From what I understand, this error comes up when the object that I am working with does not support a property that I am trying to work with. What I do not understand is why the same lines of code, work "for 90%" of the loop (i.e the same type of object does support that property for 90% of the loop) but then it does not for one object of the same type.
For completeness, the code below is used to re-insert the checkboxes every time the workbook is used. This is done as another process might delete entire rows in the workbook, messing up the functionality of the check-boxes. So this makes sure the checkbox with the right name is in the correct cell:
Sub CheckBoxes()
ThisWorkbook.Worksheets("Invoice").CheckBoxes.Delete
With ThisWorkbook.Worksheets("Invoice")
For x = 5 To 19
Set cb = .CheckBoxes.Add(.Cells(x, "J").Left, .Cells(x, "J").Top, 4, 10)
With cb
.Name = "Check Box " & x + 26
.Caption = ""
.Display3DShading = False
End With
Set cb2 = .CheckBoxes.Add(.Cells(x, "K").Left, .Cells(x, "K").Top, 4, 10)
With cb2
.Name = "Check Box " & x + 41
.Caption = ""
.Display3DShading = False
End With
Next x
End With
End Sub
Any help or guidance in the right direction would be greatly appreciated!

Excel macro runs in console and through debugger, but not with button

Error / Expected Output
When I run it from the VBA console, the code executes properly. If I step through the code manually in the debugger, it works.
The expected output is the ID of about 2000 data points. I am checking if a data matches the user input date. If that is the case, I print the ID of the event on the other sheet. Ideally, I will have a list of inputs that have numerical IDs.
When I run the code from the console or debugger, I will get a range of IDs like: 1,2,4,5,6,11,14,166... However, when I run this from the button I consistently get the first two data points, no matter which field (Date, Time, Size).
If I set a break point in the debugger then hit the button, the code is fine. All I have to do is hold run (F5). I think this tells me that the code compiles and works; meaning that the error is not a compile or logic error.
Goal
I would like the button to run the code normally.
More Info
I set a break point at every iteration of each loop. I held the step in key. The code ran flawlessly. This worked for both the console window, and the button.
Because of this, I thought I was experiencing an error due to race conditions. I went on to run the doEvents command. I was given the same results. The console and debugger ran the code properly, but the button did not.
The Code
Sub ThisBookSource()
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
Application.DisplayStatusBar = False
Start = Now()
Dim masterRow As Integer
Dim myEvents
masterRow = 9
masterRow2 = 9
ActiveWorkbook.Worksheets("Graphs by Source").Activate
myCode = Range("D" & "2").Value
Range("C9:C2290").Clear
Range("T9:U2290").Clear
ActiveWorkbook.Worksheets("Data").Activate
For I = 3 To 2113
If Range("T" & I) = myCode Then
Worksheets("Data").Range("M" & I).Copy
Worksheets("Graphs by Source").Range("C" & masterRow).PasteSpecial xlPasteValues
masterRow = masterRow + 1
If I Mod 250 = 0 Then
DoEvents
End If
End If
Next I
ActiveWorkbook.Worksheets("Graphs by Source").Activate
Calculate
For I = 9 To 2290
If Range("I" & I).Value <> "NA" Then
Range("T" & masterRow2) = Range("G" & I).Value
Range("U" & masterRow2) = Range("I" & I).Value
masterRow2 = masterRow2 + 1
If I Mod 250 = 0 Then
DoEvents
End If
End If
Next I
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
Application.DisplayStatusBar = True
MsgBox "Done. Started at " & Start & ", and ended at " & Now & "!"
End Sub
Note
I cannot post screen shots because the data is sensitive and confidential.
If you mean to work with ThisWorkbook, work with ThisWorkbook. Doing Range("foobar") [implicitly] works off ActiveSheet, which may or may not be a worksheet in ThisWorkbook - it's a worksheet in whatever workbook is currently active. It makes the whole difference. And causes bugs every day.
Rule of thumb, explicit anything is better than implicit whatever in VBA. The language is already doing way too much stuff behind your back, you need to take control.
Rubberduck (open-source VBE add-in project I manage) can help you find all instances of implicit ActiveSheet references... and many other potential issues.

Resources