End vba code if no value found - excel

I am using this code to transfer data from one sheet to another. The code allows for the data being transferred to stay on the new sheet until deleted.
Private Sub Transfer2_Click()
Dim Work_Order1 As String, Qty1 As Integer, Frame1 As String, Qty_Frame1 As Integer
Worksheets("Work_Order").Select
if Worksheets("Work_Order").Range("C12") = "" Then Exit Sub
Work_Order1 = Range("N3")
Qty1 = Range("B3")
Frame1 = Range("C12").Value
Qty_Frame1 = Range("M12")
Worksheets("Order").Select
Worksheets("Order").Range("A4").Select
If Worksheets("Order").Range("A4").Offset(1, 0) <> "" Then
Worksheets("Order").Range("A4").End(xlDown).Select
End If
ActiveCell.Offset(1, 0).Select
ActiveCell.Value = Work_Order1
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = Qty1
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = Frame1
ActiveCell.Offset(0, 2).Select
ActiveCell.Value = Qty_Frame1
Private Sub Transfer2_Click()
Dim Work_Order2 As String, Qty2 As Integer, Frame2 As String, Qty_Frame2 As Integer
Worksheets("Work_Order").Select
if Worksheets("Work_Order").Range("C13") = "" Then Exit Sub
Work_Order2 = Range("N3")
Qty2 = Range("B3")
Frame2 = Range("C13").Value
Qty_Frame2 = Range("M13")
Worksheets("Order").Select
Worksheets("Order").Range("A4").Select
If Worksheets("Order").Range("A4").Offset(1, 0) <> "" Then
Worksheets("Order").Range("A4").End(xlDown).Select
End If
ActiveCell.Offset(1, 0).Select
ActiveCell.Value = Work_Order2
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = Qty2
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = Frame2
ActiveCell.Offset(0, 2).Select
ActiveCell.Value = Qty_Frame2
Private Sub Transfer2_Click()
Dim Work_Order3 As String, Qty3 As Integer, Frame3 As String, Qty_Frame3 As Integer
Worksheets("Work_Order").Select
if Worksheets("Work_Order").Range("C14") = "" Then Exit Sub
Work_Order1 = Range("N3")
Qty3 = Range("B3")
Frame3 = Range("C14").Value
Qty_Frame3 = Range("M14")
Worksheets("Order").Select
Worksheets("Order").Range("A4").Select
If Worksheets("Order").Range("A4").Offset(1, 0) <> "" Then
Worksheets("Order").Range("A4").End(xlDown).Select
End If
ActiveCell.Offset(1, 0).Select
ActiveCell.Value = Work_Order3
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = Qty3
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = Frame3
ActiveCell.Offset(0, 2).Select
ActiveCell.Value = Qty_Frame3
What I am trying to do is end this code is no value is found in the "C" Range. I have the code repeated nine times because there are nine instances where this info can be found, but not all will have values all the time. If that occurs, I want it to end the code before transferring info to the new sheet.
so far I've tried:
if Worksheets("Work_Order").Range("C12")="" Then
Exit sub
But it returns with the error Block if without end if.

