Microsoft VBA Error - Run time Error - 1004 - excel

Run-time error '1004': The PivotTable field name is not valid. To create a PivotTable report you must use data that is organized as a list of labeled columns. If you are changing the name of a PivotTable field, you must type a new name for the field.
Here Is my Code?
Please tell me the mistake so I can understand it. also How Can I Correct it?
Option Explicit
Public PageName, RowName, ColumnName, DataName As String
Sub ShowForms()
frmGenerateReports.Show
End Sub
Sub CreatePivot()
Dim Destination, RangeData As Range
Set Destination = Worksheets("Reports").Range("A1")
Set RangeData = Range("A1", Range("I1").End(xlDown))
ActiveWorkbook.PivotCaches.Create _
(SourceType:=xlDatabase, SourceData:=RangeData) _
.CreatePivotTable TableDestination:=Destination, TableName:="SalesPivot"
End Sub
Sub SetFields()
Dim PvtTable As PivotTable
Set PvtTable = Worksheets("Reports").PivotTables("SalesPivot")
With PvtTable
.PivotFields(PageName).Orientation = xlPageField
.PivotFields(RowName).Orientation = xlRowField
.PivotFields(ColumnName).Orientation = xlColumnField
.PivotFields(DataName).Orientation = xlDataField
End With
ActiveWorkbook.Sheets("Reports").Activate
If frmGenerateReports.Sales <> "Model" Then
PvtTable.PivotSelect "", xlDataOnly
Selection.NumberFormat = "$#, ##0"
End If
Range("E1").Select
End Sub
Sub ConsolidateData(ThisMonth)
Dim BeenThere As Boolean
Dim Compare As String
Dim Sheet As Worksheet
BeenThere = False
Sheets.Add
ActiveSheet.Name = "Reports"
If frmGenerateReports.Period = "Month" Then
Select Case ThisMonth
Case "Jan"
ThisMonth = 1
Case "Feb"
ThisMonth = 2
Case "Mar"
ThisMonth = 3
Case "Apr"
ThisMonth = 4
Case "May"
ThisMonth = 5
Case "Jun"
ThisMonth = 6
Case "Jul"
ThisMonth = 7
Case "Aug"
ThisMonth = 8
Case "Sep"
ThisMonth = 9
Case "Oct"
ThisMonth = 10
Case "Nov"
ThisMonth = 11
Case "Dec"
ThisMonth = 12
End Select
End If
Select Case frmGenerateReports.Period
Case "Month"
For Each Sheet In Worksheets
Sheet.Select
Compare = ActiveSheet.Name
On Error Resume Next
Compare = Month(CDate(Compare))
If Compare = ThisMonth Then
frmGenerateReports.StartDate = Sheet.Name
If BeenThere = False Then
GrabCells 1
BeenThere = True
Else
GrabCells 2
DoEvents
End If
End If
Next
Case "All"
GrabCells 1
Do
frmGenerateReports.StartDate = frmGenerateReports.StartDate + 1
GrabCells 2
DoEvents
Loop Until frmGenerateReports.StartDate = frmGenerateReports.EndDate
Columns("A:J").EntireColumn.AutoFit
Range("A1").Select
Case "Other"
GrabCells 1
Do
frmGenerateReports.StartDate = frmGenerateReports.StartDate + 1
GrabCells 2
DoEvents
Loop Until frmGenerateReports.StartDate = frmGenerateReports.EndDate
Columns("A:J").EntireColumn.AutoFit
Range("A1").Select
End Select
End Sub
Sub GrabCells(StartingCell)
Dim CallDate, Where, Where2 As String
CallDate = Format(frmGenerateReports.StartDate, "d-mmm-yy")
Sheets(CallDate).Select
If Range("A2").Value <> Empty Then
Where = "B" & StartingCell
Where2 = "J" & StartingCell
Range(Where, Range(Where2).End(xlDown)).Select
Application.CutCopyMode = False
Selection.Copy
Range("A1").Select
Sheets("Reports").Select
ActiveSheet.Paste
Range("A1").End(xlDown).Offset(1).Select
Else
If StartingCell = 1 Then
Application.CutCopyMode = False
Range("B1:J1").Select
Selection.Copy
Sheets("Reports").Select
ActiveSheet.Paste
Range("A2").Select
End If
End If
End Sub
Sub FinishReport()
Dim Sheet As Worksheet
Workbooks.Open Filename:=ThisWorkbook.Path & "\Reports.xlsx"
For Each Sheet In Worksheets
Sheet.Select
Cells.Select
Selection.Clear
Range("A1").Select
Next
Workbooks("Sales - Fiscal Year1.xlsm").Activate
Sheets("Reports").Select
Cells.Select
Selection.Copy
Workbooks("Reports.xlsx").Activate
ActiveSheet.Paste
Range("A1").Select
Windows("Sales - Fiscal Year1.xlsm").Activate
Application.CutCopyMode = False
ActiveWindow.SelectedSheets.Delete
Workbooks("Reports.xlsx").Activate
CreatePivot
SetFields
End Sub
I need to understand the logic behind the solution and why it caused?
So that I can prevent it from happening next time.

