Combine and Pass value from cells to another in Excel VBA - vba

Basically, I 'd like to combine values from two cell and then display it in another new cell after I click a button. The tricky part is every time when I enter a new value, it should display in the next row. For example, I shall combine value from A1 and B1 and pass it to C1. the next time I re-enter A1 and B1, the new value should pass to C2.
Here is the code I wrote:
Private Sub CommandButton2_Click()
Dim count As Integer
Dim rowNo As String
Dim val As String
Dim val2 As String
Dim sum As String
count = 1
rowNo = "C" + CStr(count)
If (Range("A1") <> "" And Range("B1") <> "") Then
val = Range("A1")
val2 = Range("B1")
sum = val + "/" + val2
Worksheets("Sheet1").Range(rowNo).Value = sum
count = count + 1
End If
End Sub
I am new to excel VBA, the above code only write value in A1 and it didnt go to next row when I re-enter the values, can anyone help me to solve this?

Besides answering your specific question, I will add a few (hopefully useful) comments on your code.
It is convenient to fully qualify ranges, e.g., use Worksheets("Sheet1").Range instead of Range, see this explanation.
To choose a Range you can use direct addressing (as in the comment by chris nielsen) or other options, as Offset, possibly convenient here.
It appears that your code will always go to the same target cell rowNo C1, since count is reset to 1. You will have to let your Sub know where to place the result, and this is key. I guess the safest option is to have one cell in your worksheet set to contain that information, and have your Sub reading it. If you know that column C will only contain the results you want, and that data will be contiguous there, then you could use the code below, which accounts for all items here.
It is often convenient to define a variable for using as reference, e.g., Dim rng as Range and Set rng = Worksheets("Sheet1").Range...
Code below should work.
Private Sub CommandButton2_Click()
Dim val As String
Dim val2 As String
Dim sum As String
Dim rng As Range
Dim ws As Worksheet
Set ws = Worksheets("Sheet1")
With Worksheets("Sheet2")
If (IsEmpty(.Range("C1"))) Then
Set rng = .Range("C1")
Else
' There are other options to find the last cell
Set rng = .Cells(.Rows.count, "C").End(xlUp).Offset(1, 0)
End If
If (ws.Range("A1") <> "" And ws.Range("B1") <> "") Then
val = ws.Range("A1")
val2 = ws.Range("B1")
' Added ' to prevent sum being converted into a date
'sum = "'" + val + "/" + val2
sum = "'" & val & "/" & val2
rng.Value = sum
End If
End With
End Sub
PS: there are some variations in the way to select the target range, depending on the contents of your worksheet.

Try
Worksheets("Sheet1").Range(rowNo).Value = sum

Related

Using VBA to fill a column based on the value in a separate sheet

I need to run a macro between two worksheets where say column C in "Sheet 1" has a "Y", I need column AP in "Sheet 2" to return something along the lines of "covered" or "Y". Just something to indicate that a Y was there in Sheet 1. I am mainly running issues in actually connecting the two worksheets. This code below works fine if I am running it on columns within the same work sheet.
Code:
Private Sub Set_Border_Pattern(Requirements_Selector_Str As String)
Dim strTemp As String
Dim strRange As String
Dim strCellVal As String
If Len(Requirements_Selector_Str) > 2 Then
strTemp = Mid(Requirements_Selector_Str, 4, 1)
Else
strTemp = Requirements_Selector_Str
End If
With Worksheets("test")
For i = 2 To REQUIREMENT_ROW_COUNT
strRange = strTemp & i
strCellVal = .Range(strRange).Value
If strCellVal = "Y" Then
Worksheets("NFR_List").Range(AP & i).Value = "Y"
End If
Next i
End With
The code below does what you describe in a very simple way. I believe that if you understand it you will be able to modify it for your situation. If not, please feel free to ask questions.
Sub test()
Dim sh1 As Worksheet, sh2 As Worksheet
Dim r1 As Range, r2 As Range, i As Long
Set sh1 = Worksheets("test")
Set sh2 = Worksheets("NFR_List")
Set r1 = sh1.Range("C1")
Set r2 = sh2.Range("AP1")
i = 0
While r1.Offset(i, 0) <> ""
If r1.Offset(i, 0) = "Y" Then r2.Offset(i, 0) = "Y"
i = i + 1
Wend
End Sub
I've assumed that Column C has no blank cells until the data is finished, but if this is not true, the code can be easily modified according to your needs.
Another approach would be to just use a formula for this (instead of VBA), such as =IF(test!C1="Y", "Y","") in AP1 (if the "NFR_List" sheet) and then drag the formula down. Or you could also put the formula in using VBA using code like, r2.offset(i,0).formula = ... . There are many ways.

