I have a copy script that works perfectly, with the exception to losing my formatting when it runs. I lose the horizontally and vertically centered text, cell background color (for conditions), all of my borders, and any text effects (bold/underline/italic). For adding uniform borders, I use
Range("CSResults").Borders.LineStyle = xlContinuous
While this works, not all of the borders are the same thickness and the cell background color varies depending on the contents of the cell.
I need to modify my current script to keep the formatting.
Copy Script
Dim SectionCS As Long, NextRow As Long, TotalRows As Long
Sheets("CS Results").Activate
Range("CSResults").Select
Selection.AutoFilter
Range("CSResults").Clear
For SectionCS = 1 To 13 '36
NextRow = Sheets("CS Results").Range("A" & Rows.Count).End(xlUp).Row + 1 'Next empty row
Sheets("Function Test Procedure - CS").Activate
TotalRows = Range("CSSec" & SectionCS).Rows.Count
Sheets("CS Results").Range("A" & NextRow).Resize(TotalRows, 14).Value = _
Range("CSSec" & SectionCS).Columns("A:N").Value
Next SectionCS
You're not technically copy/pasting, you're setting values equal. To paste the data and the format, use pasteSpecial:
Range("CSSec" & SectionCS).Columns("A:N").Copy
With Sheets("CS Results").Range("A" & NextRow).Resize(TotalRows, 14)
.PasteSpecial xlPasteFormats
.PasteSpecial xlPasteValues
End With
Application.CutCopyMode = False
That should work, just double check the copy range is accurate.
Related
I'm trying to convert number in decimal format in my selection to percentages but am getting a type mismatch error.
Current code is below, where lRow is predefined integer.
Range("F6:F" & lRow).Select
Selection.Value = Selection.Value / 100
Selection.NumberFormat = "0.0%_);(0.0%)"
The issue is here:
Selection.Value = Selection.Value / 100
I am assuming that Selection typically contains more than one cell, in which case .Value does not return a number that can be divided but rather an array containing the value of each individual cell. Use a For Each loop to go through the set of cells in the selection and apply the calculation:
For Each cel In Selection
cel.Value = cel.Value /100
Next
Also note that you don't need to select cells as if you were using Excel mouse input to do things in VBA. It is better to do something like
Dim rng As Range
Set rng = Range("F6:F" & lRow)
and then use rng where you currently use Selection, for example rng.NumberFormat = ...
One approach is to use PasteSpecial with xlPasteSpecialOperationDivide :
With Range("F6:F" & lRow)
With Range("F" & lRow + 1)
.Value = 100 'put 100 to a helper cell
.Copy 'put divider into the clipboard
End With
.PasteSpecial xlPasteValues, xlPasteSpecialOperationDivide 'divide all the values by divider in the clipboard
.NumberFormat = "0.0%_);(0.0%)"
End With
Range("F" & lRow + 1).ClearContents 'clear the helper cell
I have a loop that needs to stop when activecell value is "BBSE", but it passes the cell and continues the loop. someone can help me with that?
I cut rows from table in one workbbok and paste it to another. before the list in column F I have many blank cells, and because of that I am usind xldown.
Here is the relevant code:
'Illuminators Worksheet
OP_wb.Activate
Range("F2").End(xlDown).Select
Do Until ActiveCell.Value = "BBSE"
OP_wb.Activate
Worksheets("Optic Main").Activate
Range("F2").End(xlDown).Select
Selection.EntireRow.Cut
Demand_WB.Activate
Worksheets("Illuminators").Activate
Range("A" & Rows.Count).End(xlUp).Offset(1).Select
ActiveSheet.Paste
Loop
Here is where I want to stop the loop in the red circle:
this is why I am using END.xlDown
If I understand what you are trying to achieve correctly, I believe the following will achieve it:
Dim startRow As Long
Dim endRow As Long
With OP_wb.Worksheets("Optic Main")
startRow = .Range("F2").End(xlDown).Row
endRow = .Columns("F").Find(What:="BBSE", LookIn:=xlValues, LookAt:=xlWhole).Row
.Rows(startRow & ":" & endRow).Cut
End With
With Demand_WB.Worksheets("Illuminators")
.Range("A" & .Rows.Count).End(xlUp).Offset(1).Insert Shift:=xlDown
End With
May be try like this...
'Mentioning Starting Row Here
x = 2
Do
'x refers to Row and F refer to column name
With Cells(x, "F")
'Exiting Do Loop once it finds the matching value using If statement
If .Value = "BBSE" Then Exit Do
OP_wb.Activate
Worksheets("Optic Main").Activate
.EntireRow.Cut
Demand_WB.Activate
Worksheets("Illuminators").Activate
Range("A" & Rows.Count).End(xlUp).Offset(1).Select
ActiveSheet.Paste
End With
'Incrementing row number here to move on to next row
x = x + 1
Loop
I am a newcomer to vba/excel macros and need a more efficient way to run the below code. I am using a for each loop to return a value from a row based on a column's value (same row). The code works, but takes far too much processing power and time to get through the loops (often freezing the computer or program). I would appreciate any suggestions...
'The following is searching each cell in a range to determine if a cell is not empty. If the cell is not empty, the macro will copy the value of the cell and paste it in to another worksheet (same row)
Set rng = Worksheets("Demographic").Range("AU2:AU" & lastRow)
i = "2"
For Each cell In rng
If Not IsEmpty(cell.Value) Then
Sheets("Demographic").Range("AU" & i).Copy
Sheets("Employee import").Range("F" & i).PasteSpecial xlPasteValues
End If
i = i + 1
Next
'The following is searching each cell in a range to determine if a cell contains a "T". If the cell contains a "T", the macro will copy the value of a different column (same row) and paste it in to another worksheet (same row)
Set rng = Worksheets("Demographic").Range("AM2:AM" & lastRow)
i = "2"
For Each cell In rng
If cell.Value = "T" Then
Sheets("Demographic").Range("AO" & i).Copy
Sheets("Employee import").Range("G" & i).PasteSpecial xlPasteValues
End If
i = i + 1
Next
A formula array should be your best hope. This supposes that the cells that do not match will lead to empty values in the destination range:
chk = "Demographic!AU2:AU" & lastRow
src = "Demographic!AU2:AU" & lastRow
With Sheets("Employee import").Range("F2:F" & lastRow)
.FormulaArray = "=IF(" & chk & "<> """"," & src & ", """")"
.Value = .Value '<-- if you want to remove the formulas and keep only the copied values
End With
chk = "Demographic!AM2:AM" & lastRow
src = "Demographic!AO2:AO" & lastRow
With Sheets("Employee import").Range("G2:G" & lastRow)
.FormulaArray = "=IF(" & chk & "= ""T""," & src & ", """")"
.Value = .Value '<-- if you want to remove the formulas and keep only the copied values
End With
Not sure that it will be faster with your dataset though, you can only verify by trying it.
If you just want a straight data transfer (ie no formulas or formats), and your data set is large, then you could consider writing the data in one batch by way of an array.
Your own code shouldn't be horrendously slow though, so it suggests you have some calculations running or maybe you're handling Worksheet_Change events. If this is possible, then you might want to disable those during the data transfer:
With Application
.EnableEvents = False
.ScreenUpdating = False
.Calculation = xlCalculationManual
End With
Just remember to reset them at the end of your routine:
With Application
.EnableEvents = True
.ScreenUpdating = True
.Calculation = xlCalculationAutomatic
End With
If you went the array route, skeleton code would be like so:
Dim inData As Variant
Dim outData() As Variant
Dim r As Long
'Read the demographic data
With Worksheets("Demographic")
inData = .Range(.Cells(2, "AU"), .Cells(.Rows.Count, "AU").End(xlUp)).Value2
End With
'Use this if your column F is to be entirely overwritten
ReDim outData(1 To UBound(inData, 1), 1 To UBound(inData, 2))
'Use this if you have exisiting data in column F
'With Worksheets("Employee import")
' outData = .Cells(2, "F").Resize(UBound(inData, 1)).Value2
'End With
'Pass the values across
For r = 1 To UBound(inData, 1)
If Not IsEmpty(inData(r, 1)) Then
outData(r, 1) = inData(r, 1)
End If
Next
'Write the new values
Worksheets("Employee import").Cells(2, "F").Resize(UBound(outData, 1)).Value = outData
as for your first copy/paste values, it actually doesn't need any check, since blank values would be pasted as blank ones...
so you could go:
With Worksheets("Demographic")
With .Range("AU2", .Cells(.Rows.count, "AU").End(xlUp))
Worksheets("Employee import").Range("F2").Resize(.Rows.count).Value = .Value
End With
End With
as for your 2nd copy/paste values, you could paste all values and then filter not wanted ones and clear them in target sheet
like follows:
With Worksheets("Demographic")
With .Range("AM2", .Cells(.Rows.count, "AM").End(xlUp))
Worksheets("Employee import").Range("G2").Resize(.Rows.count).Value = .Offset(, 2).Value
End With
End With
With Worksheets("Employee import")
With .Range("G1", .Cells(.Rows.count, "G").End(xlUp))
.AutoFilter field:=1, Criteria1:="<>T"
.Resize(.Rows.count).Offset(1).SpecialCells(xlCellTypeVisible).ClearContents
End With
.AutoFilterMode = False
End With
that said, if your workbook has many formulas and/or event handlers then you would also greatly benefit from disabling them (Application.EnableEvents = False, Application.Calculation = xlCalculationManual) before running your code and enabling them back (Application.EnableEvents = True, Application.Calculation = xlCalculationAutomatic) after you code completes
First, my code (below) works, but I am trying to see if it can be simplified. The macro in which this code is located will have a lot of specific search items and I want to make it as efficient as possible.
It is searching for records with a specific category (in this case "Chemistry") then copying those records into another workbook. I feel like using Activate in the search, and using Select when moving to the next cell are taking too much time and resources, but I don't know how to code it to where it doesn't have to do that.
Here are the specifics:
Search column T for "Chemistry"
Once it finds "Chemistry", set that row as the "top" record. e.g. A65
Move to the next row down, and if that cell contains "Chemistry", move to the next row (the cells that contain "Chemistry" will all be together"
Keep going until it doesn't find "Chemistry", then move up one row
Set that row for the "bottom" record. e.g. AX128
Combine the top and bottom rows to get the range to select. e.g. A65:AX128
Copy that range and paste it into another workbook
Here is the code:
'find "Chemistry"
Range("T1").Select
Cells.Find(What:="Chemistry", After:=ActiveCell, LookIn:=xlFormulas, LookAt _
:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
False, SearchFormat:=False).Activate
'set top row for selection
toprow = ActiveCell.Row
topcellselect = "A" & toprow
'find all rows for Chemistry
Do While ActiveCell = "Chemistry"
ActiveCell.Offset(1, 0).Select
Loop
ActiveCell.Offset(-1, 0).Select
'set bottom row for selection
bottomrow = ActiveCell.Row
bottomcellselect = "AX" & bottomrow
'define selection range from top and bottom rows
selectionrange = topcellselect & ":" & bottomcellselect
'copy selection range
Range(selectionrange).Copy
'paste into appropriate sheet
wb1.Activate
Sheets("Chemistry").Select
Range("A2").PasteSpecial
Thanks in advance for any help!
You never need to select or activate unless that's really what you want to do (at the end of the code, if you want the user to see a certain range selected). To remove them, just take out the activations and selections, and put the things on the same line. Example:
wb1.Activate
Sheets("Chemistry").Select
Range("A2").PasteSpecial
Becomes
wb1.Sheets("Chemistry").Range("A2").PasteSpecial
For the whole code; I just loop thorugh the column and see where it starts and stops being "chemistry". I put it in a Sub so you only have to call the sub, saying which word you're looking for and where to Paste it.
Sub tester
Call Paster("Chemistry", "A2")
End sub
Sub Paster(searchWord as string, rngPaste as string)
Dim i as integer
Dim startRange as integer , endRange as integer
Dim rng as Range
With wb1.Sheets("Chemistry")
For i = 1 to .Cells(Rows.Count,20).End(XlUp).Row
If .Range("T" & i ) = searchWord then 'Here it notes the row where we first find the search word
startRange = i
Do until .Range("T" & i ) <> searchWord
i = i + 1 'Here it notes the first time it stops being that search word
Loop
endRange = i - 1 'Backtracking by 1 because it does it once too many times
Exit for
End if
Next
'Your range goes from startRange to endRange now
set rng = .Range("T" & startRange & ":T" & endRange)
rng.Copy
.Range(rngPaste).PasteSpecial 'Paste it to the address you gave as a String
End with
End sub
As you can see I put the long worksheet reference in a With to shorten it. If you have any questions or if it doesn't work, write it in comments (I haven't tested)
The most efficient way is to create a Temporary Custom Sort Order and apply it to your table.
Sub MoveSearchWordToTop(KeyWord As String)
Dim DestinationWorkSheet As Workbook
Dim SortKey As Range, rList As Range
Set SortKey = Range("T1")
Set rList = SortKey.CurrentRegion
Application.AddCustomList Array(KeyWord)
rList.Sort Key1:=SortKey, Order1:=xlAscending, Header:=xlGuess, _
OrderCustom:=Application.CustomListCount + 1, MatchCase:=False, _
Orientation:=xlTopToBottom, DataOption1:=xlSortNormal
Application.DeleteCustomList Application.CustomListCount
Set DestinationWorkSheet = Workbooks("Some Other Workbook.xlsx").Worksheets("Sheet1")
rList.Copy DestinationWorkSheet.Range("A1")
End Sub
My quote generator creates an Excel document and I want to run a macro on it to just keep it's calculations. For some reason it says 'Number stored as text' when there are numbers. How can I change them to the number format using the macro? I have found out if I click once in the formula bar, the problem is solved too.
The code below is what I have now, but it won't solve the error.
Range("A1:A" & LastRow).Select
Selection.NumberFormat = "0"
Column A contains an amount (1, 2, 3, etc). I have another column with the same problem, but this contains a currency in € and has 2 decimal places.
Range("I1:I" & LastRow).Select
Selection.NumberFormat = "0.00"
Thanks for your help! :)
Extra shoutout to Siddharth who helped me complete this complete issue.
Tom,
There are 3 ways to solve this
1) Go Back to your quote generator and see how it is saving the data to Excel Sheet and amend the code there
2) Manually: Highlight the Range and click on the exclamation mark next to the Green Triangle and click on "Convert to Number" See snapshot
3) Use this code.
Sub Sample()
Dim LastRow As Long, i As Long
LastRow = Sheets("Sheet1").Range("A" & Rows.Count).End(xlUp).Row
Sheets("Sheet1").Range("A1:A" & LastRow).NumberFormat = "0"
For i = 1 To LastRow
If Val(Sheets("Sheet1").Range("A" & i).Value) <> 0 Then _
Sheets("Sheet1").Range("A" & i).Formula = _
Val(Sheets("Sheet1").Range("A" & i).Value)
Next i
Dim temp As Double
LastRow = Sheets("Sheet1").Range("I" & Rows.Count).End(xlUp).Row
Sheets("Sheet1").Range("I1:I" & LastRow).NumberFormat = "\$#,##0.00"
For i = 1 To LastRow
If Val(Sheets("Sheet1").Range("I" & i).Value) <> 0 Then
temp = Sheets("Sheet1").Range("I" & i).Value
Sheets("Sheet1").Range("I" & i).ClearContents
Sheets("Sheet1").Range("I" & i).Value = temp
End If
Next i
End Sub
FOLLOW UP
Before and After snapshot attached
MORE FOLLOW UP (IMPORTANT)
If you have different regional settings then you will have to take care of them appropriately.
For Example Dutch Belgium you have to use "," for a decimal. Please see snapshot.
Try this different ways:-
Way 1
Selection.NumberFormat = "General"
Way 2
vStr = "1000.5"
intNum = CInt(vStr)
Way 3
Convert Text to Numbers With VBA
If you frequently convert text to numbers, you can use a macro.
Add a button to an existing toolbar, and attach the macro to that button. Then, select the cells, and click the toolbar button.
Sub ConvertToNumbers()
Cells.SpecialCells(xlCellTypeLastCell) _
.Offset(1, 1).Copy
Selection.PasteSpecial Paste:=xlPasteValues, _
Operation:=xlPasteSpecialOperationAdd
With Selection
.VerticalAlignment = xlTop
.WrapText = False
End With
Selection.EntireColumn.AutoFit
End Sub