Correcting formula in vba excel - vba

I want to create a macro that check all the cells of a column and if the first two characters of a cell is "BB" then i want the macro to extract three characters from the cell and paste it to the next column but a the corresponding row.
But my formula after the if clause is not working.
this is what i have done since:
Sub test()
Dim lmid As String
Dim srange, SelData, ExtBbFor As String
Dim lastrow As Long
Dim i, icount As Integer
lastrow = ActiveSheet.Range("B30000").End(xlUp).Row
srange = "G1:G" & lastrow
SelData = "A1:G" & lastrow
Range(srange).Formula = "=mid(E1,1,3)"
For i = 1 To lastrow
If InStr(1, LCase(Range("E" & i)), "bb") <> 0 Then
Range("G" & i).Formula = "=mid("E & i", 4, 3)"
End If
Next i
End Sub
thanks in advance

Try with below. It will work
Range("G" & i).Value = Mid(Range("E" & i), 4, 3)
If the cell is not limited to 7 then you need as below
Range("G" & i).Value = "=Mid(E" & i & ", 3, " & Len(E & "& i & ") & ")"
It will extract from the 3rd character up to the last character in a cell.

Your syntax is wrong where you're trying to concatenate strings, I think you mean to use:
Range("G" & i).Formula = "=MID(E" & i & ",4,3)"
Based on your code I think this will do the exact same thing without having to loop or declare any variables:
Sub test()
With Range("G1:G" & Cells(Rows.Count, 2).End(xlUp).Row)
.FormulaR1C1 = "=IF(UPPER(LEFT(RC[-2],2))=""BB"",MID(RC[-2],4,3),"""")"
.Value = .Value
End With
End Sub

Related

Replace comma with blank in vba

I have to replace comma in the last column of any row with blank.I have below in excel.
1 _1 "",
2 _2 "",
3 _3 "",
4 _4 "",
5 _5 "",
My code. but it is not working.
Private Sub CommandButton1_Click()
Dim lRow As Long
Dim length As Long
'Find the last non-blank cell in column A(1)
lRow = Cells(Rows.Count, 1).End(xlUp).Row
length = Len(Range("C" & lRow)) - 1
Range("C" & lRow).Value = Replace(Range("C" & lRow), ",", "", length)
Range("B2:B" & lRow).ClearContents
End Sub
This should do the trick: It will remove the last character in the last row if it is a comma (this assumes that you want to replace in column C as your code indicates):
Private Sub CommandButton1_Click()
Dim lRow As Long
lRow = ActiveSheet.UsedRange.Rows.Count
If Right(Range("C" & lRow).Value, 1) = "," Then
Range("C" & lRow).Value = Left(Range("C" & lRow), Len(Range("C" & lRow)) - 1)
End If
Range("B2:B" & lRow).ClearContents
End Sub
You could also use the replace, but it is trickier that way.

Insert formula with Variable VBA

I'm trying to insert a formula in the Column C of Sheet2. The row number however depends on the value of pasterow. The range in the formula should be G[lastrow]:NS[lastrow] with lastrow pertaining to the last row of Sheet1.
Here is my code:
Sub try()
With Sheets("Sheet2")
pasterow = .Cells(.rows.Count, "B").End(xlUp).Offset(1, 0).Row
With Sheets("Sheet1")
lastRow = ActiveWorkbook.Worksheets("Sheet1").Range("F" & .rows.Count).End(xlUp).Row
ActiveWorkbook.Worksheets("Sheet2").Range("C" & pasterow).formula = _
"=COUNTIF(Sheet1!G & lastRow & :NS & lastRow & , ""VL"" )"
End With
End With
End Sub
I'll really appreciate if someone could point out what's wrong with my code. Thanks!
The VBA variables are inside your formula string. Compare:
ActiveWorkbook.Worksheets("Sheet2").Range("C" & pasterow).formula = "=COUNTIF(Sheet1!G" & lastrow & ":NS" & lastrow & ", ""VL"" )"
Try this..
ActiveWorkbook.Worksheets("Sheet2").Range("C" & pasterow).FormulaR1C1 = "=COUNTIF(Sheet1!C[4]:C[380],""VL"")"
May be this is what your expecting to achieve!
ActiveWorkbook.Worksheets("Sheet2").Range("C" & pasterow).Value = "=COUNTIF(Sheet1!G" & lastRow & ":NS" & lastRow & ", ""VL"" )"
Try with:
ActiveWorkbook.Worksheets("Sheet2").Range("C" & pasterow).formula = _
"=COUNTIF(Sheet1!R" & lastrow & "C7:R" & lastrow & "C383,""VL"")"

How do I get all the different unique combinations of 3 columns using VBA in Excel?

I have an Excel worksheet with several columns, where 3 of them form a "unique key".
If I have fruits in column A (Apple, Banana, Orange), some name in column B (John, Peter) and something like Yes/No in column C, I want to be able to get sums of values from rows where the values in these columns are the same.
For instance, the sum of all the values in column D for rows where columns A, B and C are Apple,John,Yes.
Sorry for the confusing text, but I don't know how to express my question more clearly. I've never done anything in VBA so I'm a bit lost here...
Here's an example of the expected result.
It is also possible to go to the data tab -> remove duplicates. You can then select which columns you would like to compare in removing the dulicates.
I don't know in advance which combinations exist. The goal is to list all the unique combinations and the sum of some other columns. Can I do this without using VBA?
No Formulas/VBA required. Use a Pivot table for a summary of all combinations. See screenshot
If you still want VBA then that can also be done :)
EDIT
I quickly wrote this
Sub sample()
Dim ws As Worksheet
Dim lRow As Long, i As Long, j As Long
Dim col As New Collection
Dim Itm
Dim cField As String
Const deLim As String = "#"
Set ws = ThisWorkbook.Sheets("Sheet1")
With ws
lRow = .Range("A" & .Rows.Count).End(xlUp).Row
For i = 2 To lRow
cField = .Range("A" & i).Value & deLim & _
.Range("B" & i).Value & deLim & _
.Range("C" & i).Value
On Error Resume Next
col.Add cField, CStr(cField)
On Error GoTo 0
Next i
i = 2
.Range("A1:C1").Copy .Range("F1")
.Range("I1").Value = "Count"
For Each Itm In col
.Range("F" & i).Value = Split(Itm, deLim)(0)
.Range("G" & i).Value = Split(Itm, deLim)(1)
.Range("H" & i).Value = Split(Itm, deLim)(2)
For j = 2 To lRow
cField = .Range("A" & j).Value & deLim & _
.Range("B" & j).Value & deLim & _
.Range("C" & j).Value
If Itm = cField Then nCount = nCount + 1
Next
.Range("I" & i).Value = nCount
i = i + 1
nCount = 0
Next Itm
End With
End Sub

macro to check non blank cells in a column to ensure isdate()

I've been looking to write a macro to check 3 columns to ensure the contents are a date value. The columns can contain empty cells.
The below returns a message box for each cell that is not a date, even the blanks.
Sub DateCheck()
With ActiveSheet
lastRow = .Range("AB" & Rows.Count).End(xlUp).Row
For RowCount = 2 To lastRow
POC = .Range("AB" & RowCount)
If Not IsDate(POC) Then
MsgBox ("Please enter valid date in Cell : AB" & RowCount & ". Example: dd/mm/yyyy")
End If
Next RowCount
End With
End Sub
Could anybody be so kind as to help to adjust this to look at 3 non-adjacent columns, ignore blank cells and only return one message per column in the event it finds non-date values?
Thanks as always
Chris
Code:
Sub DateCheck()
Dim s(2) As String
Dim i As Integer
Dim o As String
Dim lastRow As Long
Dim r As Long
'Enter columns here:
s(0) = "A"
s(1) = "B"
s(2) = "C"
For i = 0 To 2
With ActiveSheet
lastRow = .Range(s(i) & Rows.Count).End(xlUp).Row
For r = 2 To lastRow
POC = .Range(s(i) & r)
If Not IsDate(POC) Then
o = o & ", " & .Range(s(i) & r).Address
End If
Next r
MsgBox ("Please enter valid date in Cells : " & Right(o, Len(o) - 1) & ". Example: dd/mm/yyyy")
o = ""
End With
Next i
End Sub
I would change your loop to a For Each In ... Next and use .Union to construct a range of non-adjacent columns.
Sub MultiDateCheck()
Dim lr As Long, cl As Range, rng As Range, mssg As String
With ActiveSheet
lr = .Range("AB" & Rows.Count).End(xlUp).Row
Set rng = Union(.Range("AB2:AB" & lr), .Range("AM2:AM" & lr), .Range("AZ2:AZ" & lr))
For Each cl In rng
If Not IsDate(cl.Value) And Not IsEmpty(cl) Then _
mssg = mssg & cl.Address(0, 0) & Space(4)
Next cl
End With
If CBool(Len(mssg)) Then
MsgBox ("Please enter valid date(s) in Cell(s): " & Chr(10) & Chr(10) & _
mssg & Chr(10) & Chr(10) & _
"Example: dd/mm/yyyy")
Else
MsgBox "All dates completed!"
End If
Set rng = Nothing
End Sub
I've used a single lastrow from column AB to determined the scope of the cells to be examined but individual rows for each column could easily be compensated for.
Addendum: Code modified for a single message showing rogue non-date/non-blank cells (as below). The Chr(10) is simply a line feed character.
                     

SUM formula VBA

I am trying to calculate the sum of changing cell range in vba. Unfortunately the cell values are variables. I can't seem to get the following formula to work.
Private Sub calcOverheadRate(startCell As Integer, endCell As Integer)
Total = endCell + 1
Range("D" & Total).Formula = "=SUM("D" & startCell & ":" & "D" & endCell)"
End Sub
I get compile error: "Expected: end of statement
To solve this problem I changed the function to,
Private Sub calcOverheadRate(startCell As Integer, endCell As Integer)
Dim start As String
Dim endC As String
start = "D" & CStr(startCell)
endC = "D" & CStr(endCell)
Total = endCell + 1
Range("D" & Total).Formula = "=SUM(start:endC)"
End Sub
The function compiles fine, when I run it, the value in the cell is "#NAME" where it references SUM(start:endC) not SUM(D5:D23)....
Any thoughts on how to solve this would be appreciated.
The quotes are the issue:
Range("D" & Total).Formula = "=SUM(" & startCell & ":" & endCell & ")"
I have figured out the problem the & needs to be inside the quotation for string literals
Range("D" & Total).Formula = "=SUM(" & start & ":" & endC & ")"
How about you try using a table?
Here is a 1 min video on how to make a table in Excel:
http://www.screenr.com/VvZ8