excel vba loop max value and location more sheets - vba

I need the location of max value (one column) or address, so i can locate two cells left of the max value cell. next is finding the higher value of the two new cells and dividing the higher value with the max value. last step is returning the value to sheet "List1". that s the basic logic :)
thx for any help
the locating of max value and locating cells left of it, that is my main concern.
i cant figure it out. been looking for it but cant get it to work.
Sub DoIt()
'ONE MAIN SHEET (List1)
'MORE SECONDARY SHEETS WHERE DATA FOR MAX VALUE IS
Dim strSheet As String
Dim rng As Range
Dim dblMax As Double
Dim r As Range
i = 4
j = 8
g = 4
h = 20
s = 22
Dim cell As Range
Dim col, row
Do While Cells(i, j).Value <> ""
strSheet = Sheets(1).Cells(i, j)
Sheets(strSheet).Activate
'w = 2
'e = 27
'a = 2
'Do While Cells(a, s).Value >= "0"
'Range("AA1") = "IT WORKS"
'Cells(w, e) = Cells(a, s).Value
'a = a + 1
'w = w + 1
'Loop
Set rng = Sheets(strSheet).Range("V2:V8761")
dblMax = Application.WorksheetFunction.Max(rng)
'CODE FOR MAX VALUE LOCATION
'LOCATING TWO LEFT CELLS OF LOCATION MAX VALUE CELL
'DETERMINING THE HIGHER VALUE
'DIVIDING
Range("Z2") = dblMax 'CONTROL
i = i + 1
Range("Z1") = "IT WORKS" 'CONTROL
Sheets("List1").Activate
Cells(g, h) = "AAA" 'result of higher value cell by max value cell
g = g + 1
Loop
End Sub

thx for help i did it. code is not refind. here is the code:
Sub DoIt()
Dim strSheet As String
Dim rng As Range
Dim dblMax As Double
Dim r As Range
Dim dely As Double
i = 4
j = 8
g = 4
h = 20
l = 21
s = 22
Dim cell As Range
Dim col, row
Do While Cells(i, j).Value <> ""
strSheet = Sheets(1).Cells(i, j)
Sheets(strSheet).Activate 'error on no strsheet
w = 2
e = 27
a = 2
sumall = Application.Sum(Range("v2:v9000"))
'Do While Cells(a, s).Value >= "0"
'Range("AA1") = "nekaj dela"
'Cells(w, e) = Cells(a, s).Value
'a = a + 1
'w = w + 1
'Loop
Set rng = Sheets(strSheet).Range("V2:V9000")
dblMax = Application.WorksheetFunction.Max(rng)
mmm = Application.WorksheetFunction.Match(dblMax, Sheets(strSheet).Range("v:v"), 0)
positionRange = Sheets(strSheet).Range("v:v")
'iii = Application.WorksheetFunction.Index(positionRange, mmm)
'ooo = mmm.Offset(0, -1)
sum1 = Cells(mmm, 12)
sum2 = Cells(mmm, 21)
If sum1 > sum2 Then
'sumall = Application.Sum(Range("l2:l8761"))
PLDP = sumall / 365
dely = sum1 / PLDP * 100
smer = "1"
Else
'sumall = Application.Sum(Range("u2:u8761"))
PLDP = sumall / 365
dely = sum2 / PLDP * 100
smer = "2"
End If
'Range("AA2") = iii
Range("AB2") = sum1
Range("AC2") = sum2
Range("ad2") = dely
Range("ae2") = sumall
Range("af2") = PLDP
Range("Z2") = dblMax 'test cell
i = i + 1
Range("Z1") = "IT WORKS"
Sheets("List1").Activate
Cells(g, h) = smer
Cells(g, l) = dely
g = g + 1
Loop
End Sub

Related

VBA counting number of occurrences in a list of strings