Counting words in column and then display said amount on userform

I don't know if this is possible or if I'm just searching wrong keywords.
Basically I have user-form with multi-page arrangement and I wondered if it possible for one of multi-pages to display running tally of what on the worksheet.
Example:on spreadsheet (Data) column B description of asset: Laptop, Desktop, Printer etc. and then User-form looks at sheet (Data) and then display to end user on user-form running tally of Laptops = 7 Desktop = 9 Printers = 2.
Depending on how many words are in that column matching the word looking for.
I don't know where to start to create code to do is and I can't seem to find any help on any websites when searching Google (VBA User-form to display column count).
Sorry If I'm not asking in correct way on here just at complete loss with what to do.
Thank you in advance.
You can create a function to do this.
Assign all the cells in your column into a string, then push that string into your function.
Function countWords(ByVal sText As String) As Long
Dim sTextArr() As String
sTextArr = Split(sText, " ")
countWords = UBound(sTextArr) + 1
End Function
Sub test()
Dim myStr As String
myStr = "The dog barked non-stop. I wish he would stop"
MsgBox countWords(myStr)
End Sub
You would just assign the value of countWords to your userform control.
If you want to add the values into a ListBox with two columns on your UserForm, having the item in the first column and the count of items in the second column then the following will help:
Sub foo()
Dim k As Variant
Dim d As Variant
Dim c As Range
Dim rng As Range
Dim ws As Worksheet: Set ws = Sheets("Sheet1")
'declare and set your worksheet, amend as required
LastRow = ws.Cells(ws.Rows.Count, "B").End(xlUp).Row
'get the last row with data on Column B
Set rng = ws.Range("B2:B" & LastRow)
Set d = CreateObject("Scripting.Dictionary")
For Each c In rng
d(c.Value) = d(c.Value) + 1
Next c
For Each k In d
If k <> "" Then
ListBox1.AddItem k
ListBox1.List(ListBox1.ListCount - 1, 1) = d(k)
End If
Next k
End Sub

Excel count target then output value in cell

