Most efficient way to remove all linebreaks in worksheet - excel

I have a macro which iterates over column C, anytime the cell is not empty it opens a file referenced in Column B, searches this newly opened file for a string that is written in column A and then replaces the content of that cell with what is written in column C. My problem though is that in the newly opened file, there are line breaks in some columns (sometimes trailing, sometimes where there should only be a space), so the macro doesn't find the right cell.
I was thinking to solve this I write another macro which goes through those files and replaces every line break with a space. It's basically just
For Each Cell In Worksheet.Range(Cells.Address)
Cell.Value = Replace(Cell.Value, Chr(10), " ")
Next
This seems to work, but I can't run it without excel crashing. Are there more efficient ways to do this? Or maybe all together a better approach to my problem? Thanks.

The VBA DoEvents function temporarily pauses a running macro, giving Excel a chance to process key presses, mouse clicks, and other operating system messages.
In long-running macros, Excel can appear to hang and become unresponsive, and the macro may be impossible to interrupt. If DoEvents is included in your code, users can be assured that the macro is still running, and can still interrupt execution if necessary.
For Each Cell In Worksheet.Range(Cells.Address)
Cell.Value = Replace(Cell.Value, Chr(10), " ")
DoEvents
Next
Source: automateexcel

This (I hope) is an implementation of BigBen's suggestion for the active sheet:
Sub test()
Dim r As Range
Set r = ActiveSheet.Cells.SpecialCells(xlCellTypeConstants)
r.Replace Chr(10), " "
End Sub
EDIT#1:
The code above relies on the proper worksheet being Active. A safer alternative would be to use something more explicit like:
Set r = Sheets("my data").Cells.SpecialCells(xlCellTypeConstants)
NOTE:
We are using the .Replace() Method rather than the Replace() function.

Related

Macro Paste in Excel

Currently I have macros set up in my excel that pastes a list when clicked.
However I am encountering an issue where I have to paste the copied list (from a pdf) into notepad before pasting into excel, so that it separates into cells instead of trying to excel cram the entire list into one cell when done directly.
I have tried creating a macro that would open a cell directly paste into it then cut out before pasting (Which works when done manually) as well as a number of different methods that were all dead ends.
My procedure is currently:
Open PDF, ctrl a, ctrl c
paste into notepad then ctrl a, cut
paste into excel
If I could get help removing the notepad part of the procedure, I would be incredibly happy!
If you paste the whole thing inside a cell like this:
Then you can use this script to do a text to rows operation.
Option Explicit
Sub TextToRows()
Dim RG As Range
Dim RGValue As String
Dim LinesArray
Dim LineCount As Long
Dim I As Long
Set RG = Selection
If RG.Cells.Count <> 1 Then Exit Sub
RGValue = RG.Value
LineCount = Len(RGValue) - Len(Replace(Replace(RGValue, Chr(13), ""), Chr(10), "")) + 1
If InStr(1, RGValue, Chr(10)) = 0 Then
LinesArray = Split(RGValue, Chr(13))
Else
LinesArray = Split(RGValue, Chr(10))
End If
RG.Offset(1, 0).Resize(LineCount, 1).Value = Application.Transpose(LinesArray)
End Sub
Viola!
Your aim is reduced notepad step however I suggest I would remove the pdf step since poppler or xpdf pdftotext -layout is usually good to add the needed white space to keep text tabular. That can be drag and drop pdf on a shortcut that calls open new spreadsheet with text. And here is the usual core issue with cut and paste plain text as a framework.
Most spreadsheets as far back as last century have several text import methods, most common is add commas for csv import, but space separated text is accepted too. (I still use MSeXcel 97 portable as its an old familiar) It often requires some intervention to check detection, so here in Modern Open Office I specified combine spaces. Thus, introduces just one minor error here, "Addresss" is moved left-wards.
No Problem it has a spelling mistake so it's just that one that needs managing twice. 1st spell check and then move it right.
Every case can be different but if you write a macro to cover those corrections you repeat then it pays to run for the next import to include all the steps.
The simplest is plan ahead by tidy the text (here used tabs to replace spaces), then drag and drop, the results are usually cleaner data in = cleaner the cells are aligned.
Thank you everyone for your advice, I finally found a solution. It was as simple as a paste special text.
ActiveSheet.PasteSpecial Format:="Text", Link:=False, DisplayAsIcon:= _
Hopefully this helps someone else! Found it whilst looking into ways the window operating system formats copy/paste. It can be manually done by right clicking > Paste Special > Text

Managing Excel Worksheet_Change Feature