I have a list of 1000+ names in a single column in excel where the names repeat occasionally. I am trying to count how many times each name occurs. This is what I have currently and it populates the desired sheet but it seems to mess up when counting the number of times the names show up. Anything helps!
m = 2
n = 1
person = Worksheets("Sheet1").Cells(m, 6).Value
Worksheets("Sorted_Data").Cells(n, 2).Value = person
Worksheets("Sorted_Data").Cells(n, 3).Value = 1
n = n + 1
m = m + 1
For i = 0 To Total_Tickets
person = Worksheets("Sheet1").Cells(m, 6).Value
y = 1
d = 0
Do While d <= i
comp = Worksheets("Sorted_Data").Cells(y, 2).Value
x = StrComp(person, comp, vbTextCompare)
If x = 0 Then
Worksheets("Sorted_Data").Cells(n - 1, 3).Value = Worksheets("Sorted_Data").Cells(n - 1, 3).Value + 1
m = m + 1
d = 10000
ElseIf x = 1 Or x = -1 Then
If comp = "" Then
Worksheets("Sorted_Data").Cells(n, 2).Value = person
Worksheets("Sorted_Data").Cells(n, 3).Value = 1
n = n + 1
m = m + 1
d = 10000
End If
y = y + 1
d = d + 1
End If
Loop
Next i
You're managing a lot of counters there, and that makes the logic more difficult to follow.
You could consider something like this instead:
Sub Tester()
Dim wsData As Worksheet, wsList As Worksheet, arr, m, i As Long, nm
Set wsData = ThisWorkbook.Sheets("Sheet1")
Set wsList = ThisWorkbook.Sheets("Sorted_Data")
'grab all the names in an array
arr = wsData.Range("A2:A" & wsData.Cells(Rows.Count, "A").End(xlUp).Row).Value
For i = 1 To UBound(arr, 1) 'loop over the array
nm = arr(i, 1) 'grab the name
m = Application.Match(nm, wsList.Columns("A"), 0) 'existing name on the summary sheet?
If IsError(m) Then
'name was not found: add it to the summary sheet
With wsList.Cells(Rows.Count, "A").End(xlUp).Offset(1)
.Value = nm
m = .Row
End With
End If
With wsList.Cells(m, "B")
.Value = .Value + 1 'update the count
End With
Next i
End Sub

VBA code Adding a cell contains date and a cell contains a number, getting mismatch error

Hi I am Trying to add to cells together and compare them against another cell but I get a type mismatch.
first cell is a date, the one being added is a number"as in number of days" and the third one being compared is a date also.
but I get type mismatch.
my code is below
Sub Macro1()
Macro1 Macro
Dim wks As Worksheet
Set wks = ActiveSheet
Dim x As Integer
Dim p As Integer
Dim rowRange As Range
Dim colRange As Range
Dim LastCol As Long
Dim LastRow As Long
LastRow = wks.Cells(wks.Rows.Count, "A").End(xlUp).Row
Set rowRange = wks.Range("A1:A" & LastRow)
For i = 7 To 189
p = 0
For q = 8 To LastRow
If [aq] = [si] Then
If [cq] + [ui] >= [xi] Then
[oq] = 1
Else
p = p + [dq]
[qq] = 0
End If
End If
Next q
Next i
End Sub
[cq] is a cell that contains date
[ui] is a cell that contains number
[xi] is a cell that contains date
Try it as cells(q, "A") = cells(i, "S").
For i = 7 To 189
p = 0
For q = 8 To LastRow
'If [aq] = [si] Then
If cells(q, "A") = cells(i, "S") Then
'If [cq] + [ui] >= [xi] Then
If cells(q, "C") + cells(i, "U") >= cells(i, "X") Then
'[oq] = 1
cells(q, "O") = 1
Else
'p = p + [dq]
p = p + cells(q, "D")
'[qq] = 0
cells(q, "Q") = 0
End If
End If
Next q
Next i
You need to use the "DateAdd" function. Instructions here: https://www.techonthenet.com/excel/formulas/dateadd.php
Example:
Sub add_dates()
Dim dateOne As Date
Dim dateTwo As Date
Dim lngDays As Long
dateOne = "1/1/2018"
lngDays = 2
dateTwo = "1/3/2018"
Dim result As Boolean
If DateAdd("d", lngDays, dateOne) >= dateTwo Then
MsgBox ("Greater than or equal to")
Else
MsgBox ("Less than")
End If
End Sub

So how to I reference the value of one cell as a series name using VBA?