I have a workbook with three sheets (Dash, HT, RV.)
I am trying to write a macro/function that counts how many times a value from 'Dash' exists in a specific column within sheet 'RV' then output that value in a specific cell within 'Dash'
I could go so far as to say that the value within 'Dash' is static and repeat it (The variable from 'Dash' won't ever change as it's a list of Usernames)
In my head it's something like: Count whatever.variable.Dash in column J of sheet.RV print in Dash.B2...
I was able to find a MsgBox option that works, but I have to manually type in each Username (which is a 16character name (string)) then a MsgBox tells me the occurrences. I'm looking to just automate this option with a fixed/static username in the macro/function because the amount of rows in 'RV' can vary between 700 entries to 23k entries
The MsgBox option is:
Dim Count as Integer
Dim Target As String
Dim Cell as Object
Dim N As Integer
Sub Target_Count()
Count = 0
Target = InputBox("character(s) to find?")
If Target = "" Then GoTo Done
For Each Cell in Selection
N = InStr(1, cell.Value, target)
While N <> 0
Count = count + 1
N = InStr(n + 1, cell.Value, target)
Wend
Next Cell
MsgBox count & " Occurrences of " & target
Done:
End Sub
I want the input box target to be 'Dash.A1:8' and the occurrences to be printed in 'Dash.B1:8'
Can you just use a countif() formula rather than programming a macro? say the column you were counting the "dash"'s in was column B in sheet RV, Then in the cell in sheet Dash, the formula would be:
=COUNTIF(RV!B:B,"dash")
Or, if you wanted to vary what you were counting, you simply replace the hardcoded "dash" in the formula with the input cell address.
If you want VBA you can use this. Adjust it however you want.
Sub Target_Count_2()
Dim wb As Workbook
Set wb = ThisWorkbook
Dim Cell As Range
Dim Count As Integer
Dim LastRow As Long
LastRow = wb.Worksheets("RV").Range("A1").SpecialCells(xlCellTypeLastCell).Row
Dim strArr() As Variant
strArr() = wb.Worksheets("RV").Range("J1:J" & LastRow).Value
Dim i As Long
Dim str As String
For Each Cell In wb.Worksheets("Dash").Range("B1:B8")
Count = 0
str = Cell.Offset(, -1).Value2
For i = LBound(strArr) To UBound(strArr)
If str = strArr(i, 1) Then Count = Count + 1
'If InStr(strArr(i, 1), str) > 0 Then Count = Count + 1
Next
Cell.Value2 = Count
Next
Set Cell = Nothing
Set wb = Nothing
End Sub
Note that str = strArr(i, 1) will match only full value in cells, while InStr(strArr(i, 1), str) > 0 will also match parts in cells. Let's say you are looking for "AAA" in cell with the value "AAAB". The first method will not add additional 1 to the Count, while the second method will.

Filter out blank for a specific column

I was wondering if there was a way to run a macro in VBA to filter out blanks for a specific column. The column currently has either -1 or blanks in the cells. I am trying to add a macro so that it removes the blanks and only leaves the -1's in the cells. Thank you.
This is the code that I am attempting to run this macro.
O.K. Here is an example for blanks in column Z The rows will be hidden rather than deleted.
Sub HideSome()
Dim rHide As Range, col As String
col = "Z"
Set rHide = Intersect(Range(col & ":" & col), ActiveSheet.UsedRange).Cells.SpecialCells(xlCellTypeBlanks)
rHide.EntireRow.Hidden = True
End Sub
EDIT#1
Here is a version the uses the proper tab and the proper column:
Sub HideSome()
Dim s1 As Worksheet, s2 As Worksheet
Set s1 = ActiveSheet
Set s2 = Sheets("Current")
Dim rHide As Range, col As String
col = "Z"
s2.Activate
Set rHide = Intersect(Range(col & ":" & col), ActiveSheet.UsedRange).Cells.SpecialCells(xlCellTypeBlanks)
rHide.EntireRow.Hidden = True
s1.Activate
End Sub
We go to the tab with the data.....hide the rows....then return......

How to compare two columns in different sheets

