Excel Application Crash due to Macro - vba

During launching my macro the Excel application is crashed. If I test the macro with an integer the program runs properly (partnumber = 123). If I check with a string the application is crashed. Thus, no error code is visible for me. I assume that there is a type mismatch (but I set Variant for partnumber)
Sub SbIsInCOPexport()
Dim lastRow As Long
Dim i As Long
Dim found As Boolean
Dim partnumber As Variant
i = 1
found = False
partnumber = ActiveCell.Value
Windows("COPexport.xlsx").Activate
lastRow = Sheets(1).Cells.SpecialCells(xlLastCell).Row
Do While i < lastRow + 1
If Cells(i, 6).Value = partnumber Then
found = True
Exit Do
End If
i = i + 1
Loop
If found = True Then
Cells(i, 6).Select
MsgBox ("Searched part number: " & Str(partnumber) & vbNewLine & "Found part number: " _
& ActiveCell.Value & vbNewLine & "Address: " & Cells(i, 6).Address & vbNewLine & vbNewLine & "Test Order: " & _
Cells(i, 2).Value)
Windows("COPexport.xlsx").Activate
Else
MsgBox "Part number is not found in the COP samples!"
Windows("COPexport.xlsx").Activate
End If
End Sub
What can be the root cause?

I don't see any obvious issues, but consider using the .Find method of range object, like so:
Sub SbIsInCOPexport()
Dim partnumber as Variant
Dim rng as Range
Windows("COPexport.xlsx").Activate
partnumber = ActiveCell.Value
Set rng = Columns(6).Find(partnumber) '## Search in column 6 for partnumber
If rng Is Nothing Then
MsgBox "Part number is not found in the COP samples!"
Windows("COPexport.xlsx").Activate
Else
With rng
MsgBox ("Searched part number: " & Str(partnumber) & vbNewLine & _
"Found part number: " & .Value & vbNewLine & _
"Address: " & .Address & vbNewLine & vbNewLine & _
"Test Order: " & .Offset(0,-4).Value) '## Get the value from column 2
End With
End If
End Sub

Related

Inserting a Formula into Cell with table reference using VBA

