How to remove spaces at start and end of a cell? - excel

I have an imported CSV in my spreadsheet. When I run a refresh macro it adds a space to the beginning and end of each cell.
I'm trying to remedy it by having the same macro trim all the spaces at the start and end of a cell (not in between).
Doing it on a single cell works without issue
Range("F10").Value = Trim(Range("F10").Value)
In a range it doesn't do anything, no error message, just no reaction
Dim cell As Range, areaToTrim As Range
Set areaToTrim = Sheet1.Range("A6:J10")
For Each cell In areaToTrim
cell.Value = Trim(cell.Value)
Next cell
In reality, I don't want it to be A6 to J10, I just put this in to see if it worked with a range. I want it to be A6 to J last row. So I wanted my final code to be
Dim lastrowindex As Long
lastrowindex = ActiveSheet.Cells(ActiveSheet.Rows.Count, "A").End(xlUp).Row
Dim db_range_start As String
Dim db_range_end As String
db_range_start = "A6"
db_range_end = "J" & lastrowindex
db_range_region = db_range_start & ":" & db_range_end
Dim db_range As Range
Set db_range = Range(db_range_region)
Dim cell As Range, areaToTrim As Range
Set areaToTrim = Sheet1.Range(db_range)
For Each cell In areaToTrim
cell.Value = Trim(cell.Value)
Next cell
But this throws a
Method Value of object Range failed.

How about the following, just took your code and simplified it, as you declared db_range as a Range and then tried to use it to specify the range using Sheet1.Range(db_range) which would take a string instead of a Range:
Sub Trim_Range()
Dim ws As Worksheet: Set ws = Sheet1
Dim LastRow As Long
Dim c As Range
LastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
For Each c In ws.Range("A6:J" & LastRow)
c.Value = Trim(c.Value)
Next c
End Sub

Related

VBA set multiple variable from cell value

I want to do that; i1=A2.value i2=A3.value i3=A4.value ..... but ı dont know how to start it.
Public Sub SetVariable()
Dim cell As Range
Dim rng As Range
Dim i As Integer
Set rng = Range("B2", Range("B1").End(xlDown))
For Each cell In rng
For i = 1 To rng
i = Range("A" & cell.Row)
Next i
Next cell
End Sub

How to make each cell's length to be 5?

I have a column with 7000+ names. I want to make each name's length not excess to 5. Here is what I have tried which doesn't work
Sub del()
Dim myCell
Set myCell = ActiveCell
Dim count As Integer
count = Len(ActiveCell)
While count > 5
myCell = Left(myCell, Len(myCell) - 1)
myCell.Offset(1, 0).Select
Set myCell = ActiveCell
Wend
End Sub
No need for VBA. You can use a formula, =Left(A1,5), to get the first 5 characters of the cell. Simply autofill the formula down.
If you still want VBA then also you do not need to loop. See this example. For explanation see Convert an entire range to uppercase without looping through all the cells
Option Explicit
Sub Sample()
Dim ws As Worksheet
Dim lRow As Long
Dim rng As Range
'~~> Change this to the relevant sheet
Set ws = ThisWorkbook.Sheets("Sheet1")
With ws
lRow = .Range("A" & .Rows.Count).End(xlUp).Row
Set rng = .Range("A1:A" & lRow)
rng = Evaluate("index(left(" & rng.Address(External:=True) & ",5),)")
End With
End Sub
In the above code I am assuming that the data is in column A in Sheet1. Change as applicable.
In Action

Add to Listbox if cell value contains specific string

