Loop Through Column Using If Statement Checking =isnumber() - vba

I'm just starting to use VBA and I would like some help with writing an IF statement that is searching using =ISnumber() as it loops through all of column A until it encounters an empty cell.
The data I am working with is a text file that is being dropped onto sheet1 and has data that only populates column A.
On sheet2 I would like to press a button that starts a loop. The loop needs to check each row of sheet 1 to see what the first three numbers of the line is for example: =ISNUMBER(SEARCH("101",A1)) If this qualification is met then complete something like: =MID(A1,24,6)
There are two different row starts: 101 and 621.
My pseudo code logic is as follows:
Sub Button1_Click()
IF 'first iteration
Row A1 starts with "101"
THEN Add =MID(A1,24,6) to cell A1 of sheet 2
ELSE IF
Row starts with "621"
THEN Add =MID(A1,55,24) to cell B1 of sheet 2
AND add =MID(A1,30,10) to cell C1 of sheet 2
ELSE
Skip this row
End If
IF 'second iteration
Row A2 starts with "101"
THEN Add =MID(A2,24,6) to cell A2 of sheet 2
ELSE IF
Row starts with "621"
THEN Add =MID(A2,55,24) to cell B2 of sheet 2
AND add =MID(A2,30,10) to cell C2 of sheet 2
ELSE
Skip this row
End If
'iterations continue until empty cell
End Sub

You can do it like this - you may have to change sheet names to suit. That said, you don't need VBA for this, you could do it with formulae.
Sub Button1_Click()
Dim r As Range
With Sheet1
For Each r In .Range("A1", .Range("A" & Rows.Count).End(xlUp))
If Left(r, 3) = "101" Then
Sheet2.Range(r.Address).Formula = "=MID(Sheet1!" & r.Address & ",24,6)"
ElseIf Left(r, 3) = "621" Then
Sheet2.Range(r.Offset(, 1).Address).Formula = "=MID(Sheet1!" & r.Address & ",55,24)"
Sheet2.Range(r.Offset(, 2).Address).Formula = "=MID(Sheet1!" & r.Address & ",30,10)"
End If
Next r
End With
End Sub

Related

Excel VBA Getting value on One sheet to be parameter for search results on another sheet

I have a sheet called "lookup" and in cell B2 of that sheet, users can input a department code (ex: 190) and select a "Search" button:
Once they hit the search button it will take them to a sheet called "department_lookup" which in column A has account codes with the department code 190 in it and in column B has the account code description. In cell C1, though, I want to have the value being searched for populate cell C1 that way the query in sheet "department_lookup" can refresh to show proper data. Here is what sheet "department_lookup" looks like:
In column A & B would be a list depending on how many account codes have the department code 190 in it.
Essentially, the data in sheet department_lookup is a dynamic query and I'd like cell C1 to be the parameter value that alters the query to display the account codes that the user is searching for in cell B2 in the sheet lookup.
Here's the code I have for sheet lookup:
On Error GoTo Done:
If Target.Column = 2 And Target.Cells.Count = 1 Then
Cancel = True
mycell = Sheets("department_lookup").Range("$C$1").Value
If mycell = " " Then GoTo Done:
Sheets("department_lookup").Activate
End If
Sheets("acct_codes").Visible = False
Sheets("dept_list").Visible = False
Cancel = True
Application.ScreenUpdating = True
End Sub
Here is the vba i have for sheet department_lookup:
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Address = "$C$1" Then
With ActiveWorkbook.Connections("deptlookup").OLEDBConnection
.CommandText = "select seg1_code+'-'+seg2_code+'-'+seg3_code+'-'+seg4_code as account_code, account_description from glchart as GL where GL.inactive_flag = 0 and seg2_code='" & Range("C1").Value & "' order by seg1_code"
End With
ActiveWorkbook.Connections("deptlookup").Refresh
End If
End Sub
Currently, when I manually change the value of cell C1 to a different department code, the query in department_lookup will change to display the proper codes but, I think my issue is properly setting C1 to equal whatever the user searched for in cell B2 in sheet lookup. Can anyone help out with this?
Set that sheet's c1 to equal the cell of your initial sheet upon click of the submit button, then filter per C1 such as:
Sheets("department_lookup").Cells(1, 3).Value = Sheets("lookup").Cells(2, 2).Value
With Sheets("department_lookup")
.Range(.Cells(1, 1), .Cells(LR, LC)).AutoFilter field:=3, Criteria1:=.Cells(1, 3).Value, VisibleDropDown:=True
End With
You would define the LR as the last row and the LC as last column.

copy data using vlookup and if