I'm trying to insert a formula into a cell so a variable that is captured with a MsgBox function is inserted into the formula.
TmpPT = "=IF(NOT(ISBLANK(INDEX(" & "Table10[Recvd Date]" & ",MATCH("" * """ & prjNum & """ * "" ," & "Table10[Project Name]" & ",0)))),INDEX(" & "Table10[Recvd Date]" & ",MATCH("" * """ & prjNum & """ * ""," & "Table10[Project Name]" & ",0))," & "Not Yet Received" & ")"
The overall objective for my code below is to unhide another sheet and insert data into a range within that sheet. If irrelevant, please disregard the information.
Private Sub CommandButton1_Click()
Dim SetPT As Variant
Dim TmpStg As Variant
Dim r As Integer
Dim c As Integer
Dim prjNum As Variant
Dim titlerng As Range
Dim outptrng As Range
r = 0
c = 0
SetPT = "A1"
Sheets("MG Rpt").Visible = True
Sheets("MG Rpt").Activate
ActiveSheet.Range(SetPT).Select
r = 8
ActiveCell.Offset(r, c).Activate
ActiveCell.Value = "Project #:"
ActiveCell.Offset(1, c).Activate
ActiveCell.Value = "Received Date:"
ActiveCell.Offset(1, c).Activate
ActiveCell.Value = "Elapsed Time:"
ActiveCell.Offset(1, c).Activate
ActiveCell.Value = "Expected Completion:"
ActiveCell.Offset(1, c).Activate
ActiveCell.Value = "Feedback:"
prjNum = InputBox("Please enter the Project # you are requesting down below.", "Project Search Query")
ActiveCell.Offset(-4, 1).Value = prjNum
ActiveCell.Offset(-4, 0).Activate
TmpStg = "=IF(NOT(ISBLANK(INDEX(" & "Table10[Recvd Date]" & ",MATCH("" * """ & prjNum & """ * "" ," & "Table10[Project Name]" & ",0)))),INDEX(" & "Table10[Recvd Date]" & ",MATCH("" * """ & prjNum & """ * ""," & "Table10[Project Name]" & ",0))," & "Not Yet Received" & ")"
Range("B10").Formula = TmpPT
End Sub
Am I missing an object or am I failing to format a line? Learning VBA as I go :)
The formula should look like this:
=IF(NOT(ISBLANK(INDEX(Table10[Recvd Date],MATCH("*"&prjNum&"*",Table10[Project Name],0)))),INDEX(Table10[Recvd Date],MATCH("*"&prjNum&"*",Table10[Project Name],0)),"Not Yet Received")
Solution:
Got it! Here's the final output that got it to work:
TmpStg = "=IF(NOT(ISBLANK(INDEX(Table10[Recvd Date],MATCH(""*""&" & prjNum & "&""*"",Table10[Project Name],0)))),INDEX(Table10[Recvd Date],MATCH(""*""&" & prjNum & "&""*"",Table10[Project Name],0)),""Not Yet Received"")"
Thanks for the help everyone!
Try Avoiding Select and Activate while minimizing the string concatenation down to what is absolutely necessary.
Option Explicit
Private Sub CommandButton1_Click()
Dim tmpStg As Variant, prjNum As Variant
prjNum = InputBox("Please enter the Project # you are requesting down below.", "Project Search Query")
tmpStg = "=IF(LEN(INDEX(Table10[Recvd Date], MATCH(""*" & prjNum & "*"", Table10[Project Name], 0))), " & _
"INDEX(Table10[Recvd Date], MATCH(""*" & prjNum & "*"", Table10[Project Name], 0)), ""Not Yet Received"")"
Debug.Print tmpStg
With Worksheets("MG Rpt")
.Visible = True
.Cells(9, "A").Resize(5, 1) = _
Application.Transpose(Array("Project #:", "Received Date:", "Elapsed Time:", _
"Expected Completion:", "Feedback:"))
.Cells(9, "B") = prjNum
.Cells(10, "B").Formula = tmpStg
.Cells(10, "B").NumberFormat = "mm/dd/yyyy"
.Activate
End With
End Sub
Do you really need to bracket wildcard the project number?

Run-time error 5 : Invalid procedure call or argument

I've got the below code and it works completely fine for rows 1 - 46 on it's own populating one table. As soon as I replicate this with a second table to populate it throws Error1.
I've taken out everything below "' Second Table Entry " and works fine ... put back in and same error. On the "Home" sheet it actually populates the tables information but still throws the error which is stopping further vba from executing.
Any ideas? I've been all over google, stackoverflow, superuser and Microsoft MSDN and can't figure out where in the second bit of code is causing it to error.
EDIT: I've checked the debugger and it's highlighting the below code in the second table inserts
With Worksheets("Home")
.Hyperlinks.Add Anchor:=.Range("H" & row_ptr), _
Address:="", _
SubAddress:=AddStr, _
TextToDisplay:=Workbooks(ActiveWorkbook.Name).Worksheets("Audit_InFlight").Range("D" & i).Value
End With
Any help is greatly appreciated.
Error1
Run-time error '5': Invalid procedure call or argument
Private Sub Workbook_Open()
Dim row_ptr As Long
Dim i As Long
Dim i2 As Long
Dim rownbrMA_Inflight As Long
Dim rownbrAudit As Long
Dim CurrentWorkbook As Workbook
Dim InputWorksheet As Worksheet
Dim DataSourceWorksheet As Worksheet
Dim AuditDataSourceWorksheet As Worksheet
Set CurrentWorkbook = Workbooks(ActiveWorkbook.Name)
Set InputWorksheet = CurrentWorkbook.Sheets("Home")
Set DataSourceWorksheet = CurrentWorkbook.Sheets("MA_Inflight")
Set AuditDataSourceWorksheet = CurrentWorkbook.Sheets("Audit_InFlight")
InputWorksheet.Range("A30:M176").Clear
InputWorksheet.Range("A30:M176").ClearFormats
InputWorksheet.Range("A30:M176").Interior.Color = RGB(255, 255, 255)
rownbrMA_Inflight = DataSourceWorksheet.Range("C" & Rows.Count).End(xlUp).Row
row_ptr = 31
For i = 8 To rownbrMA_Inflight
If DataSourceWorksheet.Range("C" & i).Value = "Open" Then
InputWorksheet.Rows(row_ptr).Insert Shift:=xlDown 'CopyOrigin:=xlFormatFromLeftOrAbove
InputWorksheet.Range("A" & row_ptr).Value = DataSourceWorksheet.Range("E" & i).Value
InputWorksheet.Range("B" & row_ptr).Value = DataSourceWorksheet.Range("F" & i).Value
AddStr = "MA_Inflight!" & "$F$" & CStr(i)
ActiveWorkbook.Activate
Worksheets("Home").Activate
With Worksheets("Home")
.Hyperlinks.Add Anchor:=.Range("B" & row_ptr), _
Address:="", _
SubAddress:=AddStr, _
TextToDisplay:=Workbooks(ActiveWorkbook.Name).Worksheets("MA_Inflight").Range("F" & i).Value
End With
InputWorksheet.Range("C" & row_ptr).Value = DataSourceWorksheet.Range("I" & i).Value
InputWorksheet.Range("D" & row_ptr).Value = DataSourceWorksheet.Range("J" & i).Value
InputWorksheet.Range("E" & row_ptr).Value = DataSourceWorksheet.Range("L" & i).Value
row_ptr = row_ptr + 1
End If
Next i
'============================================================
' Second Table Entry
'============================================================
rownbrAudit = DataSourceWorksheet.Range("C" & Rows.Count).End(xlUp).Row
row_ptr = Empty
row_ptr = 31
For i = 8 To rownbrAudit
If AuditDataSourceWorksheet.Range("B" & i).Value <> "Closed" Then
InputWorksheet.Rows(row_ptr).Insert Shift:=xlDown, CopyOrigin:=xlFormatFromLeftOrAbove
InputWorksheet.Range("G" & row_ptr).Value = AuditDataSourceWorksheet.Range("B" & i).Value
InputWorksheet.Range("H" & row_ptr).Value = AuditDataSourceWorksheet.Range("D" & i).Value
'New code ---------------------------
AddStr = "Audit_InFlight!" & "$D$" & CStr(i)
ActiveWorkbook.Activate
Worksheets("Home").Activate
With Worksheets("Home")
.Hyperlinks.Add Anchor:=.Range("H" & row_ptr), _
Address:="", _
SubAddress:=AddStr, _
TextToDisplay:=Workbooks(ActiveWorkbook.Name).Worksheets("Audit_InFlight").Range("D" & i).Value
End With
'-----------------------------------
InputWorksheet.Range("I" & row_ptr).Value = AuditDataSourceWorksheet.Range("G" & i).Value
InputWorksheet.Range("J" & row_ptr).Value = AuditDataSourceWorksheet.Range("H" & i).Value
InputWorksheet.Range("K" & row_ptr).Value = AuditDataSourceWorksheet.Range("I" & i).Value
InputWorksheet.Range("L" & row_ptr).Value = AuditDataSourceWorksheet.Range("J" & i).Value
InputWorksheet.Range("M" & row_ptr).Value = AuditDataSourceWorksheet.Range("K" & i).Value
row_ptr = row_ptr + 1
End If
Next i
'RemoveBlankCells
'PURPOSE: Deletes single cells that are blank located inside a designated range
Dim rng As Range
'Store blank cells inside a variable
Set rng = InputWorksheet.Range("A30:E50").SpecialCells(xlCellTypeBlanks)
'Delete blank cells and shift upward
rng.Rows.Delete Shift:=xlShiftUp
End Sub

How do i use the IF condition depending on the input contained in a column (not in a cell)?

I have an excel-workbook containing two worksheets, and I have written code to transfer data from sheet No.1 to sheet No.2.
What I need is to include a condition that checks if the column G does not contain a certain value. In that case I would like a MsgBox to display "Check..".
The interested range in the Sheet 1 is (A3:J50), so the condition would interest cells G3 to G50.
My current code is:
Sub kk()
Dim lastrow As Integer
lastrow = [b50].End(xlUp).Row
Range("b3:J" & lastrow).Copy Sheets("Daily Rec.").Range("b" & Sheets("Daily Rec.").[b1000].End(xlUp).Row + 1)
Range("b3:j" & lastrow).ClearContents
MsgBox ("Date Posted")
Sheets("Daily Rec.").Activate
MsgBox ("Check..")
End Sub
please advice
This should help get you started.
But like others have mentioned, we need more info to help.
Sub Okay()
Dim source As Range
Dim target As Range
Dim found As Range
Dim cell As Range
Set source = ThisWorkbook.Worksheets("Sheet 1").Range("A3:J50")
Set target = ThisWorkbook.Worksheets("Sheet 2").Range("G3:G50")
For Each cell In source.Cells
Set found = target.Find(cell.Value)
If found Is Nothing Then
MsgBox "Check.." & vbNewLine _
& "Cell [" & cell.Address(0, 0) & "] on sheet [" & cell.Parent.Name & "]" _
& vbNewLine _
& "was not found within " & vbNewLine _
& "cell range of [" & target.Address(0, 0) & "] on sheet [" & target.Parent.Name & "]"
End If
Next cell
End Sub

Copy data to new workbook and add specific text to each row´s value in a specific column

I am exporting data from one workbook to another workbook to T13:Tlastrow
This data, from column F in my workbook where I run this macro, I want to be put into {nyckel="TEXT HERE";} in column T in the "new" workbook, starting from row 13 (T13).
I am stuck here. So would really appreciate some help/solution. Thanks!
Sub CopyData()
Dim wkbCurrent As Workbook, wkbNew As Workbook
Set wkbCurrent = ActiveWorkbook
Dim valg, c, LastCell As Range
Set valg = Selection
Dim wkbPath, wkbFileName, lastrow As String
Dim LastRowInput As Long
Dim lrow, rwCount, lastrow2, LastRowInput2 As Long
Application.ScreenUpdating = False
' If nothing is selected in column A
If Selection.Columns(1).Column = 1 Then
wkbPath = ActiveWorkbook.Path & "\"
wkbFileName = Dir(wkbPath & "CIF LISTEN.xlsm")
Set wkbNew = Workbooks.Open(wkbPath & "CIF LISTEN.xlsm")
'Application.Run ("'C:\Users\niclas.madsen\Desktop\TEST\CIF LISTEN.xlsm'!DelLastRowData")
LastRowInput = Cells(Rows.count, "A").End(xlDown).Row
For Each c In valg.Cells
lrow = wkbNew.Worksheets(1).Range("B1").Offset(wkbNew.Worksheets(1).Rows.count - 1, 0).End(xlUp).Row + 1
lastrow2 = Range("A" & Rows.count).End(xlUp).Row
lastrow3 = Range("T" & Rows.count).End(xlUp).Row
wkbCurrent.ActiveSheet.Range("E" & c.Row).Copy Destination:=wkbNew.Worksheets(1).Range("A" & lrow)
wkbCurrent.ActiveSheet.Range("A" & c.Row).Copy Destination:=wkbNew.Worksheets(1).Range("B" & lrow)
wkbCurrent.ActiveSheet.Range("F" & c.Row).Copy Destination:=wkbNew.Worksheets(1).Range("T" & lrow)
' Standard inputs
wkbNew.Worksheets(1).Range("D13:D" & lastrow2).Value = "Ange referens och period"
wkbNew.Worksheets(1).Range("E13:E" & lastrow2).Value = "99999002"
wkbNew.Worksheets(1).Range("G13:G" & lastrow2).Value = "EA"
wkbNew.Worksheets(1).Range("H13:H" & lastrow2).Value = "2"
wkbNew.Worksheets(1).Range("M13:M" & lastrow2).Value = "SEK"
wkbNew.Worksheets(1).Range("N13:N" & lastrow2).Value = "sv_SE"
wkbNew.Worksheets(1).Range("P13:P" & lastrow2).Value = "TRUE"
wkbNew.Worksheets(1).Range("Q13:Q" & lastrow2).Value = "TRUE"
wkbNew.Worksheets(1).Range("S13:S" & lastrow2).Value = "Catalog_extensions"
'wkbNew.Worksheets(1).Range("T" & lastrow3).Value = "{Nyckelord=" & wkbNew.Worksheets(1).Range("T" & lastrow3).Value & ";}"
Next
' Trying to get this to work
LastRowInput2 = wkbNew.Worksheets(1).Range("T" & wkbNew.Sheets("Sheet1").UsedRange.Rows.count + 1).End(xlUp).Row
For i = 0 To LastRowInput2 - 13
wkbNew.Worksheets(1).Range("T" & 13 + i).Value = "{Nyckelord=" & wkbNew.Worksheets(1).Range("T" & 13 + i).Value & ";}"
Next i
' END HERE
' wkbNew.Close False
' Find the number of rows that is copied over
wkbCurrent.ActiveSheet.Activate
areaCount = Selection.Areas.count
If areaCount <= 1 Then
MsgBox "The selection contains " & Selection.Rows.count & " suppliers."
' Write it in A10 in CIF LISTEN
wkbNew.Worksheets(1).Range("A10").Value = "COMMENTS: " & Selection.Rows.count & " Suppliers Added"
Else
i = 1
For Each A In Selection.Areas
'MsgBox "Area " & I & " of the selection contains " & _
a.Rows.count & " rows."
i = i + 1
rwCount = rwCount + A.Rows.count
Next A
MsgBox "The selection contains " & rwCount & " suppliers."
' Write it in A10 in CIF LISTEN
wkbNew.Worksheets(1).Range("A10").Value = "COMMENTS: " & rwCount & " Suppliers Added"
End If
wkbNew.Worksheets(1).Activate
Application.ScreenUpdating = True
Else
MsgBox "Please select cell(s) in column A", vbCritical, "Error"
Exit Sub
End If
End Sub
OK Try
wkbNew.Worksheets(1).Range("T" & lrow).Value = "{Nyckelord=" & wkbCurrent.ActiveSheet.Range("F" & c.Row).Value & "}"
Instead of your line:
wkbCurrent.ActiveSheet.Range("F" & c.Row).Copy Destination:=wkbNew.Worksheets(1).Range("T" & lrow)
And remove the whole block marked 'Trying to get this to work
If the code is doing the right action but on the wrong cells, then the problem is in the start and end of the For loop. Your For Loop is going from row '13 + i' where i = 0 (so row 13), to row 13 + LastRowInput2 - 13 (so LastRowInput2). This seems right to me, so the problem must be with the value in LastRowInput2.
You need to correct this line:
LastRowInput2 = wkbNew.Worksheets(1).Range("T" & wkbNew.Sheets("Sheet1").UsedRange.Rows.count + 1).End(xlUp).Row
So that is gives you the correct last row input in your data. There are several approaches to finding the end of data depending on whether there may be blank cells in the middle and other factors. This may be one option:
LastRowInput2 = wkbNew.Worksheets(1).Range("T65000").End(xlUp).Row
Be sure to step through the code and verify that LastRowInput2 is set to the value you expect and then this should work.

Get specific values from an range and store it in another

I'm trying to type a search term and look into a entire specific range and every time this term has a match the information will be stored in another column.
When I use "Do", "With" or "While" it just stores one result.
Sub MethodFindAllSamples()
Dim rng1 As Range
Dim strSearch As String
index = 11
strSearch = InputBox("Type the model you are looking for, please: ")
Set rng1 = Range("G:G").Find(strSearch, , xlValues, xlPart, xlByRows, False)
If Not rng1 Is Nothing Then
Application.Goto rng1
Model = ActiveCell(1.1)
Content = ActiveCell(1, 4)
FIssues = Range("ER" & ActiveCell.Row + 1).Value
TIssues = Range("ER" & ActiveCell.Row + 1).Value
MsgBox "Model selected: " & Model & vbNewLine & "CS: " & Content & vbNewLine & " Issues found: " & FIssues
Errors = Left(FIssues, 1)
Errors2 = Mid(TIssues, 22, 1)
Cells(index, 1).Value = Mid(Model, 4, 6)
Cells(index, 3).Value = Errors
Cells(index, 4).Value = Errors2
Cells(index, 2).Value = strSearch + Left(Content, 8)
Else
MsgBox strSearch & " This device can't be found, please try again"
End If
End Sub
this an example how you can achieve this
Sub MethodFindAllSamples()
Dim oCell As Range, i&, z&, strSearch$
strSearch = InputBox("Type the model you are looking for, please: ")
i = Cells(Rows.Count, "G").End(xlUp).Row
z = 0
If strSearch <> "" Then
For Each oCell In Range("G1:G" & i)
If Replace(Trim(UCase(oCell.Value)), " ", "") Like "*" & Replace(Trim(UCase(strSearch)), " ", "") & "*" Then
z = z + 1
End If
Next
If z > 0 Then
MsgBox "Range [D] contain: " & z & " iteration of the selected model : " & strSearch
Else
MsgBox "Range [D] does not contain: " & strSearch
End If
Else
MsgBox "Search model not specified!"
End If
End Sub