Related

I want the VisibleDropDown to be showing after moving data from one sheet to the other

With the code below I'm moving data from one sheet to the other. in the title I want arrow of autofilter to be visible/showing, so I can filter every column after moving the data.
I want to be able to filter the columns of all moved data.
Private Sub cmdLoad_Click()
Dim wsName As String
Dim mySh As Worksheet
Dim newsh As Worksheet
Set newsh = ThisWorkbook.Sheets("rapport")
Set mySh = ThisWorkbook.Sheets("Rapportbron")
Dim countselected As Integer: countselected = 0
Dim col_name As String
Dim col_count As Integer: col_count = 4
Application.ScreenUpdating = False
newsh.Unprotect
newsh.Cells.Clear
newsh.Columns("D:Z").EntireColumn.Delete
newsh.Columns.UseStandardWidth = True
newsh.Rows.UseStandardHeight = True
newsh.Rows.RowHeight = 15
newsh.Columns.ColumnWidth = 8.71
For i = 0 To Me.ListBox2.ListCount - 1
If Me.ListBox2.Selected(i) Then
col_name = Me.ListBox2.List(i)
countselected = countselected + 1
For a = 1 To mySh.Cells(1, Columns.Count).End(xlToLeft).Column
If mySh.Cells(1, a).Value = col_name Then
'copy the data from raw to new worksheet created
For b = 1 To mySh.Cells(Rows.Count, a).End(xlUp).Row
newsh.Cells(b, col_count).Value = mySh.Cells(b, a).Value
'Autofit Columns
newsh.Cells.EntireColumn.AutoFit
'Format Table Headers
newsh.Cells(1, col_count).Resize(1, 1).Interior.Color = RGB(233, 233, 233)
newsh.Cells(1, col_count).Resize(1, 1).Font.Bold = True
newsh.Cells(1, col_count).Resize(1, 1).HorizontalAlignment = xlCenter
newsh.Cells(1, col_count).Resize(1, 1).VerticalAlignment = xlBottom
Next b
col_count = col_count + 1
End If
Next a
End If
Next i
Application.ScreenUpdating = True
MsgBox "Data Loaded", vbInformation
newsh.Activate
newsh.Range("C2:G6").Select
Selection.Locked = False
Selection.FormulaHidden = False
newsh.Protect DrawingObjects:=True, Contents:=True, Scenarios:=True _
, AllowFormattingCells:=True, AllowFormattingColumns:=True, _
AllowFormattingRows:=True, AllowSorting:=True, AllowFiltering:=True, _
AllowUsingPivotTables:=True
newsh.Range("D5").Select
End
End Sub

VBA and Excel optimization of processing time, dealing with several rows