this question is probably easy to solve but I cannot figure out how to do it and a quick web search didn't lead to anything. So here is my code:
Option Explicit
'Description: This macro is used to number plot all specimens into the stress-strain curve since this has become a task that
'has to be done very frequently
Sub PlotAllSpecimens_Tensile()
Dim ws As Worksheet, wb As Workbook
Dim xrng As Range, yrng As Range, namerng As Range
Dim CH As Chart, CHcond As Chart, CHdry As Chart
Dim Material As String, state As String, Temperatur As String, name As String
Dim i As Integer, j As Integer, idry As Integer, icond As Integer, k As Integer
Dim ser As series
Dim startrow As Integer
Set wb = ActiveWorkbook
idry = 1
icond = 1
For Each CH In wb.Charts
If CH.name = "Stress-Strain curve cond" Then
Set CHcond = CH
ElseIf CH.name = "Stress-Strain curve dry" Then
Set CHdry = CH
End If
Next CH
If Not CHdry Is Nothing Then
For Each ser In CHdry.SeriesCollection
ser.Delete
Next ser
End If
If Not CHcond Is Nothing Then
For Each ser In CHcond.SeriesCollection
ser.Delete
Next ser
End If
For Each ws In wb.Worksheets
If ws.name <> "Start" And ws.name <> "Auswertung" And ws.name <> "Zusammenfassung" Then
i = 1
For k = 1 To 15
If ws.Cells(k, 5 * i - 4) = "Material" Or ws.Cells(k, 5 * i - 4) = "Werkstoff" Then
Material = ws.Cells(k, 5 * i - 3).Value
ElseIf ws.Cells(k, 5 * i - 4) = "Temperatur" Then
Temperatur = ws.Cells(k, 5 * i - 3).Value
ElseIf ws.Cells(k, 5 * i - 4) = "Zustand" Then
state = ws.Cells(k, 5 * i - 3).Value
End If
Next k
While Not IsEmpty(ws.Cells(i * 5 - 4).Value)
name = Material & "_" & i & ", " & state & ", " & Temperatur
Set namerng = ws.Cells(1, 5 * i - 1).End(xlDown).Offset(-1, -1)
namerng.Value = name
startrow = ws.Cells(1, 5 * i - 1).End(xlDown).Row
Set xrng = Range(ws.Cells(startrow, 5 * i - 2), ws.Cells(startrow, 5 * i - 2).End(xlDown))
Set yrng = Range(ws.Cells(startrow, 5 * i - 1), ws.Cells(startrow, 5 * i - 1).End(xlDown))
If Not (CHdry Is Nothing) And state = "dry" Then
CHdry.SeriesCollection.NewSeries
CHdry.SeriesCollection(idry).XValues = xrng
CHdry.SeriesCollection(idry).Values = yrng
CHdry.SeriesCollection(idry).name = ??????????
CHdry.SeriesCollection(idry).Border.ColorIndex = 42 + ws.Index Mod 5
idry = idry + 1
End If
If Not (CHcond Is Nothing) And state = "conditioned" Then
CHcond.SeriesCollection.NewSeries
CHcond.SeriesCollection(icond).XValues = xrng
CHcond.SeriesCollection(icond).Values = yrng
CHcond.SeriesCollection(icond).Border.ColorIndex = 42 + ws.Index Mod 5
CHcond.SeriesCollection(icond).name = ???????
icond = icond + 1
End If
i = i + 1
Wend
End If
Next ws
End Sub
????? marks the issue. I want to name my series the value of the cell "namerng" so if i later change this cell the name in the plot will update. This can be done manually in excel by selecting a cell as the name range. If I use:
CHcond.SeriesCollection(icond).name = namerng.value
The results will be correct but do not change after I change the value of the namerng. So how to I reference the value of one cell as a series name using VBA?
I got it it is:
CHcond.SeriesCollection(icond).name = "='" & ws.name & "'!" & namerng.Address
Not very elegant but it works.

Find Method Object Variable Not Set