By putting the Exit Sub on a different line to the If, you are creating a "Block If", which needs an End If:
If Worksheets("Work_Order").Range("C12")="" Then
Exit sub
End If
If you want to use a "single-line If", you should put your statements on a single line:
If Worksheets("Work_Order").Range("C12")="" Then Exit sub
Both statements work in exactly the same way, but "block Ifs" are usually easier to code when you have multiple statements to be executed within either the True or False leg of the statement.
E.g.
If a = 5 Then
b = 7
c = 10 * a - b
d = 5 + b - c
Else
b = 9
c = 20 * a - 4 * b
d = 6 + b + c
End If
is easier to read than
If a = 5 Then b = 7: c = 10 * a - b: d = 5 + b - c Else b = 9: c = 20 * a - 4 * b: d = 6 + b + c
In response to your comments, I am guessing that you don't actually want to Exit Sub when you hit a blank value, you want to instead go on to process the next range.
This could be done like this:
Private Sub Transfer2_Click()
Dim Work_Order1 As String, Qty1 As Integer, Frame1 As String, Qty_Frame1 As Integer
If Worksheets("Work_Order").Range("C12").Value <> "" Then
Worksheets("Work_Order").Select
Work_Order1 = Range("N3")
Qty1 = Range("B3")
Frame1 = Range("C12").Value
Qty_Frame1 = Range("M12")
Worksheets("Order").Select
Worksheets("Order").Range("A4").Select
If Worksheets("Order").Range("A4").Offset(1, 0) <> "" Then
Worksheets("Order").Range("A4").End(xlDown).Select
End If
ActiveCell.Offset(1, 0).Select
ActiveCell.Value = Work_Order1
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = Qty1
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = Frame1
ActiveCell.Offset(0, 2).Select
ActiveCell.Value = Qty_Frame1
End If
'Then repeat for the next set of cells
which can be rewritten to avoid the use of Select (which leads to so many problems) as
Private Sub Transfer2_Click()
Dim Work_Order1 As String, Qty1 As Integer, Frame1 As String, Qty_Frame1 As Integer
If Worksheets("Work_Order").Range("C12").Value <> "" Then
With Worksheets("Work_Order")
Work_Order1 = .Range("N3")
Qty1 = .Range("B3")
Frame1 = .Range("C12").Value
Qty_Frame1 = .Range("M12")
End With
With Worksheets("Order").Cells(Worksheets("Order").Rows.Count, "A").End(xlUp).Offset(1, 0).EntireRow
.Cells(1, "A").Value = Work_Order1
.Cells(1, "B").Value = Qty1
.Cells(1, "C").Value = Frame1
.Cells(1, "E").Value = Qty_Frame1
End With
End If
'Then repeat for the next set of cells
But it would be best if that was split into two subroutines to avoid a lot of repetitive code:
Private Sub Transfer2_Click()
With Worksheets("Work_Order")
Transfer2_Paste .Range("N3").Value, .Range("B3").Value, .Range("C12").Value, .Range("M12").Value
'Then repeat for the next set of cells, e.g.
'Transfer2_Paste .Range("N4").Value, .Range("B4").Value, .Range("C13").Value, .Range("M13").Value
'etc
End With
End Sub
Private Sub Transfer2_Paste(Work_Order1 As String, Qty1 As Integer, Frame1 As String, Qty_Frame1 As Integer)
If Frame1 = "" Then
Exit Sub
End If
With Worksheets("Order").Cells(Worksheets("Order").Rows.Count, "A").End(xlUp).Offset(1, 0).EntireRow
.Cells(1, "A").Value = Work_Order1
.Cells(1, "B").Value = Qty1
.Cells(1, "C").Value = Frame1
.Cells(1, "E").Value = Qty_Frame1
End With
End Sub

Related

Merge cells with same year in a row

