I want compute the sum of a column by VBA.
This following my code:
Sub CALRU()
ECP_CA = 0
Radome_CA = 0
For i = 1 To 21726
If Cells(i, "L") = "GET" Then
If Cells(i, "H") = "2014" Then
ECP_CA = ECP_CA + Cells(i, "J")
Else
MsgBox "not found"
End If
Else
MsgBox "not found"
End If
Next i
End Sub
My loop when it find the first result is true it stoped.And do not termine the rest of column.
Someone, can give me a suggestion where's the problem ?
Thank you.
If your code stops, you must click the OK button in the MsgBox for the macro to continue.
EDIT#1:
This may help solve your problem:
Sub CALRU()
ECP_CA = 0
Radome_CA = 0
For i = 1 To 21726
If Cells(i, "L") = "GET" Then
If Cells(i, "H") = "2014" Then
ECP_CA = ECP_CA + ReturnNumber(Cells(i, "J"))
Else
MsgBox "not found"
End If
Else
MsgBox "not found"
End If
Next i
End Sub
Public Function ReturnNumber(v As Variant) As Double
Dim L As Long, temp As String, CH As String
L = Len(v)
If L = 0 Then
ReturnNumber = 0
Exit Function
End If
temp = ""
For i = 1 To L
CH = Mid(v, i, 1)
If CH Like "[0-9]" Or CH = "." Or CH = "-" Then temp = temp & CH
Next i
If temp = "" Then
ReturnNumber = 0
Else
ReturnNumber = CDbl(temp)
End If
End Function
It should work now:
Option Explicit
Sub CALRU()
Dim ecp_ca As Double
Dim Radome_CA As Double
Dim i As Long
ecp_ca = 0
Radome_CA = 0
With ActiveSheet
For i = 1 To 217
If .Cells(i, "L") = "GET" Then
If .Cells(i, "H") = "2014" Then
ecp_ca = ecp_ca + .Cells(i, "J")
Else
Debug.Print "not found"
End If
Else
Debug.Print "not found"
End If
Next i
End With
End Sub
I have tried up to 217, because I didn't want to wait to print for 21K. I have changed the MsgBoxes to Debug.Print and I have added With ActiveSheet, as far as this can be a problem as well. Option Explicit is also added.
Related
My macro goes through all data rows on a specific sheet. Currently there are 6 rows. The first row is a negative number and the 2nd row is a positive number (debit and credit).
The macro reviews each row and displays a list box for the user to make a selection. Then it goes through the next row and does the same thing. I'm expecting the listbox to display 6 times, once for each row of data.
The problem I'm having is that the listbox is displaying 7 times. 3 times for the first pair or records and twice for the remaining pair of records. I can't figure out why the listbox is displaying the extra time.
Here is the code for the list box:
Private Sub ContinueButton_Click()
If IsNull(ListBox1.Value) Then
MsgBox " Please select the appropriate balance to continue. "
Exit Sub
Else
MyIndex = 0
MyIndex = ListBox1.ListIndex
MyIndex = MyIndex + 1
MyBal = ""
MyBal = APIARArray(MyIndex, 4)
Unload UserForm1
UserForm1.Hide
Sleep 750
End If
End Sub
Private Sub UserForm_Initialize()
UserForm1.Label1.Caption = "Please select the appropriate balance for Unit: " & vUnit
ListBox1.ColumnCount = 4
ListBox1.ColumnWidths = "50;50;75;50"
Dim i As Integer
With ListBox1
w = 1
i = 0
For w = 1 To UBound(APIARArray)
DoEvents
.AddItem
.List(i, 0) = APIARArray(w, 1)
.List(i, 1) = APIARArray(w, 2)
.List(i, 2) = APIARArray(w, 3)
.List(i, 3) = format(APIARArray(w, 4), "#,##0.00;[Red](#,##0.00)")
i = i + 1
Next
End With
UserForm1.Height = 215
UserForm1.Width = 348
ListBox1.SetFocus
End Sub
This is the code that calls the ListBox:
Sub LookForBalance()
Dim r As Integer
Dim APIUnit As String
r = 2
Do Until Len(Trim(Cells(r, 1))) + Len(Trim(Cells(r, 7))) + Len(Trim(Cells(r, 9))) + Len(Trim(Cells(r, 10))) + Len(Trim(Cells(r, 11))) = 0
DoEvents
If Trim(Cells(r, 27)) = "A199" Then
If Cells(r, 29) > 90 Then
APIUnit = ""
vUnit = ""
vUnit = Trim(Cells(r, 11))
If MyCntry = "A1" Then APIUnit = clsAPI.APIARSearch("WWW11", Trim(Cells(r, 11)))
If MyCntry = "A2" Then APIUnit = clsAPI.APIARSearch("WWW12", Trim(Cells(r, 11)))
If InStr(1, APIUnit, "ERROR") > 0 Then
Cells(r, 30) = "Unit Not Found"
Else
If UBound(APIARArray) > 1 Then
Load UserForm1
UserForm1.Show
Cells(r, 30) = MyBal
Else
Cells(r, 30) = APIARArray(1, 4)
End If
End If
End If
End If
r = r + 1
Loop
End Sub
There isn't much code here but I'm not sure what is going on. Any help or suggestions to resolve this issue would be greatly appreciated. Thanks in advance for your help.....
I am a beginner on vba, sarching and reading different things about vba I have created a piece of code but doesn't work how I want to. If I search for a specific value the code find it and show on specific textboxes a specific value, but if there are more than one same values (in searching column) I want to make the code go to next one until find every same value, what my actual code doesn't do. Any help on improving this code or any other code that does it I appreciate.
Here is my code,
Private Sub Search_Click()
Dim a As String
Dim b As Double
Dim k As Range
On Error GoTo dontexist:
If Me.TextBox20.Value = "" Or Me.TextBox20.Value = "Number of invoice" Then
Me.Label29.Caption = "Number of invoice"
b = Me.TextBox24.Value
Set k = Sheets("Sheet2").Range("E:E")
r = Application.WorksheetFunction.Match(b, k, 0)
Me.TextBox21.Value = Sheets("Sheet2").Cells(r, 2).Value
Me.TextBox22.Value = Sheets("Sheet2").Cells(r, 8).Value
Me.TextBox23.Value = Sheets("Sheet2").Cells(r, 4).Value
Exit Sub
Else
Me.Label29.Caption = "Sum of invoice"
a = Me.TextBox20.Value
Set k = Sheets("Sheet2").Range("H:H")
r = Application.WorksheetFunction.Match(a, k, 0)
Me.TextBox21.Value = Sheets("Sheet2").Cells(r, 2).Value
Me.TextBox22.Value = Sheets("Sheet2").Cells(r, 5).Value
Me.TextBox23.Value = Sheets("Sheet2").Cells(r, 4).Value
Exit Sub
End If
dontexist:
MsgBox "This record dosn't exist!", vbInformation, "Info!"
End Sub
Add a label to your form to hold the last found row and start the search from there. I have used label30.
Option Explicit
Private Sub Search_Click()
Dim rngSearch As Range, rngFound As Range, sColumn As String
Dim sValue As String, iCount As Long
Dim ws As Worksheet
Set ws = Sheets("Sheet2")
' label to hold row to start search at
If Label30 = "" Then Label30 = "1"
If Len(TextBox24) > 0 Then
' search on number
sValue = TextBox24
sColumn = "E"
Label29 = "Number of invoice"
ElseIf Len(TextBox20) > 0 Then
' search on total
sValue = TextBox20
sColumn = "H"
Label29 = "Sum of invoice"
Else
MsgBox "No search values entered", vbExclamation
Exit Sub
End If
' count number of matches
Set rngSearch = ws.Cells(1, sColumn).EntireColumn
iCount = Application.WorksheetFunction.CountIf(rngSearch, sValue)
If iCount > 0 Then
' continue search from last position
Set rngFound = rngSearch.Find(sValue, _
After:= ws.Range(sColumn & Label30), _
LookIn:=xlValues, _
LookAt:=xlWhole)
If rngFound Is Nothing Then
' not found
Label30 = ""
MsgBox "No more records found"
Else
' is row new
If rngFound.Row > Label30 Then
'MsgBox rngFound.Row
' copy into text boxes
With rngFound.EntireRow
If sColumn = "E" Then
TextBox21 = .Cells(1, 2)
TextBox22 = .Cells(1, 8)
TextBox23 = .Cells(1, 4)
Else
TextBox21 = .Cells(1, 2)
TextBox22 = .Cells(1, 5)
TextBox23 = .Cells(1, 4)
End If
End With
Label30 = rngFound.Row
Else
MsgBox "No more records found", vbExclamation
Label30 = ""
Exit Sub
End If
End If
Else
MsgBox "No records found", vbExclamation
Label30 = ""
End If
End Sub
I am working on a userform where users can edit entries from a list selection and save them to specific cells.
Private Sub CommandButton3_Click()
Dim lZeile As Long
If ListBox1.ListIndex = -1 Then Exit Sub
If Trim(CStr(TextBox_Name.Text)) = "" Then
MsgBox "Sie müssen mindestens einen Namen eingeben!", vbCritical + vbOKOnly, "FEHLER!"
Exit Sub
End If
lZeile = 2
Do While Trim(CStr(Tabelle4.Cells(lZeile, 1).Value)) <> ""
If ListBox1.Text = Trim(CStr(Tabelle4.Cells(lZeile, 1).Value)) Then
Tabelle4.Cells(lZeile, 1).Value = Trim(CStr(TextBox_Name.Text))
Tabelle4.Cells(lZeile, 11).Value = ListBox_Problem.Text
Tabelle4.Cells(lZeile, 12).Value = TextBox_Problem2.Text
Tabelle4.Cells(lZeile, 4).Value = ComboBox1.Text
Tabelle4.Cells(lZeile, 3).Value = ComboBox2.Text
Tabelle4.Cells(lZeile, 13).Value = TextBox3.Text
Tabelle4.Cells(lZeile, 14).Value = TextBox4.Text
If ListBox1.Text <> Trim(CStr(TextBox_Name.Text)) Then
Call UserForm_Initialize
If ListBox1.ListCount > 0 Then ListBox1.ListIndex = 0
End If
Exit Do
End If
lZeile = lZeile + 1
Loop
End Sub
Now I have a ListBox where multiple entries can be selected. I want to write the selected entries into one single cell with "," as delimiter.
I have found the following code for that:
Dim i As Long
sText = ""
Range("B34").Value = ""
With Me.ListBox1
For i = 0 To .ListCount - 1
If .Selected(i) Then
sText = sText & ", " & .List(i)
End If
Next i
End With
sText = Mid(sText, 3)
If Len(sText) > 0 Then
Range("B34").Value = sText
Else
MsgBox "No selection made.", vbInformation
End If
I tried to incorporate it into mine but just cannot get it to work. I am not that fluent with VBA and was wondering if someone could help me?
The easiest way is to put your code (minor changes made) into a function:
Public Function GetCommaSeparatedListBoxItems(ByVal FromListBox As MSForms.ListBox) As String
Dim sText As String
With FromListBox
Dim i As Long
For i = 0 To .ListCount - 1 'loop through all items in the ListBox
If .Selected(i) Then 'chech each item if it is selected and if so …
sText = sText & ", " & .List(i) '… append this item comma delimited to `sText`
End If
Next i
End With
'since `sText` is empty in the beginning, data will always start with a comma, so removo that
'example data before: ", Item 1, Item 2, Item 3"
sText = Mid$(sText, 3)
'example data afterwards: "Item 1, Item 2, Item 3"
'return the comma separated items in the function
GetCommaSeparatedListBoxItems = sText
'Alternatively instead of the lise above you can …
If Len(sText) > 0 Then 'check if something was selected in the listbox and …
GetCommaSeparatedListBoxItems = sText '… return the value
Else
MsgBox "No selection made.", vbInformation '… or a error message
End If
End Function
That you can easily use like:
Debug.Print GetCommaSeparatedListBoxItems(FromListBox:=Me.ListBox1)
Example to write it into a cell you can use the function (in your first code) like:
Tabelle4.Cells(lZeile, 14).Value = GetCommaSeparatedListBoxItems(FromListBox:=Me.ListBox1)
you just need to adjust the code Me.ListBox1 to your multi select ListBox.
please help where is the error.
loop without IF?
I need to load the code, check the first 2 values match the cell. Check that you do not duplicate in column A. And retrieve the codes until the required number is reached.
Thank you
My Code:
Sub novy()
Dim aText(1) As Variant
Dim n As Integer
Dim vstup As String
vstup = InputBox(aText(x))
Set hledat = Range("A:A").Find(what:=vstup, LookIn:=xlValues, LookAt:=xlWhole)
If vstup = "" Then ' in case the use press "Cancel"
i = MsgBox("Chcete ukončit načítání?", vbYesNo)
Select Case i
Case vbYes
Exit Sub
Case vbNo
Call novy
End Select
ElseIf Left(vstup, 2) <> Range("D3").Formula Then
i = MsgBox("jiný modul!", vbExclamation)
ElseIf hledat Is Nothing Then
For n = 1 To 10
aText(1) = "Načti kód"
Sheets("data").Select
aLastRow = Cells(1, 1).CurrentRegion.Rows.Count + 1
For x = 1 To 1
Cells(aLastRow, x) = vstup
Next
Cells(10, 9) = n
'MsgBox n
Next n
MsgBox "Bedna je hotová"
Else
i = MsgBox("modul byl už načten!", vbExclamation)
End If
End Sub
You have an error on the the two last for loops. you dont need 2 either with an "x" from 1 to 1..
For n = 1 To 10
aText(1) = "Načti kód"
Sheets("data").Select
aLastRow = Cells(1, 1).CurrentRegion.Rows.Count + 1
Cells(aLastRow, 1) = vstup
Next
I have a strange problem. That code works as long as I don't assign addresses of cells to the variables komorka_k and komorka_y. Since 2 lines of the code marked with "LINE 1" and "LINE 2" are disabled, VBA macro works properly. What is the reason for such an activity? How is it possible that assigning a value not connected with any other part of a submodule makes it acting differently?
Public stara_wartosc As Variant
Public czy_wiekszy_zakres As Boolean
Private Sub Worksheet_Change(ByVal Target As Range)
Dim x, y As Integer
Dim x_err As Integer
Const y_err = 4
Dim nowa_wartosc As Variant
Dim komorka_x As String
Dim komorka_y As String
Const kon_col = 72
komorka_x = ""
komorka_y = ""
x = Target.row
y = Target.Column
nowa_wartosc = Target.Value
If czy_wiekszy_zakres = True Then
stara_wartosc = nowa_wartosc
End If
On Error GoTo TypeMismatch
If stara_wartosc <> nowa_wartosc And czy_wiekszy_zakres = False Then
If Target.Worksheet.Cells(x, 2).Value = "" Or Target.Worksheet.Cells(x, 2).Value = 0 Then
Application.EnableEvents = False
Target.ClearContents
MsgBox Prompt:="Zmieniłeś wartość komórki bez wpisania numeru zlecenia." & vbCrLf & "Wpisz nr zlecenia!", Title:="ZACHOWUJESZ SIĘ NIEWŁAŚCIWIE, MÓJ DROGI!"
Target.Worksheet.Cells(x, 2).Activate
Application.EnableEvents = True
Exit Sub
End If
With ActiveWorkbook.Worksheets("Errata")
komorka_x = .Range("A:A").Find(x, LookIn:=xlValues).Address 'LINE 1
komorka_y = .Range("B:B").Find(y, LookIn:=xlValues).Address 'LINE 2
x_err = .Cells(Rows.Count, 1).End(xlUp).row + 1
If .Cells(x_err, 1).Value = 0 Or .Cells(x_err, 1).Value = "" Then
.Cells(x_err, 1).Value = x
End If
If .Cells(x_err, 2).Value = 0 Or .Cells(x_err, 2).Value = "" Then
.Cells(x_err, 2).Value = y
End If
Set_values:
.Cells(x_err, y_err - 1).Value = stara_wartosc
.Cells(x_err, y_err).Value = Target.Value
.Cells(x_err, y_err + 1).Value = Target.Worksheet.Cells(x, 2).Value
End With
End If
TypeMismatch:
If Err = 13 Then
Exit Sub
End If
End Sub
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Target.Cells.Count = 1 Then
stara_wartosc = Target.Value
czy_wiekszy_zakres = False
Else
czy_wiekszy_zakres = True
End If
End Sub
Probably
komorka_x = .Range("A:A").Find(x, LookIn:=xlValues).Address
komorka_y = .Range("B:B").Find(y, LookIn:=xlValues).Address
doesn't find anything. Therefore .Address fails because no find result no address.
Then because of On Error GoTo TypeMismatch it jumps to the error handling here.
So make sure .Find is not nothing:
Dim FoundX As Range
Set FoundX = .Range("A:A").Find(x, LookIn:=xlValues)
If Not FoundX Is Nothing Then
komorka_x = FoundX.Address
Else
MsgBox "Nothing found for x=" & x
End If