I have one excel file with multiple sheets.
I need to compare two sheets (1) TotalList and (2) cList with more than 25 columns, in these two sheets columns are same.
On cList the starting row is 3
On TotalList the starting row is 5
Now, I have to compare the E & F columns from cList, with TotalList E & F columns, if it is not found then add the entire row at the end of TotalList sheet and highlight with Yellow.
Public Function compare()
Dim LoopRang As Range
Dim FoundRang As Range
Dim ColNam
Dim TotRows As Long
LeaData = "Shhet2"
ConsolData = "Sheet1"
TotRows = Worksheets(LeaData).Range("D65536").End(xlUp).Row
TotRows1 = Worksheets(ConsolData).Range("D65536").End(xlUp).Row
'TotRows = ThisWorkbook.Sheets(LeaData).UsedRange.Rows.Count
ColNam = "$F$3:$F" & TotRows
ColNam1 = "$F$5:$F" & TotRows1
For Each LoopRang In Sheets(LeaData).Range(ColNam)
Set FoundRang = Sheets(ConsolData).Range(ColNam1).Find(LoopRang, lookat:=xlWhole)
For Each FoundRang In Sheets(ConsolData).Range(ColNam1)
If FoundRang & FoundRang.Offset(0, -1) <> LoopRang & LoopRang.Offset(0, -1) Then
TotRows = Worksheets(ConsolData).Range("D65536").End(xlUp).Row
ThisWorkbook.Worksheets(LeaData).Rows(LoopRang.Row).Copy ThisWorkbook.Worksheets(ConsolData).Rows(TotRows + 1)
ThisWorkbook.Worksheets(ConsolData).Rows(TotRows + 1).Interior.Color = vbYellow
GoTo NextLine
End If
Next FoundRang
NextLine:
Next LoopRang
End Function
Please help with the VBA code.
Thanks in advance...
First I am going to give some general coding hints:
set Option Explicit ON. This is done through Tools > Options >
Editor (tab) > Require Variable Declaration . Now you HAVE to
declare all variables before you use them.
always declare a variables type when you declare it. If you are unsure about what to sue or if it can take different types (not advisable!!) use Variable.
Use a standard naming convention for all your variables. Mine is a string starts with str and a double with dbl a range with r, etc.. So strTest, dblProfit and rOriginal. Also give your variables MEANINGFUL names!
Give your Excel spreadsheets meanigful names or captions (caption is what you see in excel, name is the name you can directly refer to in VBA). Avoid using the caption, but refer to the name instead, as users can change the caption easily but the name only if they open the VBA window.
Ok so here is how a comparison between two tables can be done with your code as starting point:
Option Explicit
Public Function Compare()
Dim rOriginal As Range 'row records in the lookup sheet (cList = Sheet2)
Dim rFind As Range 'row record in the target sheet (TotalList = Sheet1)
Dim rTableOriginal As Range 'row records in the lookup sheet (cList = Sheet2)
Dim rTableFind As Range 'row record in the target sheet (TotalList = Sheet1)
Dim shOriginal As Worksheet
Dim shFind As Worksheet
Dim booFound As Boolean
'Initiate all used objects and variables
Set shOriginal = ThisWorkbook.Sheets("Sheet2")
Set shFind = ThisWorkbook.Sheets("Sheet1")
Set rTableOriginal = shOriginal.Range(shOriginal.Rows(3), shOriginal.Rows(shOriginal.Rows.Count).End(xlUp))
Set rTableFind = shFind.Range(shFind.Rows(5), shFind.Rows(shFind.Rows.Count).End(xlUp))
booFound = False
For Each rOriginal In rTableOriginal.Rows
booFound = False
For Each rFind In rTableFind.Rows
'Check if the E and F column contain the same information
If rOriginal.Cells(1, 5) = rFind.Cells(1, 5) And rOriginal.Cells(1, 6) = rFind.Cells(1, 6) Then
'The record is found so we can search for the next one
booFound = True
GoTo FindNextOriginal 'Alternatively use Exit For
End If
Next rFind
'In case the code is extended I always use a boolean and an If statement to make sure we cannot
'by accident end up in this copy-paste-apply_yellow part!!
If Not booFound Then
'If not found then copy form the Original sheet ...
rOriginal.Copy
'... paste on the Find sheet and apply the Yellow interior color
With rTableFind.Rows(rTableFind.Rows.Count + 1)
.PasteSpecial
.Interior.Color = vbYellow
End With
'Extend the range so we add another record at the bottom again
Set rTableFind = shFind.Range(rTableFind, rTableFind.Rows(rTableFind.Rows.Count + 1))
End If
FindNextOriginal:
Next rOriginal
End Function