This is an error I've been trying to figure out for awhile now, my find method is not producing any results and I cannot figure out why.
The code is suppose to search InputSheet for a string, report the row number and start moving information over to Background based on that row number. Then the next .find will find the string in SummaryResults and start moving information from Background, reformat it a bit, and paste to SummaryResults.
My find method is not producing any results and leaves FindRow = Nothing even though the strings are present in the sheets and in the correct Ranges.
This error started occurring after running the macro with another Excel sheet open so maybe the ActiveWorkbook was incorrect, but I have not been able to get it to run since.
Some of the variables shown are from other sections of the code but when I hover over them in the debug mode they are showing what they're suppose to.
Option Explicit
Sub CAESARCONVERSION()
Dim InputSheet As Worksheet, SummaryResults As Worksheet, Background As Worksheet
Dim i As Integer
Dim j As Integer
Dim x As Integer
Dim y As Integer
Dim h As Integer
Dim v As Integer
Dim c As Integer
Dim z As Integer
Dim myBook As Workbook
Set myBook = Excel.ThisWorkbook
Set InputSheet = myBook.Sheets("Input Sheet")
Set SummaryResults = myBook.Sheets("Summary Results")
Set Background = myBook.Sheets("Background")
Dim NodeList As Integer
Dim TotalCases As Integer
Dim sMyString As String
Dim Nodes As Variant
Dim FindRow As Range
Dim intValueToFind As String
Dim FindRowNumber As Long
Dim SecondRowNumber As Long
'Clear the last run of macro
Background.Range("A2:A1000").Cells.Clear
Background.Range("C2:I10000").Cells.Clear
SummaryResults.Cells.Clear
'Code that will count the total number of load cases
TotalCases = 0
h = 2
Dim text As String
For v = 12 To 100
If InputSheet.Cells(v, 2).Value <> "" Then
text = LTrim(InputSheet.Cells(v, 2).Value)
Background.Cells(h, 3).Value = text
h = h + 1
TotalCases = TotalCases + 1
Else
GoTo NodeCounter
End If
Next v
NodeCounter:
y = TotalCases - 1
x = 0
Dim LoadCaseList() As Variant
ReDim LoadCaseList(y)
LoadCaseList:
For x = 0 To y
LoadCaseList(x) = Background.Cells(2 + x, 3).text
Next x
j = 2
For i = 17 + TotalCases To 20000 'Need to define how far for the program to search, we may exceed 20000 at some point
If InputSheet.Cells(i, 2).Value <> "" Then
Background.Cells(j, 1).Value = InputSheet.Cells(i, 2).Value
j = j + 1
End If
Next i
With Background
NodeList = Background.Cells(2, 2).Value
Background.Range("AA1:XX" & NodeList + 1).Cells.Clear
End With
ReDim Nodes(NodeList - 1)
v = 0
j = 2
For i = 0 To NodeList - 1
Nodes(i) = Background.Cells(j, 1).Value
j = j + 1
Next i
Headers:
Dim LoadCaseHeader() As String
Dim TypHeader()
TypHeader = Array("Node", "L", "Direction", "Magnitude")
Dim LoadDirections()
LoadDirections = Array("X", "Y", "Z", "MX", "MY", "MZ")
x = 0
z = 0
For x = 0 To NodeList - 1
For z = 0 To TotalCases - 1
SummaryResults.Range(("B" & 2 + (NodeList * 6 + 2) * z) & ":" & "E" & 2 + (NodeList * 6 + 2) * z) = TypHeader()
SummaryResults.Range("A" & 2 + (NodeList * 6 + 2) * z) = Background.Range("C" & 2 + z)
Next z
Next x
'Search rows for the first instance of this value.
LoadCases:
'Code that copies information from the InputSheet to the SummaryResults
Dim LoadCases() As Long
ReDim LoadCases(NodeList, 6)
FindRowNumber = 0
SecondRowNumber = 0
For c = 0 To y
intValueToFind = LoadCaseList(c)
For i = 7 To 31 + TotalCases
With InputSheet
If Trim(Cells(i, 3).Value) = intValueToFind Then
MsgBox ("Found")
Set FindRow = InputSheet.Range("C:C").Find(What:=intValueToFind, LookIn:=xlValues)
FindRowNumber = FindRow.Row
End If
End With
Next i
'MsgBox FindRowNumber
With InputSheet
For i = 0 To NodeList - 1
x = 4
For j = 0 To 5
LoadCases(i, j) = InputSheet.Cells(FindRowNumber + (TotalCases + 3) * i, x)
x = x + 1
Next j
Next i
End With
Background.Range("AC2:AH" & NodeList + 1).Offset(0, c * 7) = LoadCases
For i = 1 To NodeList * 6 * TotalCases
With SummaryResults
If Trim(Cells(i, 5).Value) = intValueToFind Then
Set FindRow = SummaryResults.Range("A:A").Find(What:=intValueToFind, LookIn:=xlValues)
SecondRowNumber = FindRow.Row
GoTo Step2
End If
End With
Next i
Step2:
With SummaryResults
For x = 0 To NodeList - 1
For j = 0 To 5
SummaryResults.Cells(SecondRowNumber + 1 + j + 6 * x, 5) = Background.Cells(x + 2, 29 + j)
SummaryResults.Cells(SecondRowNumber + 1 + j + 6 * x, 3) = TypHeader(1)
SummaryResults.Cells(SecondRowNumber + 1 + j + 6 * x, 4) = LoadDirections(j)
SummaryResults.Cells(SecondRowNumber + 1 + j + 6 * x, 2) = Nodes(x)
Next j
Next x
End With
Next c
End Sub
Any help would be appreciated. EDIT: Uploaded the entire code. Additional information, the code works when not tabbed into excel but will fail when tabbed in a ran again.
The issue seems to be that the LoadCaseList() array is never getting populated. This is your Find statement:
Set FindRow = InputSheet.Range("C:C").Find(What:=intValueToFind, LookIn:=xlValues)
intValueToFind is set by this statement:
intValueToFind = LoadCaseList(c)
But the LoadCaseList() array is populated by the following code which is a label that is never called by a GoTo statement (as far as I can tell):
LoadCaseList:
For x = 0 To y
LoadCaseList(x) = Background.Cells(2 + x, 3).text
Next x
So because the LoadCaseList label statement is never being called by a GoTo statement, the LoadCaseList() array is never being populated so intValueToFind has no value and therefore the Find method has no value to search for (except for maybe the empty string).