I am trying to add data to a Listbox on a Userform, based on the value of the the Cell in column C of the range that is searched. If the cell in column C contains a certain string I would like it to be added to the Listbox.
The below code is as far as I have got but it is returning an empty Listbox with no error.
Private Sub OptionButton12_Click()
Dim I As Integer
Dim lastRow As Integer
Dim searchString As String
searchString = "LISTBOXENTRY"
With ThisWorkbook.Sheets("Sheet1")
lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
End With
Plybooks.ListBox1.Clear
For I = 1 To lastRow
If Cells(I, 3).Value = searchString Then
Plybooks.ListBox1.AddItem Range("A" & I)
End If
Next I
End Sub
Try using the script below and please let me know if it works!
based on your script above, I assumed some of the dataframe dimensions. please let me know if it is not correct so I can tweak it.
I assumed you are working on first sheet (sheets(1)), and col C is the column you are using for the value check against the "searchString" variable. (if true, append the value in listbox1)
Thanks
Private Sub OptionButton12_Click()
Dim lastRow As Integer
Dim searchString As String
Dim wb As Workbook
Dim sRng As Range
Dim cel As Range
'assign current wb into wb workbook object
Set wb = ThisWorkbook
'assign str you want to search into variable
searchString = "LISTBOXENTRY"
'find last row number in colC (3) using crow function. (assuming you want to do a check on every cell listed in column C)
lastRow = crow(1, 3)
plybooks.listbox1.Clear
'assign range object using dataframe dimensions based on row 1 col C (lbound), to lastrow col3 (ubound)
With wb.Sheets(1)
Set sRng = .Range(.Cells(1, 3), .Cells(trow, 3))
End With
'loops through each cel
For Each cel In sRng
If cel.Value = searchString Then
'adds item into listbox1 if conditional statement is True
plybooks.listbox1.AddItem Item:=cel.Value
Else
End If
Next cel
End Sub
Private Function crow(s As Variant, c As Integer)
crow = Sheets(s).Cells(Rows.Count, c).End(xlUp).Row
End Function
Added cell values in ranges over multiple sheets if cell contains certain value, using the following:
Public Sub PlybookListbox()
'Clear fields before start
Plybooks.ListBox1.MultiSelect = 0
Plybooks.ListBox1.Clear
Plybooks.ListBox1.Value = ""
Plybooks.ListBox1.MultiSelect = 2
Dim AllAreas(2) As Range, Idx As Integer, MyCell As Range, TargetRange As Range
Dim lastrowFrontWing As Long
Dim lastrowNose As Long
Dim lastrowBargeboard As Long
lastrowFrontWing = Worksheets("Front Wing").Cells(Rows.Count, 2).End(xlUp).Row
lastrowNose = Worksheets("Nose").Cells(Rows.Count, 2).End(xlUp).Row
lastrowBargeboard = Worksheets("Bargeboard & SPV").Cells(Rows.Count, 2).End(xlUp).Row
Set AllAreas(0) = Worksheets("Front Wing").Range("c6:c" & lastrowFrontWing)
Set AllAreas(1) = Worksheets("Nose").Range("c6:c" & lastrowNose)
Set AllAreas(2) = Worksheets("Bargeboard & SPV").Range("c6:c" & lastrowBargeboard)
Plybooks.ListBox1.Clear
For Idx = 0 To 2
For Each MyCell In AllAreas(Idx).Cells
If InStr(1, MyCell.Value, "(FS)") > 0 Then
Plybooks.ListBox1.AddItem MyCell.Value
End If
Next MyCell
Next Idx
End Sub

Autofill with VBA in this specific flow

