Merging excel cells isn't works how its supposed to - vba

mycode :-
Public Sub CombineCells()
'Use to mash all cells with there contents into one
Dim selectedCells As Range
Dim cell As Range
Dim cellText As String
Application.DisplayAlerts = False
cellText = ""
Set selectedCells = Selection
For Each cell In selectedCells
cellText = cellText & cell.Value & " "
Next
selectedCells.merge
selectedCells.Value = Trim(cellText)
selectedCells.WrapText = True
Application.DisplayAlerts = True
End Sub
Basically I want to merge cells from A1 to H6, Range A1:H6, into the same cell without losing the data in the cells (they are going to have the same number in every cell((like same value/)) when I run my code, it saves the date and merges the cells but the numbers are going like this
But I want it to be like this (merged into one cell and without the border.
What am I doing wrong in my code?

I cant imagine why you would want to merge cells in such a way, but you were close none the less.
Since your range is static, define your range explicitly. Avoid .Selection & .Select when possible.
Sub Test()
Dim selectedCells As Range
Dim cell As Range
Dim cellText As String
Application.DisplayAlerts = False
cellText = ""
Set selectedCells = Range("A1:H6")
For Each cell In selectedCells
cellText = cellText & cell.Value & " "
Next
selectedCells.Merge
selectedCells.Value = Trim(cellText)
selectedCells.WrapText = True
Application.DisplayAlerts = True
End Sub
You can find lists of cell appearance properties online or here is the first one Google pulled for me. here
You can use the With feature to quickly apply a bunch of formats to your range without having to continuously qualify the range
With selectedcells
.Merge
.Value = Trim(cellText)
.WrapText = True
End With

Related

Excel VBA function to make a cell text 'BOLD' won't work

Public Function highlight_text(Search)
Dim rng As Range
Dim cell As Range
Set rng = Range("A2:H32")
For Each cell In rng
If cell.text = Search Then
cell.Font.ColorIndex = 3
cell.Font.Name = "Arial"
cell.Font.Size = 14
cell.Font.Bold = True
Else
cell.Font.Bold = False
cell.Font.Size = 11
cell.Font.ColorIndex = 1
End If
Next cell
End Function
The above function is called on 'mouseover' a cell, it manages to set the proper cells to RED color but it won't make the text bold
You cannot call a function from the worksheet and change the format of a cell.
(The fact that even the color is changing is perplexing)
As this does not need to be a function, it does not return anything and you cannot use it from the worksheet, we can make it a sub:
Public Sub highlight_text(Search)
Dim rng As Range
Dim cell As Range
Set rng = Range("A2:H32")
For Each cell In rng
If cell.Text = Search Then
cell.Font.ColorIndex = 3
cell.Font.Name = "Arial"
cell.Font.Size = 14
cell.Font.Bold = True
Else
cell.Font.Bold = False
cell.Font.Size = 11
cell.Font.ColorIndex = 1
End If
Next cell
End Sub
Use a Worksheet_Change Event(or some other event) to call the sub:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Not Intersect(Target, Range("A2:H32")) Is Nothing Then
highlight_text (Target.Text)
End If
End Sub
Put both of these in the worksheet code in which you want the code to run.
This will now highlight the like cells as you click on any cell in the range.
This is a good solution in this case. But I am confused by the statement that you cannot change to format of a cell in a function. Tried this to confirm. It works fine.
Function boldit() As String
Dim theCell As String
theCell = "Q8"
Range(theCell).Value = "XorY"
Range(theCell).Font.Color = RGB(255, 0, 0)
Range(theCell).Font.Bold = True
End Function
The reason I'm interested is that in a real function I have written the same .Font.Bold statement does not work (while the .Font.Color does)
Any other idea why .Font.Bold=True might not work

VLookup On Another Workbook

Trying to make a macro that will take an input (a 13 digit number) from cell A7, A8, A9 and so forth until a blank cell is reached, and run a vlookup with this against another workbook.
However, I'm just getting the #N/A error and I can't work out why.
My current code:
Sub getData()
Application.EnableEvents = False
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Application.Calculation = xlManual
Dim wb As Workbook, src As Workbook
Dim srcRange As Range
Dim InputString
Dim OutputString
Dim i As Long
Set wb = ActiveWorkbook
Set src = Workbooks.Open("D:\Files\test1.csv", True, True)
Set srcRange = src.Sheets(1).Range("A1:H1").End(xlDown)
i = 7
Do While wb.ActiveSheet.Cells(i, 1) <> ""
InputString = wb.Worksheets("Sheet 1").Cells(i, 1)
OutputString = Application.VLookup(InputString, srcRange, 3, False)
wb.Worksheets("Sheet 1").Cells(i, 2) = OutputString
i = i + 1
Loop
src.Close (False)
Application.EnableEvents = True
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.Calculation = xlAutomatic
End Sub
I think it is worth noting that the reference I'm looking up ("InputString") is defined as custom format #0 in the "src" file. I don't really know if this matters too much, it should still be an integer?
Additionally, the "OutputString" could be either numbers or text, which is why I've purposefully let it undefined. I have tried defining it as 'Variant', 'String', and 'Integer' but that's not really changed anything.
Thanks.
Set srcRange = src.Sheets(1).Range("A1:H1").End(xlDown)
This will get you a range of one single cell, on column A, i.e. A20.
Doing a VLookup on a single cell is meaningless.
What you probably meant was this:
With Sheets(1)
Set srcRange = .Range("A1:H" & .Range("A1").End(xlDown).Row)
End With
This will set to something like A1:H20.
First you should change your src range which is actually set to grab only the bottom row, not the range from top to bottom. Try
Set wb = ActiveWorkbook
Set src = Workbooks.Open(""D:\Files\test1.csv", True, True)
With src.Sheets(1)
Set srcRange = .Range(.Range("A1"), .Range("H1").End(xlDown))
End With
Second, I don't believe the CSV file would support a 13 digit number except as text. VLOOKUP is very sensitive about text vs general vs number so if the new src range doesn't help, try converting the inputstring using CStr() first.
Good luck!

Hiding a variable RangeName based on value in other sheet

At the moment I'm working on making a working code smaller using an array. I will explain the code shortly;
If a certain part is required to be in a datasheet (this worksheet is called "High Pressure Grinding Rolls"), then the user can define this by putting in value "a" on Sheets("Invulformulier"). Now there are several parts which can be on the datasheet if the cell value is "a". If we have "partA", "partB" and "partC", the RangeName of the cell will be the name of the part on Sheets("Invulformulier"). The RangeName of the range on Sheets("High Pressure Grinding Rolls") will be the name of the part + "1". For example "partA1". This range must be hidden depending on if the user puts in "a" for "partA".
This is the code I used and worked, but is specific to the cell names:
Sub Hidecellv1 ()
If Range("partA").Value = "a" Then
Sheets("High Pressure Grinding Rolls").Range("partA1").EntireRow.Hidden = False
ElseIf Range("partA").Value = "" Then
Sheets("High Pressure Grinding Rolls").Range("partA1").EntireRow.Hidden = True
End If
End Sub
This code is very specific and I want to make an array. This is what I have so far:
Sub Hidecellwitharray ()
Dim rngName As Range
Dim cell As Range
Application.ScreenUpdating = False
For Each cell In Range("Checkbox") 'Where user puts in value "a" or not
If cell.Value = "a" Then
Sheets("High Pressure Grinding Rolls").Range(RangeName & "1").EntireRow.Hidden = False
Else
Sheets("High Pressure Grinding Rolls").Range(RangeName & "1").EntireRow.Hidden = True
End If
Next cell
Application.ScreenUpdating = True
End Sub
The searching for value "a" for every part works, but I can't get it to work to hide the parts in the datasheet if value "a" is or isn't inserted. How do I refer to a variable RangeName?
If I correctly understood your issue you could try this:
Option Explicit
Sub Hidecellwitharray()
Dim cell As Range
Application.ScreenUpdating = False
For Each cell In Range("Checkbox") 'Where user puts in value "a" or not
Sheets("High Pressure Grinding Rolls").Range(Split(cell.Name.Name, "!")(1) & "1").EntireRow.Hidden = Not cell.Value = "a"
Next cell
Application.ScreenUpdating = True
End Sub
Does this do as you require? It will hide all named ranges on the 'High Pressure Grinding Rolls' sheet, then show the row containing the corresponding checkbox value.
I found helpful information on the following page: Loop through all named ranges in a Excel Sheet
Sub Hidecellv1()
Dim nm
Dim rngName
For Each nm In ThisWorkbook.Names
If Left(nm.Name, 4) = "Part" Then
Sheets("High Pressure Grinding Rolls").Range(nm).EntireRow.Hidden = True
End If
Next nm
rngName = Range("checkbox").Value
Sheets("High Pressure Grinding Rolls").Range("Part" & rngName & "1").EntireRow.Hidden = False
End Sub

Remove text after a space across multiple columns in Excel using VBA

I have a list of items' monthly prices and the price columns have both the amount and currencies. I am trying to remove the currencies across multiple columns.
Sample data sets:
I wrote below macro to remove text after space of cells in A1:E6:
Sub RemoveCurrency()
Dim cell As Range
Dim withCurrency As String
Dim PriceOnly As String
For Each cell In Worksheets("Sheet1").Range("A1:E6")
withCurrency = cell.Value
PriceOnly = Left(withCurrency, InStr(withCurrency, " ") - 1)
cell.Value = PriceOnly
Next cell
End Sub
After I ran it, it gives me a VB run-time error '5':
Invalid procedure call or argument
Can someone help to debug my VBA code?
Am I right, reading "to remove text after space" as "including this space"? If so:
Dim sStr$
' ...
For Each cell In Worksheets("Sheet1").Range("A1:E6")
' ...
sStr = cell.Value
If LenB(sStr) Then cell.Value = Split(sStr, " ")(0)
'or
cell.Value = Split(sStr & " ", " ")(0)
' ...
Next
' I'm not sure which is faster... but LenB seems to me more realiable
This code is much longer/less efficient than yours, but it won't give you an error when it runs out of cells to edit, at least (it's a module I had already written in the past for nearly the exact same purpose). Alternatively, yours should work (but still error at the end) if you update the range to start at the cell where your currency amount starts. You can read more about VBA ranges in the MSDN Documentation.
It requires that you add a VBA reference to "Microsoft VBScript Regular Expressions 5.5" if you don't already have it checked. You can do that in Tools -> References.
Public Sub TruncateIDs()
Dim strPattern As String: strPattern = "[A-Z]{1,3}"
Dim strReplace As String: strReplace = ""
Dim regEx As New RegExp
Dim strInput As String
Dim MyRange As Range
Set MyRange = ActiveSheet.Range("B3:E6")
ActiveSheet.Range("B3").Select
Do While strPattern <> ""
strInput = ActiveCell.Value
With regEx
.Global = True
.MultiLine = True
.IgnoreCase = False
.Pattern = strPattern
End With
If regEx.Test(strInput) Then
ActiveCell = regEx.Replace(strInput, strReplace)
ActiveCell.Offset(1, 0).Select
ElseIf ActiveCell = "" Then
ActiveCell.Offset(-4, 1).Select
If ActiveCell <> "" Then
strInput = ActiveCell.Value
ActiveCell = regEx.Replace(strInput, strReplace)
ActiveCell.Offset(1, 0).Select
Else
Exit Do
End If
Else
Exit Do
End If
Loop
End Sub

Using VBA to search for a string (fuzzy logic)

I cobbled together this a few years ago and now I need it tweaked slightly but I'm very rusty with VBA so could do with some advice:
Sub Colour_Cells_By_Criteria()
Dim myRange As Range
Dim myPattern As String
Dim myLen As Integer
Dim myCell As Range
Set myRange = Range("A1:A1000")
myPattern = "*1*"
myLen = 4
Application.ScreenUpdating = False
Application.StatusBar = "Macro running, please wait...."
For Each myCell In myRange
With myCell
If (.Value Like myPattern) And (Len(.Value) = myLen) Then
myCell.Interior.Color = 65535
myCell.Font.Bold = True
End If
End With
Next
Application.ScreenUpdating = True
Application.StatusBar = False
End Sub
Rather than colouring and bolding any cells that are captured by the logic, I'd like to put the word "MATCH" in the same row in column B.
Any nudges in the right direction would be appreciated.
myCell.Offset(0,1).Value="Match"