Hello StackOverflowers,
I need som help here.
I have been working on a VBA code but it is taking around 20 to 30 mins to process the data and I need some advise to reduce the amount the processing time.
I have 3 sheets in the document.
1- Sheet 1 is called "ExtractData".
That sheet contains 3 columns:
Column A: contains "Environment: PROD, Pre-Prod & UAT", responsible fetching the data based on the environment stated in the dropdown list.
That column contains also a possibility to parse the html text contained in some cells
Column B: Contain list of Product Code
Column C: contains name of fields / attribute for which we need the data for.
Also, we have a button in that sheet that should run the code to fetch the data and display them in sheet called "Source Data"
2- Sheet 2: Called "DataReview", containing extracted data, then I copy data content from cell A2:MJ500 and paste it in sheet 3 (Source Data) that contains some predefined headers.
So I paste data from A4
3- Sheet 3 called: "Source Data"
That sheet will display all data fetched based on the stated attribute
CASE 1: What I am supposed to do, is to filter the data based on some variable and transpose them in a separate sheet:
Exemple 1: May via a VBA buttong, I select specific attribute, like filter based on "Product Family", when you click run, it will copy the data,
then transpose them in a specific way in a separate sheet named after the Product family name
BUT, I tried, different ways and I am not getting what I wanted.
Below find the code I am using, please go through it and help me make it better.
Function Get_File(Enviromment As String, Pos_row As Integer, Data_date As String) As String
Dim objRequest As Object
Dim blnAsync As Boolean
Dim strResponse As String
Dim Token As String
Dim Url As String
Dim No_product_string As String
Token = "xxxxxxxx"
Url = CreateURL(Enviromment, Pos_row, Data_date)
Set objRequest = CreateObject("MSXML2.XMLHTTP")
blnAsync = True
With objRequest
.Open "GET", Url, blnAsync
.SetRequestHeader "Content-Type", "application/json"
.SetRequestHeader "x-auth-token", "xxxxxxxx"
.Send
'spin wheels whilst waiting for response
While objRequest.ReadyState <> 4
DoEvents
Wend
strResponse = .ResponseText
End With
Debug.Print strResponse
Get_File = strResponse
End Function
Function CreateURL(Enviroment As String, Pos_row As Integer, Data_date As String)
Dim product_code As String
If (StrComp(Enviroment, "UAT", vbTextCompare) = 0) Then
CreateURL = "https://TEST1-uat.Nothing.net:8096/api/products/hierarchies"
ElseIf (StrComp(Enviroment, "PPROD", vbTextCompare) = 0) Then
CreateURL = "https://TEST1-pprod.nothing.net:8096/api/products/hierarchies"
ElseIf (StrComp(Enviroment, "PROD", vbTextCompare) = 0) Then
CreateURL = "https://TEST1.nothing.net:8096/api/products/hierarchies"
Else
CreateURL = "https://TEST1.nothing.net:8096/api/products/hierarchies"
End If
If Pos_row <> -1 Then
product_code = ThisWorkbook.Sheets("DataReview").Cells(Pos_row, 1)
CreateURL = CreateURL & "?query=%7B%22productCode%22%3A%22" & product_code & "%22%7D"
End If
If Not (Trim(Data_date & "") = "") Then
CreateURL = Left(CreateURL, Len(CreateURL) - 3) & "%2C%22date%22%3A%22" & Data_date & "%22%7D"
End If
End Function
Function Get_value(Json_file As String, Field_name As String, Initial_value As String, Current_amount_values As Integer) As String
Dim tempString As String
Dim Value As String
Dim Field_name_temp As String
Field_name_temp = "my_" & Field_name 'Ensure that field name is not subset of other field name
Value = Initial_value
Pos_field = InStr(Json_file, Field_name_temp & """:")
tempString = Mid(Json_file, Pos_field + Len(Field_name_temp) + 4)
'MsgBox (Mid(tempString, 1, 75))
If Not StrComp(Left(tempString, 1), "}") Then
Value = Value & "," & ""
Else
Value = Value & "$" & Replace(Split(tempString, "]")(0), """", "")
End If
If Not InStr(tempString, Field_name_temp & """:") = 0 Then
Value = Get_value(tempString, Field_name, Value, Current_amount_values + 1)
End If
Get_value = Value
End Function
Sub Set_value(Value As String, Pos_col As Integer, Pos_row As Integer, Pos_row_max As Integer)
Dim i As Integer
Dim HTML As String
HTML = ThisWorkbook.Sheets("ExtractData").Range("A8")
If HTML = "Yes" Or HTML = "" Then
Value = ParseHTML(Value)
End If
If Value <> "" Then
If UBound(Split(Value, "$")) = 0 Then
ThisWorkbook.Sheets("DataReview").Cells(Pos_row, Pos_col).Value = Value
Else
If Pos_row < Pos_row_max And ThisWorkbook.Sheets("DataReview").Cells(Pos_row + 1, 1) <> "" Then
ThisWorkbook.Sheets("DataReview").Cells(Pos_row, Pos_col).Value = Split(Value, "$")(0)
For i = 1 To UBound(Split(Value, "$"))
ThisWorkbook.Sheets("DataReview").Cells(Pos_row, Pos_col).Offset(1).EntireRow.Insert
ThisWorkbook.Sheets("DataReview").Cells(Pos_row + 1, Pos_col).Value = Split(Value, "$")(i)
Next i
End If
ThisWorkbook.Sheets("DataReview").Cells(Pos_row, Pos_col).Value = Split(Value, "$")(0)
For i = 1 To UBound(Split(Value, "$"))
ThisWorkbook.Sheets("DataReview").Cells(Pos_row + i, Pos_col).Value = Split(Value, "$")(i)
Next i
End If
End If
End Sub
Public Function ParseHTML(ByVal Value As String) As String
Dim htmlContent As New HTMLDocument
htmlContent.body.innerHTML = Value
ParseHTML = htmlContent.body.innerText
End Function
Sub Main_script()
Dim Pos_col As Integer, Pos_row As Integer, Json_file As String, Field_name As String
Dim Value As String
Dim i As Integer
Dim tempValue As String
Dim Pos_row_max As Integer
Dim Enviromment As String
Dim Data_date As String
Pos_col = 2
Pos_row = 2
Call Prepare_sheet
Data_date = Format(ThisWorkbook.Sheets("ExtractData").Range("A5"), "YYYY-MM-DD")
Enviromment = ThisWorkbook.Sheets("ExtractData").Range("A2")
Do While Not IsEmpty(ThisWorkbook.Sheets("DataReview").Cells(Pos_row, 1).Value)
Json_file = Get_File(Enviromment, Pos_row, Data_date)
Do While Not IsEmpty(ThisWorkbook.Sheets("DataReview").Cells(1, Pos_col).Value)
Field_name = ThisWorkbook.Sheets("DataReview").Cells(1, Pos_col).Value
Value = Mid(Get_value(Json_file, Field_name, "", 0), 2) 'Mid() is used to remove "," from the front of values
Pos_row_max = Application.Max(Pos_row_max, Pos_row + UBound(Split(Value, "$")))
Call Set_value(Value, Pos_col, Pos_row, Pos_row_max)
Pos_col = Pos_col + 1
Loop
Pos_col = 2
Pos_row = Pos_row_max + 1
Loop
ThisWorkbook.Sheets("DataReview").Activate
'Columns.AutoFit
'Rows.AutoFit
Cells.Select
Selection.ColumnWidth = 32
Selection.RowHeight = 15
ThisWorkbook.Sheets("DataReview").Range("A2:HM10000").Select
Selection.Copy
Sheets("Source Data").Select
Sheets("Source Data").Range("A4:HM14000").Select
ActiveSheet.Paste
ThisWorkbook.Sheets("Source Data").Activate
End Sub
Sub Prepare_sheet()
Dim i As Integer
Dim j As Integer
i = 2
j = 2
ThisWorkbook.Sheets("DataReview").Range("A1:HH10000").ClearContents
Do While ThisWorkbook.Sheets("ExtractData").Cells(i, 2).Value <> ""
ThisWorkbook.Sheets("DataReview").Cells(i, 1).Value = ThisWorkbook.Sheets("ExtractData").Cells(i, 2).Value
i = i + 1
Loop
Do While ThisWorkbook.Sheets("ExtractData").Cells(j, 3).Value <> ""
ThisWorkbook.Sheets("DataReview").Cells(1, j).Value = ThisWorkbook.Sheets("ExtractData").Cells(j, 3).Value
j = j + 1
Loop
ThisWorkbook.Sheets("DataReview").Cells(1, 1).Value = "Product_code"
End Sub
Sub Insert_product_codes(Value As String)
For i = 1 To UBound(Split(Value, ","))
ThisWorkbook.Sheets("Data").Cells(i, 1).Value = Split(Value, ",")(i)
Next i
End Sub
Module 1 (Containing most of the code):
Module 2 (To transpose data): Here I transpose Data from "Source Data" sheet into "Report" sheet that contains some predefined values in column A
Sub Transpose_Data()
'
' Transpose_Data Macro
'
'
Sheets("Source Data").Select
Rows("4:500").Select
Selection.Copy
Sheets("QRA Report Main").Select
Range("B4").Select
Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:= _
False, Transpose:=True
Range("B6:MJ6").Select
Application.CutCopyMode = False
Selection.Insert Shift:=xlDown
Range("B12:MJ12").Select
Selection.Insert Shift:=xlDown
Selection.Insert Shift:=xlDown
Range("B17:MJ17").Select
Selection.Insert Shift:=xlDown
Selection.Insert Shift:=xlDown
Range("B23:MJ23").Select
Selection.Insert Shift:=xlDown
Selection.Insert Shift:=xlDown
Range("B28:MJ28").Select
Selection.Insert Shift:=xlDown
Selection.Insert Shift:=xlDown
Range("B36:MJ36").Select
Selection.Insert Shift:=xlDown
Selection.Insert Shift:=xlDown
Range("B45:MJ45").Select
Selection.Insert Shift:=xlDown
Selection.Insert Shift:=xlDown
Range("B51:MJ51").Select
Selection.Insert Shift:=xlDown
Selection.Insert Shift:=xlDown
Range("B54:MJ54").Select
Selection.Insert Shift:=xlDown
Selection.Insert Shift:=xlDown
Range("B61:MJ61").Select
Selection.Insert Shift:=xlDown
Selection.Insert Shift:=xlDown
Columns("B:NZ").Select
Range("B3").Activate
Selection.ColumnWidth = 30
With Selection
.HorizontalAlignment = xlRight
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
End With
ActiveWorkbook.Save
End Sub
But again as i said, I do not get exactly what I need plus, the processing time is huge.
Try this, but note you'll need to fill in the section in the middle.
``
Sub Transpose_Data()
'
' Transpose_Data Macro
'
'
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
Sheets("Source Data").Rows("4:500").Copy Sheets("QRA Report Main").Range("B4")
With Sheets("QRA Report Main")
.Range("B6:MJ6").Insert Shift:=xlDown
.Range("B12:MJ12").Resize(2).Insert Shift:=xlDown
.Range("B17:MJ17").Resize(2).Insert Shift:=xlDown
.Range("B23:MJ23").Resize(2).Insert Shift:=xlDown
' add rest in here
.Range("B61:MJ61").Resize(2).Insert Shift:=xlDown
With .Columns("B:NZ")
.ColumnWidth = 30
.HorizontalAlignment = xlRight
.WrapText = False
.Orientation = 0
.AddIndent = False
.IndentLevel = 0
.ShrinkToFit = False
.ReadingOrder = xlContext
End With
End With
ActiveWorkbook.Save
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
End Sub
``

Selecting column range with specific header

I have a macro code but it runs on specific column and on range of 500 only. I wish it should dynamically select column of header 'PRODUCTS' is present. if possible can we increase the limit of 500 to all the data present in column 'PRODUCTS'.
Sub Pats()
myCheck = MsgBox("Do you have Patent Numbers in Column - B ?", vbYesNo)
If myCheck = vbNo Then Exit Sub
endrw = Range("B500").End(xlUp).Row
Application.ScreenUpdating = False
For i = 2 To endrw
PatNum = Cells(i, 2).Value
If Left(Cells(i, 2), 2) = "US" Then
link = "http://www.google.com/patents/" & PatNum
Cells(i, 2).Select
ActiveSheet.Hyperlinks.Add Anchor:=Selection, Address:="http://www.google.com/patents/" & PatNum, ScreenTip:="Click to View", TextToDisplay:=PatNum
With Selection.Font
.Name = "Arial"
.Size = 10
End With
ElseIf Left(Cells(i, 2), 2) = "EP" Then
link = "http://www.google.com/patents/" & PatNum
Cells(i, 2).Select
ActiveSheet.Hyperlinks.Add Anchor:=Selection, Address:="http://www.google.com/patents/" & PatNum, ScreenTip:="Click to View", TextToDisplay:=PatNum
With Selection.Font
.Name = "Arial"
.Size = 10
End With
End If
Next i
End Sub
I would first extract the link building part into a separate subroutine ...
Sub AddLink(c As Range)
Dim link As String
Dim patNum As String
Dim test As String
patNum = c.Value
test = UCase(Left(patNum, 2))
If test = "US" Or test = "EP" Then
link = "http://www.google.com/patents/" & patNum
Else
link = "http://www.www.hyperlink.com/" & patNum
End If
c.Hyperlinks.Add Anchor:=c, Address:=link, ScreenTip:="Click to View", TextToDisplay:=patNum
With c.Font
.Name = "Arial"
.Size = 10
End With
End Sub
Then I would add a function to find the column...
Function FindColumn(searchFor As String) As Integer
Dim i As Integer
'Search row 1 for searchFor
FindColumn = 0
For i = 1 To ActiveSheet.Cells.SpecialCells(xlCellTypeLastCell).Column
If ActiveSheet.Cells(1, i).Value = searchFor Then
FindColumn = i
Exit For
End If
Next i
End Function
Finally I would put it all together ...
Sub Pats()
Dim col As Integer
Dim i As Integer
col = FindColumn("PRODUCTS")
If col = 0 Then Exit Sub
For i = 2 To ActiveSheet.Cells.SpecialCells(xlCellTypeLastCell).Row
AddLink ActiveSheet.Cells(i, col)
Next i
End Sub
I'll admit I have to use SO to remind myself how to get the last used cell on a worksheet (see Find Last cell from Range VBA).
The code below will find which column has the header PRODUCTS and then find the last row in that column and store it in variable lrProdCol.
Sub FindProductLR()
Dim col As Range
Dim endrw As Long
Set col = Rows(1).Find("PRODUCTS")
If Not col Is Nothing Then
endrw = Cells(Rows.count, col.Column).End(xlUp).Row
Else
MsgBox "The 'PRODUCTS' Column was not found in row 1"
End If
End Sub
So replace the following bit of code
myCheck = MsgBox("Do you have Patent Numbers in Column - B ?", vbYesNo)
If myCheck = vbNo Then Exit Sub
endrw = Range("B500").End(xlUp).Row
With the lines above. Hope that helps

How do I move more than one row when multiple cells match my selection? (Excel VBA)

Good morning. I have an improvement I would like to make to an existing product I have, but am not sure how to get it working. In my product, an end-user can double-click anywhere on a row, and a before-doubleclick event makes a userform appear asking which other sheet they'd like to move that row to. It transfers the data over, removes it from the original sheet, and we're all good. This works fine. What I'd like it to do is to look at the values in column "A" and Column "I" of the selected row, and move any other rows where those values match as well - this would save my users a ton of time not having to do it one row at a time, as there can be dozens of matches at times. The code I have for moving the single row is as such:
`Private Sub CommandButton1_Click()
Dim LastRowTarget As Long
Dim DestSheet As String
Dim ListChoice As String
Dim BLPL As String
If OptionButton1.Value = True Then ListChoice = "White"
If OptionButton2.Value = True Then ListChoice = "Black"
If ListChoice = "White" Then
If OptionButton3.Value = True Then DestSheet = OptionButton3.Caption & " Whitelist"
If OptionButton4.Value = True Then DestSheet = OptionButton4.Caption & " Whitelist"
If OptionButton5.Value = True Then DestSheet = OptionButton5.Caption & " Whitelist"
If OptionButton6.Value = True Then DestSheet = OptionButton6.Caption & " Whitelist"
Else
If OptionButton3.Value = True Then BLPL = OptionButton3.Caption
If OptionButton4.Value = True Then BLPL = OptionButton4.Caption
If OptionButton5.Value = True Then BLPL = OptionButton5.Caption
If OptionButton6.Value = True Then BLPL = OptionButton6.Caption
If OptionButton7.Value = True Then BLPL = OptionButton7.Caption
End If
If OptionButton1.Value = True Then
ActiveSheet.Unprotect Password:=********
Sheets(DestSheet).Unprotect Password:=********
LastRowTarget = Sheets(DestSheet).Range("A" & Rows.Count).End(xlUp).Row
Selection.EntireRow.Copy Destination:=Worksheets(DestSheet).Range("A" & LastRowTarget + 1)
Selection.EntireRow.Delete
Sheets(DestSheet).Protect (********), DrawingObjects:=True, Contents:=True, Scenarios:=True, AllowSorting:=True, AllowFiltering:=True
Else
ActiveSheet.Unprotect Password:=********
Sheets("Blacklist").Unprotect Password:=********
LastRowTarget = Sheets("Blacklist").Range("A" & Rows.Count).End(xlUp).Row
Selection.EntireRow.Copy Destination:=Worksheets("Blacklist").Range("A" & LastRowTarget + 1)
Sheets("Blacklist").Cells(LastRowTarget + 1, 20).Value = BLPL
Selection.EntireRow.Delete
Sheets("blacklist").Protect (********), DrawingObjects:=True, Contents:=True, Scenarios:=True, AllowSorting:=True, AllowFiltering:=True
End If
Unload Me
End Sub`
I would love to attach the workbook itself for you to see what I'm talking about, but unfortunately it's full of classified data. Apologies, and thanks for your time - this website has been an absolute gold mine for me to brute-force my way into learning this stuff.
Replace the following
Selection.EntireRow.Copy Destination:=Worksheets(DestSheet).Range("A" & LastRowTarget + 1)
Selection.EntireRow.Delete
with a loop
'Remember the values to compare
dim columnAValue
dim columnIValue
columnAValue=selection.entirerow.cells(1,"A").Value
columnIValue=selection.entirerow.cells(1,"I").Value
dim currentRow as long
'dont know where your list starts
'Start from the end so currentRow stays correct if someting is deleted
for currentRow = Activesheet.Range("A" & Rows.Count).End(xlUp).Row to ? Step -1
'Do you mean both have to be the same or only one? If only one replace "and" with "or"
If Activesheet.Cells(currentRow,"A").Value = columnAValue and Activesheet.Cells(currentRow,"I").Value = columnIValue then
ActiveSheet.Rows(currentRow).Copy Destination:=Worksheets(DestSheet).Range("A" & LastRowTarget + 1)
ActiveSheet.Rows(currentRow).Delete
'Update last row target
LastRowTarget =LastRowTarget +1
end if
next
do something similar with
Selection.EntireRow.Copy Destination:=Worksheets("Blacklist").Range("A" & LastRowTarget + 1)
Sheets("Blacklist").Cells(LastRowTarget + 1, 20).Value = BLPL
Selection.EntireRow.Delete

Visual Basic Excel Macro MessageBox.Show Throws "Object Required" Error

Simply put no matter how hard I try I cannot get a MessageBox to appear through my Excel macro.
Here is the line I have so far:
MyBox = MessageBox.Show("Stuff", "Title")
When I run this macro I get the following error:
Run-time error '424':
Object required
What's going on!?!?
Here is the complete code:
Sub ImportParser()
'
' ImportParser Macro
' By: Dennis Plotnik (July 2013)
'
Dim ToKeepSize As Integer ' Size of ToKeep array
Dim BlankCount As Integer ' Counts blank lines so as to stop execution after EOF
Dim ReqText As String ' Required String
ReqText = "Import Control"
BlankCount = 0
ToKeepSize = -1
' Dim ToKeep As String()
Dim ToKeep() As String ' Array to store names of tables that include required text
Dim CurrentTable As String ' String to store last required table name
Range("B1").Select
Do
Do ' Go down until come to non-blank row (or exit if all blank)
Selection.Offset(1, 0).Select
Dim tempS As String
tempS = "'" + ActiveCell.Formula
ActiveCell.Value = tempS
If ActiveCell.Value = "" Then
BlankCount = BlankCount + 1
Else
Exit Do
End If
Loop Until BlankCount > 15
If InStr(1, ActiveCell.Value, ReqText, vbTextCompare) > 0 Then ' Check for ReqText in current cell
' ActiveCell.Value = "HELLO!" ' For DEBUG purposes
ToKeepSize = ToKeepSize + 1 ' Increment size of array (to allow for new value)
ReDim Preserve ToKeep(ToKeepSize)
Selection.Offset(0, -1).Select ' Move left to retrieve name of table (category)
CurrentTable = ActiveCell.Value
ToKeep(ToKeepSize) = CurrentTable
For j = 0 To 10000
Selection.Offset(1, 0).Select ' Cycle down until new table is reached
Do
If ActiveCell.Value = "" Then
BlankCount = BlankCount + 1
Selection.Offset(1, 0).Select
Else
Exit Do
End If
Loop Until BlankCount > 15
If ActiveCell.Value <> CurrentTable Then
Selection.Offset(-1, 1).Select ' Return to Field Name to continue search for ReqText
Exit For
End If
Next j
End If
Loop Until BlankCount > 15
' Range("F1").Select ' Print found tables [FOR DEBUG]
' For i = 0 To ToKeepSize
' ActiveCell.Value = ToKeep(i)
' Selection.Offset(1, 0).Select
' Next i
' ActiveCell.Value = CStr(ToKeepSize)
For i = 0 To 1 ' Prepare Table for Flag Columns
Range("A1").EntireColumn.Insert
Next i
Range("A1").Select
ActiveCell.Value = "Import Controlled?"
Range("B1").Select
ActiveCell.Value = "Delete it?"
Columns("A:F").AutoFit
BlankCount = 0
Dim ImportControl As Boolean
ImportControl = False
Range("C1").Select
Do ' Flag necessary columns
Selection.Offset(1, 0).Select
If ActiveCell.Value = "" Then
BlankCount = BlankCount + 1
Else
For i = 0 To ToKeepSize
If ActiveCell.Value = ToKeep(i) Then
Selection.Offset(0, -2).Value = 1
Exit For
End If
Next i
End If
Loop Until BlankCount > 15
Range("A1").Select ' Sort to push all required tables to top of file
Columns("A:A").Select
ActiveSheet.Sort.SortFields.Clear
ActiveSheet.Sort.SortFields.Add Key:=Range("A1"), _
SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveSheet.Sort
.SetRange Range("A:F")
.Header = xlGuess
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
Range("A1").Select
Do
Selection.Offset(1, 0).Select
Loop Until ActiveCell.Value = ""
MyBox = MessageBox.Show("Stuff", "Title")
Dim file As String
file = Application.ActiveWorkbook.Path
Dim Word As Object: Set Word = CreateObject("Word.Application")
Word.Visible = True
Set docWD = Word.Documents.Add
docWD.SaveAs file & "\" & "dictionary", FileFormat:=wdFormatDocument
Range(ActiveCell.Offset(0, 2), "F1").Copy
Word.Selection.Paste
End Sub
MessageBox.Show is VB.Net. Even though you have tagged it as VB.Net, I believe you are doing this in VBA.
Try this
MyBox = MsgBox("Stuff", vbInformation, "Title")

Resources