I have created a spreadsheet which uses the Worksheet_Change feature and the code associated with that works very well. I can stop it firing unnecessarily when inside the module by using Application.EnableEvents = False.
However, while I've created a form to enter data directly into the next available row (again, that works fine in terms of entry) it doesn't cause the formulae in the sheet to calculate (even though auto calculation is on and re-enabled within the module). If I manually place my cursor in the row, hit F2 and simply press enter, everything then fires up.
I have tried to enter data directly into the cells, but of course the Worksheet_Change feature then kicks in again and the cursor isn't simply moving to the next adjacent cell ....
I've tried to check firs for any direct entry with the code below and if it looks like the user isn't entering directly into the cell, the Worksheet_Change is disabled:
Sub Worksheet_Change(ByVal Target As Range)
On Error GoTo eventhandler
Sheets(1).Range("a1").Select
LastCell2 = Sheets(1).Cells(Rows.Count, "A").End(xlUp).Row
Dim intersection As Range
Set intersection = Intersect(Target, Range("A3:F" & LastCell2))
If intersection.Row = LastCell + 1 Then
Exit Sub
End If
Application.EnableEvents = False
The code above is simply checking to see if data is being entered into the next empty cell and if that's the case I want it to just exit there but it isn't working.
So I actually have 2 problems :
the first is why this formula isn't triggering after entry via a vba form - I've used INDIRECT since there are other macros that delete rows by moving the remaining cells up and that was causing the count in the $A$3:$A$500 to reduce to $A$499 and then 498 etc - the addition is done depending on the system date and the transaction date so I get a current value and a future value using a standard sum statement:
=AD1-(SUMIF(INDIRECT("$A$3:$A$500"),"<="&TODAY(),INDIRECT("$E$3:$E$500")))+(SUMIF(INDIRECT("$A$3:$A$500"),"<="&TODAY(),INDIRECT("$F$3:$F$500")))
The second is why I can't enter data directly into the spreadsheet and trap the fact that I don't want it to do anything and simply allow the user to hit enter and move to the next adjacent cell to the one they just entered data into.
Is this a lost cause and am I trying to do too much here? I'm relatively new to coding and teaching myself so apologies if the standard and style isn't to everyone's taste.
Thanks in advance for any replies.

Simple vba program in Excel

Sub TEST()
If cells(i, "R").Value <> "UK" Then
cells(i, "R").Interior.ColorIndex = 3
End If
End Sub
If I run this program it throws application defined error \
I am new to Excel (beginner)
How to correct this error!!!
Thanks In advance
I think the issue is "R" that I know of the cells method takes 2 parameters one is rows the other is columns (in that order) but this is done by number not letter so if you change it to cell(1,18) then the code above works fine.
This link may also be useful to learn more, among other things it describes how you would normally select a range first as I believe your code above will assume the currently selected page, however you might want to run in on a button click from another page or as soon as the spreadsheet opens.
http://msdn.microsoft.com/en-us/library/office/ff196273.aspx
The problem is that the variable i has not been assigned a value. VBA assumes that it is zero. Since i is used to determine the row of the cell, Excel throws an exception because there is no row 0!
First you have to define i variable
for example: Dim i as variant

creating a loop in vba for an excel macro

I have recorded a macro in Excel that takes data from certain cells in one page of a spreadsheet and copies them to page in a different order. it does each cell individually, and is quite long.
However it only does it for one row of data in the first page.
How do I make this single macro into a loop that copies the same data but from each row into the new page?
I haven't included the macro code since it is very long but can do so if necessary.
Thanks
You could omit your code to only show the relevant part, or code a mockup macro to address only and only your problem.
Lets imagine your problem as a sub, which in this case is highly omitted:
Sub OmittedSub()
' Do stuff
End Sub
You can create new sub to call it many times, this new sub would be the one you would be calling instead:
Sub LoopOmittedSubs()
Dim i As Integer
' Loop to call your macro routine multiple times
For i = 1 To 100
OmittedSub
Next
End Sub
In case you would need to pass a value, for example your macro does not know which row to affect and you would need to tell it, you can pass the loop variable like this:
Sub OmittedSub(iRow As Integer)
' Do stuff for row number iRow
End Sub
Sub LoopOmittedSubs()
Dim i As Integer
' Loop to call your macro routine multiple times
For i = 1 To 100
OmittedSub i
Next
End Sub
This answer is the very basics of VBA. I dont know how to answer your question better without knowing what you already tried, how you tried, etc...
Raybarg provided you basic solution to that problem. I am not sure what do you mean by "certain cell", does it mean they have certain value or there are in regular order like A5, A10, A15?
In both cases you probably will use Raybarg's code and conditional statements.
You should include your code, it gives some hints on what you actually want to achieve and where is error.

live execution of formula

can we execute a formula without moving cursor from the cell? After giving data in to Input cell either we press enter or we move from that cell and then any formula related to that gets executed. Is there any way that while entering input itself we can see the result in output in excel?Please help me in finding this option.
I don't believe it's possible for code to execute while the "editor" of a cell has focus and control. For example, try doing something else in Excel while you are editing a formula. I believe that the cell has to finish saving its value or formula before code can execute.
You can have a formula "listen" for when a cell is updated, but this is a little bit complicated. It could then force you back into the original cell once it is updated. Here's how you can write some code to "listen" for when a value of a cell changes. In the following example:
I record the value of Cell I1 to strValue.
Then I run a loop that stays running as long as the value of cell I1 has not changed.
The DoEvents command releases control back to the processor, which is what allows you to work in Excel while this is running.
Once the value of cell I1 changes, the While statement will be false and the loop will exit.
After the loop exits, a message box pops up that tells you the value changed and then the original cell is selected again.
'
Sub testChange()
Dim strValue As String
strValue = Range("I1").Value
Do While strValue = Range("I1").Value
DoEvents
Loop
MsgBox "The value changed!"
Range("I1").Activate
End Sub
Perhaps if you simply wanted to return control back to the original cell every time the value changed, you could use the line above without the message box and return to the loop once your method executes. Keep in mind that you might have to figure out another way to exit your code if you do that.
Why do you want to have it execute from within the cell? What is the end purpose of your task?
Press F9 to do a re-calc without moving from the input cell. This works in Excel 2007. I'm not sure about earlier versions.

Resources