I need to merge the cells one above the months.
Cells Should be merged from 01 to 12 showing year in cell.
Look for the picture for more clarification.
I have below code, but which show months after run in cell row1.
My idea is to convert above cells to years through vba and apply merge same year at the end.
which is shown in desired output.
Note.
ROW 4 and 5 are just my thinking, which will help year to merge.
Dim a(), i As Long, j As Long, m As Long, x As Range
With Range("b1:qaz1")
.MergeCells = False
.ClearContents
a() = .Offset(1).Value
m = Month(a(1, 1))
j = UBound(a, 2)
Set x = .Cells(1)
For i = 2 To j
If m <> Month(a(1, i)) Or i = j Then
With Range(x, .Cells(i - IIf(i = j, 0, 1)))
.MergeCells = True
.HorizontalAlignment = xlCenter
End With
x.Value = Format(DateSerial(2000, m, 1), "MMMM")
m = Month(a(1, i))
Set x = .Cells(i)
End If
Next
End With
End Sub
After running new program output look like
Since you have true dates in your caption row the month and year can be extracted from there. However, the code below converts dates that might have been created using formulas to hard dates before processing them.
Sub MergeCaptionsByYear()
' 031
Const CapsRow As Long = 1 ' change to suit
Const StartClm As Long = 2 ' change to suit
Dim Rng As Range ' working range
Dim Tmp As Variant ' current cell's value
Dim Cl As Long ' last used column
Dim Cstart As Long ' first column in Rng
Dim C As Long ' working column
Dim Yr As Integer ' year
Cl = Cells(CapsRow, Columns.Count).End(xlToLeft).Column
Range(Cells(CapsRow, StartClm), Cells(CapsRow, Cl)).Copy
Cells(CapsRow, StartClm).PasteSpecial xlValues
Application.CutCopyMode = False
C = StartClm - 1
Application.DisplayAlerts = False
Do
Tmp = Cells(CapsRow, C + 1).Value
If Not IsDate(Tmp) And (C <> Cl) Then
MsgBox "Cell " & Cells(CapsRow, C + 1).Address(0, 0) & _
" doesn't contain a date." & vbCr & _
"This macro will be terminated.", _
vbInformation, "Invalid cell content"
Exit Do
End If
If (Yr <> Year(CDate(Tmp))) Or (C = Cl) Then
If Yr Then
Set Rng = Range(Cells(CapsRow, Cstart), _
Cells(CapsRow, C))
With Rng
.Merge
.HorizontalAlignment = xlCenter
.NumberFormat = "yyyy"
End With
SetBorder Rng, xlEdgeLeft
SetBorder Rng, xlEdgeRight
End If
If C > (Cl - 1) Then Exit Do
Cstart = C + 1
Yr = Year(Tmp)
End If
C = C + 1
Loop
Application.DisplayAlerts = True
End Sub
Private Sub SetBorder(Rng As Range, _
Bord As XlBordersIndex)
' 031
With Rng.Borders(Bord)
.LineStyle = xlContinuous
.ColorIndex = xlAutomatic
.TintAndShade = 0
.Weight = xlMedium ' xlThin
End With
End Sub
Assuming the months range is "B5:AH5"
Sub test()
Dim monthsRng As Range
Set monthsRng = Range("B5:AH5")
monthsRng.Cells(1, 1).Offset(-1, 0).Select
For j = 1 To Int((monthsRng.Cells.Count / 12) + 2)
If ActiveCell.Offset(1, 0) <> 0 Then
For i = 1 To 12
ActiveCell.Value = Year(ActiveCell.Offset(1, 0))
If Year(ActiveCell.Offset(1, i)) = ActiveCell Then
Selection.Resize(1, i + 1).Select
Else
Exit For
End If
Next
With Selection
.HorizontalAlignment = xlCenter
.MergeCells = True
End With
Selection.Offset(0, 1).Select
Else
Exit For
End If
Next
End Sub
Replacing the inner for loop with below code will work irrespective of whether the dates in the Range("B5:AH5") in above procedure are formatted as dates or not.
For i = 1 To 12
ActiveCell.Value = Right(Format(ActiveCell.Offset(1, 0), "DD.MM.YYYY"), 4)
If Right(Format(ActiveCell.Offset(1, i), "DD.MM.YYYY"), 4) = Format(ActiveCell, Text) Then
Selection.Resize(1, i + 1).Select
Else
Exit For
End If
Next
However, in any case you need to format the output in excel as number (without 1000 separator and decimal places) and not date.

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
``

Counting number of words of each column in VBA