I have a code which works good but i want some modifications as
Value of cell B5 in Sheet "feb" If sheets("Feb").Range("I5:AK81)<>"" (if any of the cell in range is none-blank and Sheets("Jan").Range("I5:AM81") is not equal to "TRF." means if any of the the cell in range is not equal to "TRF." then VLookup cell B5 in sheet "Jan" in range Sheets("master").Range("H7:Q200"),1,0) and copy it and paste in cell B5 of sheet "Feb".
and go to last blank column in range B5:B81 of sheet feb and if any of date in column O of Sheets("master").Range("H7:q200") falls only within current month of current year then copy appropriate cell b in the range and paste in last empty cell of sheet "Feb" range B5:B81 and so on
Below is code
Option Explicit
Sub CopyRows()
Dim Cl As Range
Dim str As String
Dim RowUpdCrnt As Long
str = "WRK.*" 'string to look for
Sheets("Feb").Range("B5:B81").Value = ""
RowUpdCrnt = 5
' In my test data, the "WRK."s are in column AN. This For-Each only selects column AN.
' I assume all my "WRK."s are in a single column. Replace "B" by the appropriate
' column letter for your data.
With Sheets("Jan")
' loop until last row with data in Column AN (and not the entire column) to save time
For Each Cl In .Range("AN1:AN" & .Cells(.Rows.Count, "AN").End(xlUp).Row)
If Cl.Value Like str And Sheets("Feb").Range(Cl.Address).Value <> "" Then
'if the cell contains the correct value copy it to next empty row on sheet 2 & delete the row
If Not IsError(Application.Vlookup(.Range("B" & Cl.Row).Value, Sheets("Master").Range("H7:H200"), 1, 0)) Then ' <-- verify the VLookup was successful
Sheets("Feb").Range("B" & RowUpdCrnt).Value = Application.Vlookup(.Range("B" & Cl.Row).Value, Sheets("Master").Range("H7:H200"), 1, 0)
RowUpdCrnt = RowUpdCrnt + 1
End If
End If
Next Cl
End With
Application.CutCopyMode = False
End Sub
If AND(criteria1,critieria2) then
This should allow you a second criteria, and not need to nest another if statement.
Kind of hard to follow the direction you're going, so correct me if this is wrong. Not quite getting the "so on" part of this, but we can try to break down some of this:
.1) then VLookup cell B5 in sheet "Jan" in range Sheets("master").Range("H7:Q200"),1,0)
'You've got this. I would recommend index/match
'using application and worksheet function commands.
.2) copy it and paste in cell B5 of sheet "Feb".
With Sheets("Feb").Range("B5").PasteSpecial xlPasteValues
.3) go to last blank column in range B5:B81 of sheet feb
Dim LR as Long 'LR is last row
LR = Cells(Sheets("Feb").Rows.Count, 1).End(xlUp).Row
.4) if any of date in column O of Sheets("master").Range("H7:q200") falls only within current month of current year
'Assuming this sheet based... Assuming H is the date column
If Sheets("master").Range("H7:H200").Value = "2" Then
.4a) then copy appropriate cell b in the range
'use index/match with output being Column(2)/B
WorksheetFunction.Index(rangeB,WorksheetFunction.Match(reference,rangeH)).Copy
.4b) paste in last empty cell of sheet "Feb" range B5:B81
Sheets("Feb").Cells(LR+1,2).PasteSpecial xlPasteValues
.5) so on
This will hopefully give a start to you. Just think about each line procedurally, if you can.

Search for same values in sheet1 and sheet2 and copy the values from sheet1 to sheet2

I have worked along time with excel but aren't very good at VBA, so I need help to make an macro and I cant get a recording macro to work :(
I have an excel file with 2 sheets (Sheet1 and Sheet2).
I want to compare a text from Sheet2 (column A) with sheet1 (column B) and if it finds same text in both sheets so do I want the macro to copy column A,B,C and D from sheet1 over to column B,C,D and E in sheet2.
In sheet 1 I have more than 6000 rows so I don't want to do this manually or do a formula in excel, I want a macro that does this for me.
The sheets have headers, can someone maybe help me with this ?
I'm a little unclear on what you are trying to do. This is my interpretation: suppose that, for a value in row X column A on sheet 1 -- if you find a corresponding value on sheet 2 in row Y column B -- you want to copy from sheet 1 the cells on row X belonging to columns A B C D and paste them on sheet 2 in row Y columns B C D E.
If that is correct, try this:
Sub copyCells()
Dim wb As Workbook, firstWs As Worksheet, secondWs As Worksheet
Dim matchIndex As Integer
Set wb = ThisWorkbook
Set firstWs = wb.Worksheets(1)
Set secondWs = wb.Worksheets(2)
Application.ScreenUpdating = False
' We'll start at i=2 to account for the header
For i = 2 To firstWs.Range("A2:A6000").Rows.count
On Error Resume Next
' MATCH will find the row number in sheet 2 - change the range specifications as needed
matchIndex = Application.WorksheetFunction.Match(firstWs.Range("A" & i), secondWs.Range("B2:B6000"), 0)
Err.Clear
On Error GoTo 0
' MATCH will throw an error if it finds no results.
' Hence: if matchindex contains an error, do nothing.
' But if it doesn't contain an error, it must contain a row number - so we can proceed.
If Not Application.WorksheetFunction.IsNA(matchIndex) Then
secondWs.Range("B" & matchIndex).Value = firstWs.Range("A" & i).Value
secondWs.Range("C" & matchIndex).Value = firstWs.Range("B" & i).Value
secondWs.Range("D" & matchIndex).Value = firstWs.Range("C" & i).Value
secondWs.Range("E" & matchIndex).Value = firstWs.Range("D" & i).Value
End If
Next i
Application.ScreenUpdating = True
End Sub