My macro is showing runtime error 1004. Please check

I am getting the 1004 error when running. The error is at this line:
If IsNumeric(wkbCurr.Sheets(CTRYname).Range(column & x).Value) = True Then
What I want to do is to select the sheet (CTRYNAME) and then search through columns 5,7,9 etc and format the numbers as done in the code.
Public Sub MoM_Check()
Dim inti As Integer
Dim intj As Integer
Dim k As Integer
Dim mnth As Integer
Dim currSALE As Double
Dim prevSALE As Double
Dim diffpercent As Double
Dim CTRYname As String
Dim x As Integer
Dim column As String
'Find Difference percentage between sales of 24 common months in present month's extarct and previous month's extract
For n = 1 To 13
Application.SheetsInNewWorkbook = 4
Set wkbTemp = Workbooks.Add
CTRYname = ThisWorkbook.Sheets("Country lookup").Range("A1").Offset(n, 0).Value
'Open a temporary workbook to do all the Calculations
'First the current month's extract is copied to the first sheet
'We now copy sheets for range from wkbout to wkbtemp using usedrange
wkbCurr.Sheets(CTRYname).Activate
wkbCurr.Sheets(CTRYname).UsedRange.Copy
wkbTemp.Sheets("Sheet1").Range("A1").PasteSpecial
wkbprev.Sheets(CTRYname).Activate
wkbprev.Sheets(CTRYname).UsedRange.Copy
wkbTemp.Sheets("Sheet2").Range("A1").PasteSpecial
'open the Previous month's Main Extract file as given in the lookup tab. This data is pasted on sheet2 of temporary workbook.
'This sheet helps us to compare the country channels in current month's extract with the previous Month's Extract.
'So the same process is followed for this sheet and similarly we get the country channels from the previous month's extract and paste them on 'sheet3
'Prevcnt contains the number of country channels in the previous month's extract
k = 1
For mnth = 0 To 22
currSALE = wkbTemp.Sheets("Sheet1").Range("AB10").Offset(0, mnth).Value
prevSALE = wkbTemp.Sheets("Sheet2").Range("AC10").Offset(0, mnth).Value
If prevSALE = 0 And currSALE <> 0 Then
diffpercent = 1
ElseIf prevSALE = 0 And currSALE = 0 Then
diffpercent = 0
Else: diffpercent = (currSALE - prevSALE) / prevSALE
End If
If diffpercent > 0.01 Or diffpercent < -0.01 Then
Set wkbRaw = Workbooks.Open(strOutputQCPath & "Errorlog.xlsx")
wkbRaw.Sheets("Sheet1").Activate
wkbRaw.Sheets("Sheet1").Range("A1").Offset(i, 1 + n).Value = CTRYname & " Incorrect"
Exit For
Else
Set wkbRaw = Workbooks.Open(strOutputQCPath & "Errorlog.xlsx")
wkbRaw.Sheets("Sheet1").Activate
wkbRaw.Sheets("Sheet1").Range("A1").Offset(i, 1 + n).Value = CTRYname & " Correct"
k = k + 1
wkbRaw.SaveAs Filename:=strOutputQCPath & "Errorlog.xlsx"
wkbRaw.Close
End If
Next mnth
For x = 1 To 15
If x = 1 Or x = 2 Or x = 3 Or x = 4 Or x = 6 Or x = 9 Or x = 10 Or x = 11 Or x = 13 Then
GoTo Name
Else
If IsNumeric(wkbCurr.Sheets(CTRYname).Range(column & x).Value) = True Then
If wkbCurr.Sheets(CTRYname).Range(column & x).Value > 9.99 Then
wkbCurr.Sheets(CTRYname).Range(column & x).Value = ">999%"
ElseIf wkbCurr.Sheets(CTRYname).Range(column & x).Value < -9.99 Then
wkbCurr.Sheets(CTRYname).Range(column & x).Value = "<-999%"
End If
End If
End If
Name:
Next x
wkbTemp.Close savechanges:=False
Set wkbTemp = Nothing
Next n
End Sub
Please help!
You haven't given the string "column" a value, which is why you're getting error 1004 on that line.