I'am trying to implement a code so that all the number of words from each cell in a column can be calculated and displayed in a cell just next to them.
I have written this code, but it shows Complie Error: Loop without Do, where as I'am having it.
Sub Command()
total_words = 1
Dim ans_length As Integer
Dim start_point As Integer
Range("N3").Select
Do Until ActiveCell.Value = ""
ans_length = Len(ActiveCell.Offset(0, 13).Value)
For start_point = 1 To ans_length
If (Mid(ans_length, start_point, 1)) = " " Then
total_words = total_words + 1
End If
ActiveCell.Offset(0, 12).Value = total_words
ActiveCell.Offset(1, 0).Select
Loop
End Sub
say i have this content:
Col1 Col2
The only way to do multi | 6
line comments in VB | 4
the only option you have | 5
is the single | 3
here i have col2 by default and writing VBA code for col2
This UDF approach would be an easier option ... well ... in my opinion anyway.
Public Function CountWords(ByVal strText As String) As Long
Application.Volatile
CountWords = UBound(Split(strText, " ")) + 1
End Function
... you can then use that in any cell.
If you want to go with your original approach, you were missing a NEXT.
Sub Command()
total_words = 1
Dim ans_length As Integer
Dim start_point As Integer
Range("N3").Select
Do Until ActiveCell.Value = ""
ans_length = Len(ActiveCell.Offset(0, 13).Value)
For start_point = 1 To ans_length
If (Mid(ans_length, start_point, 1)) = " " Then
total_words = total_words + 1
End If
Next start_point
ActiveCell.Offset(0, 12).Value = total_words
ActiveCell.Offset(1, 0).Select
Loop
End Sub

VBA why am i getting error or popup saying "16"

In the code shown below, i am in the first section moving data from sheet "Ark2" to the sheet "Ark1". in the second section, i transpose from vertical to horizontal. Now i am rinning it in module, but i am getting an popup saying "16" and it is deleting data from my sheet "Ark2" and therefor also data on ark2.
it is not adding data from the first sheet to the second or horizonting the colums.
hope you can help!!
Sub MyProcedure()
a = Worksheets("ark1").Cells(Rows.Count, 1).End(xlUp).Row
MsgBox (a)
End Sub
Private Sub CommandButton1_Click()
Dim nøgletal As String, år As Integer
Worksheets("Ark2").Select
nøgletal = Range("B2")
år = Range("C2")
Worksheets("Ark1").Select
Worksheets("Ark1").Range("A4").Select
ThisWorkbook.Worksheets("Ark1").Range("C1:C100").Value = ThisWorkbook.Worksheets("Ark2").Range("C12:C100").Value
ThisWorkbook.Worksheets("Ark1").Range("D1:D100").Value = ThisWorkbook.Worksheets("Ark2").Range("D12:D100").Value
ThisWorkbook.Worksheets("Ark1").Range("E1:E100").Value = ThisWorkbook.Worksheets("Ark2").Range("M12:M100").Value
ThisWorkbook.Worksheets("Ark1").Range("F1:F100").Value = ThisWorkbook.Worksheets("Ark2").Range("N12:N100").Value
ThisWorkbook.Worksheets("Ark1").Range("G1:G100").Value = ThisWorkbook.Worksheets("Ark2").Range("O12:O100").Value
ThisWorkbook.Worksheets("Ark1").Range("A1:A16").Value = ThisWorkbook.Worksheets("Ark2").Range("A12:A16").Value
If Worksheets("Ark1").Range("A4").Offset(1, 0) <> "" Then
Worksheets("Ark1").Range("A4").End(xlDown).Select
End If
ActiveCell.Offset(1, 0).Select
ActiveCell.Value = nøgletal
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = år
Worksheets("Ark2").Select
Worksheets("Ark2").Range("B2", "B16").Select
End Sub
Sub x()
Dim lngDataColumns As Long
Dim lngDataRows As Long
lngDataColumns = 3
lngDataRows = 4
For t = 1 To lngDataRows
Range("l2").Offset(((t - 1) * lngDataColumns) - 1, 0).Resize(lngDataColumns, 1).Value = _
Application.Transpose(Range("e1:g1").Value)
Range("M2").Offset(((t - 1) * lngDataColumns) - 1, 0).Resize(lngDataColumns, 1).Value = _
Application.Transpose(Range("e1:g1").Offset(t).Value)
Next t
End Sub
why am i getting error or popup saying “16”
Should be evident why if you add a value in say ark1!A17 and rerun:
Sub MyProcedure()
a = Worksheets("ark1").Cells(Rows.Count, 1).End(xlUp).Row
MsgBox (a)
End Sub
If not, try adding also into ark1!A18 and rerunning.

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

Resources