Please i have this issue and i am trying to achieve a solution using vba.
So cell
A1 has value John
A2-A3 blank
A4 has value Mary
A5-A9 blank
A10 has value Mike
A11-A14 blank
And A15 has value David
I wanna autofill only the blank spaces in the column A, like so:
A2-A3 the blanks will be filled with John
A5-A9 will be filled with Mary
A11-A14 with Mike.
So technically, I am auto filling the blank cells with the value from above
One version to do this is:
Sub Autofill1()
Dim ws As Worksheet
Dim lrow As Long
Dim i As Long
Set ws = Worksheets("Sheet1") 'Set your worksheet name
lrow = ws.Cells(Rows.Count, "A").End(xlUp).Row 'Find last row
For i = 1 To lrow 'Loop from 1st row to last row
If ws.Cells(i, "A").Value = "" Then 'If the cell value is blank then...
ws.Cells(i, "A").Value = ws.Cells(i - 1, "A").Value '.. copy the value from previous cell above
End If
Next i
End Sub
Another version is:
Sub Autofill2()
Dim ws As Worksheet
Dim FillRange As Range
Set ws = Worksheets("Sheet1") 'Set your worksheet name
On Error GoTo Errhand 'If range already is filled then go to error handler
For Each FillRange In Columns("A:A").SpecialCells(xlCellTypeBlanks) 'Define range in column A
If FillRange.Cells.Row <= ActiveSheet.UsedRange.Rows.Count Then 'Check if current row is smaller than last row
FillRange.Cells = ws.Range(FillRange.Address).Offset(-1, 0).Value 'Fill the empty cells with the non empty values
End If
Next FillRange
Errhand:
If Err.Number = 1004 Then MsgBox ("Column is already filled")
End Sub
It has been a long time, but if I'm not mistaken, the following should work:
Dim i As Integer, firstcell As Integer, lastcell As Integer
Dim currentValue As String
firstcell = 1
lastcell = 15
currentValue = ""
For i = firstcell To lastcell
If Cell(i,1).Value = "" Then
Cell(i,1).Value = currentValue
Else
currentValue = Cell(i,1).Value
End If
Next i
You loop through the cells and if there is nothing in them you write the last value in them. If they contain data, you update the currentValue
This solution using for each for more efficient looping.
Sub AutoFillIt()
Dim lLastRow As Long 'Last row of the target range
lLastRow = Cells(Rows.Count, "A").End(xlUp).Row 'Get number of rows
Dim rngCurrentCell As Range
Set rngCurrentCell = Range("A1") 'It will used for looping through the range
Dim rngTarget As Range
Set rngTarget = rngCurrentCell.Resize(lLastRow) 'Set the range working in
Dim vLastValue As Variant ' To store the value of the last not emplty cell
Dim v As Variant
For Each v In rngTarget 'looping through the target range
If v = "" Then 'if the cell is empty, write the last value in
rngCurrentCell.Value = vLastValue
Else 'if not empty, store the content as last value
vLastValue = v
End If
Set rngCurrentCell = rngCurrentCell.Offset(1) 'move to the next cell
Next v
End Sub

How to convert different cell value to single row using vba in excel?

I want to transfer data from one sheet to another.
My sheet1 is "form" type sheet. I have command button in it.
On pressing of command button cell value should be copied to another Sheet2.
I want every copy of value should be in one row and fixed column.
It should not be overwrite but enter in next empty row.
I am using below VBA code:
Private Sub Button1_Click()
Dim rng As Range
Set rng = Sheets("Sheet1").Range("A1,A2,B1,B2,B3")
For Each cell In rng
'here you copy to another sheet, one row lower
Sheets("Sheet2").Cells(cell.Row + 1, cell.Column).Value = cell.Value
Next cell
For x = lRow To 2 Step -1
If Range("I" & x) <> vbNullString Then Range("I" & x).EntireRow.Delete
Next x
Application.CutCopyMode = False
End Sub
Option Explicit
Sub test()
Dim ws1 As Worksheet, ws2 As Worksheet
Dim LastRow As Long, i As Long
Dim str As String, chara As Variant
Dim rng As Range, cell As Range
With ThisWorkbook
Set ws1 = .Worksheets("Sheet1") '<- Set worksheet ws1
Set ws2 = .Worksheets("Sheet2") '<- Set worksheet ws2
End With
Set rng = ws1.Range("B1:D1,B2:B6,B8:E11") '<- Set the range you want to loop
For Each cell In rng
If str = "" Then '<- Create a string with all details
Else
str = str & "," & cell.Value
End If
Next cell
LastRow = ws2.Cells(ws2.Rows.Count, "A").End(xlUp).Row
i = 1
For Each chara In Split(str, ",") '<- Split with commas
ws2.Cells(LastRow + 1, i) = chara
i = i + 1
Next chara
End Sub

Resources