Copy only first entered value into cell

I have this problem: in Excel file I have two sheets. In first sheet I am entering values, changing values, deleting values... Sometimes, in one cell I enter value like this 125+138+458
Now, I need to copy values into next sheet, but only values that have been first entered into first sheet.
I found this code:
Private Sub Worksheet_Change(ByVal Target As Excel.Range)
Dim VRange As Range, cell As Range
Dim Msg As String
Dim ValidateCode As Variant
Set VRange = Range("B119:H130")
For Each cell In Target
If Union(cell, VRange).Address = VRange.Address Then
Cells(cell.Row, Columns.Count).End(xlToLeft).Offset(, 1) = Date & " " & Time
Cells(cell.Row, Columns.Count).End(xlToLeft).Offset(, 1) = cell.Value
End If
Next cell End Sub
that is ok, because now I have time of change and value that change...I need to have cell value of header of column and only first change of cell.
how to do that?
in your 2nd sheet, you can put this in a cell: ยด=Sheet1!A1".
Sheet 1:
A1: 50
B1: =A1 + 20
Sheet 2:
A1: =Sheet1!A1 //Will output "50"
B1: =Sheet1!B1 //Will output '70"
Change A1from sheet 1 to any other value, and the 2 cells in sheet 2 will update as well.

Find If cell matches in another sheet and count/sum instances

I have been using simple excel array formulas to count certain values on a master sheet but now at the point where I have too many formulas in my document and excel is crashing.
Therefore, I would like to create a macro that can do the same task. I would like to have the code do the following:
IF the activecell in Sheet1 matches to any cell in a column(or range) in Sheet2,
AND IF the cell in the same row in an adjacent column in Sheet2 is not blank,
THEN count all the instances that specific string appears in Sheet2 column A
AND place the value 2 columns to the right of the original active cell in Sheet1.
Here is the original array formula I was using:
=SUM(IF(Sheet1!$A8=Sheet2!$A:$A,IF(SalesF_SignUp_data!$C:$C>1,1,0)))
The formula above is taking the cell A8 in Sheet1 and checking if it matches to any cell in Sheet2 column A,
AND making sure that column C in Sheet2 is not blank in the same row.
If this is TRUE then "add 1" for all the instances
AND place that value in Sheet1.
I believe the best way to do this is a For Next Loop but haven't been able to execute any successful code based on examples I've found.
Im happy to explain further if needed. Since I dont have a reputation of 10 I cant attach images but am willing to send if needed.
This is set up to run for all the cells you've selected in column A of sheet 1.
It looks in Sheet2 column A for the value on Sheet1 column A, then in Sheet1 column B, displays how many times the value appeared in Sheet2 column A along with a value in the same row of column C.
If the answer is helpful, please mark it as such. :-)
Option Explicit
Sub countinstances()
Dim result, counter, loopcount, tocomplete, completed As Integer
Dim findtext As Variant
Dim cell, foundcell, nextcell As Range
'Checks to make sure the sub isn't accidentally run on an invalid range
If ActiveSheet.Name <> "Sheet1" Or ActiveCell.Column <> 1 Or Selection.Columns.Count > 1 Then
MsgBox ("Please select a range in column A of Sheet 1.")
Exit Sub
End If
'In case of selecting the entire column A, curtail the number of blank cells it runs on.
tocomplete = Application.WorksheetFunction.CountA(Selection)
completed = 0
'For each cell in the selected range, searches Sheet2, Column A for the value in the selected cell
For Each cell In Selection
If completed = tocomplete Then Exit Sub
If cell.Value <> "" Then completed = completed + 1
findtext = cell.Value
result = 0
Set foundcell = Sheets("Sheet2").Range("A1")
'Uses the count function to determine how many instances of the target value to search for and check
loopcount = Application.WorksheetFunction.CountIf(Sheets("Sheet2").Range("A:A"), findtext)
'Skips the loop if the target value doesn't exist in column A
If loopcount = 0 Then GoTo NotFound
'For each time the target value was found, check the cell in column C. If it's not blank, increment "result"
For counter = 1 To loopcount
Set nextcell = Sheets("Sheet2").Range("A:A").Find(what:=findtext, lookat:=xlWhole, after:=foundcell)
If nextcell.Offset(0, 2).Value <> "" Then
result = result + 1
End If
Set foundcell = nextcell
Next
'Put the result in column B of Sheet1
NotFound:
cell.Offset(0, 1).Value = result
Blanks:
Next
End Sub