How to sort using a defined name in Excel? - excel

I have a Macro that sorts a database column by the category name with a custom order. I'm not sure if it is possible but I would like to use a defined name that contains all of the category names that is called Sorting_List. I would like for the defined name Sorting_List to replace the "FL,MF,HF,Furnace Eng,Launder,CM,CM Eng,ML,PP,Lab SOT,Lab AT,SSP,SII,NAPS,ES,FM,PW,C2H2,CA,Fluids,Fluids Eng,Elec,PMDA,Elec Eng,CH SW,CH SII,CH Std,CH High,CH Elec,CH Eng,CH FS,FS SW,FS SII,FS Elec,Eng,Train,Lab,Lab SW" so if I ever change anything in that defined name list it will automatically change in my macro. Below is my code. Any help is much appreciated.
ActiveWorkbook.Worksheets("Database").ListObjects("Database").Sort.SortFields. _
Add Key:=Range("Database[Category]"), SortOn:=xlSortOnValues, Order:= _
xlAscending, CustomOrder:= _
"FL,MF,HF,Furnace Eng,Launder,CM,CM Eng,ML,PP,Lab SOT,Lab AT,SSP,SII,NAPS,ES,FM,PW,C2H2,CA,Fluids,Fluids Eng,Elec,PMDA,Elec Eng,CH SW,CH SII,CH Std,CH High,CH Elec,CH Eng,CH FS,FS SW,FS SII,FS Elec,Eng,Train,Lab,Lab SW" _
, DataOption:=xlSortNormal

Dim sCustomOrder as String
Dim rng as Range
sCustomOrder = ""
For Each rng in ActiveWorkbook.Names("Sorting_List").RefersToRange
If rng.Text <> "" Then sCustomOrder = sCustomOrder & "," & rng.Text
Next rng
ActiveWorkbook.Worksheets("Database").ListObjects("Database").Sort.SortFields.Add _
Key:=Range("Database[Category]"), _
SortOn:=xlSortOnValues, _
Order:= xlAscending, _
CustomOrder:= sCustomOrder, _
DataOption:=xlSortNormal

Related

VBA Select CASE not working in some column

I'm a beginner in VBA coding. I want to delete column for cells that contains the following in the range("A5:CC5")
The code below doesn't work in certain column for some reason.
For example column that contain "Mango" and "Grapes" is not deleted, others are working fine.
If I run this code again, only then it will delete the "Mango" and "Grapes" column.
Appreciate your advice on this coding below.
Sheets("ILP").Select
Set a = Range("A5:CC5")
For Each cell In a
Select Case cell.value
Case "Apple", _
"Orange", _
"Banana", _
"Mango", _
"Papaya", _
"Grapes", _
"Pineapple"
cell.EntireColumn.Delete
End Select
Next
End Sub
You should interact with the range of cells, from last to first, like this:
And to not worry about different spellings (upper/lower case), use the UCASE comparison. In this way, both 'banana' and 'Banana' will be taken into account.
(the line with Debug.Print can be deleted. Put it only for inspection)
Option Explicit
Sub fnEliminateFruits()
Dim rngItems As Excel.Range
Dim intCell As Integer
Set rngItems = Range("A5:CC5")
For intCell = rngItems.Cells.Count To 1 Step -1
Debug.Print "cell address: " & rngItems(intCell).Address & " range address: " & rngItems.Address
Select Case UCase(rngItems(intCell).Value)
Case "APPLE", _
"ORANGE", _
"BANANA", _
"MANGO", _
"PAPAYA", _
"GRAPES", _
"PINEAPPLE"
rngItems(intCell).EntireColumn.Delete
End Select
Next
End Sub

Syntax Error trying to write a formula into a cell with VBA

Not actually familiar with visual basic but used some references to make this.
I would like to ask since I spent an hour figuring out how to solve this, may be I need some suggestions. I am encountering this error in Visual Basic to make macros for excel. At first it was working but after I added some lines the syntax turns red and when run the macro it just have a
Compile Error: Syntax Error
Range("D2").Select
ActiveCell.FormulaR1C1 = _
"=IF(ISNUMBER(SEARCH(""California"",RC[-2],1)),""California"",
IF(ISNUMBER(SEARCH(""Florida"",RC[-2],1)),""Florida"",
IF(ISNUMBER(SEARCH(""Texas"",RC[-2],1)),""Texas"", IF(ISNUMBER(SEARCH(""New
Mexico"",RC[-2],1)),""New Mexico"", IF(ISNUMBER(SEARCH(""Alaska"",RC[-2],1)),""Alaska"",
IF(ISNUMBER(SEARCH(""New Jersey"",RC[-2],1)),""New Jersey"",
""""))))))&IF(ISNUMBER(SEARCH(""Marikina"",RC[-2],1)),""Marikina"",
IF(ISNUMBER(SEARCH(""Maryland"",RC[-2],1)),""Maryland"",
IF(ISNUMBER(SEARCH(""Nebraska"",RC[-2],1)),""Nebraska"",
IF(ISNUMBER(SEARCH(""Pennsylvania"",RC[-2],1)),""Pennsylvania"",
IF(ISNUMBER(SEARCH(""Illinois"",RC[-2],1)),""Illinois"",
IF(ISNUMBER(SEARCH(""Colorado"",RC[-2],1)),""Colorado"",""""))))))&
IF(ISNUMBER(SEARCH(""Louisiana"",RC[-2],1)),""Louisiana"",
IF(ISNUMBER(SEARCH(""Idaho"",RC[-2],1)),""Idaho"",
IF(ISNUMBER(SEARCH(""Hawaii"",RC[-2],1)),""Hawaii"",
IF(ISNUMBER(SEARCH(""Vermont"",RC[-2],1)),""Vermont"",
IF(ISNUMBER(SEARCH(""West Virginia"",RC[-2],1)),""West Virginia"",
IF(ISNUMBER(SEARCH(""Connecticut"",RC[-2],1)),
""Connecticut"","""")))))"
Range("D2").Select
Selection.AutoFill Destination:=Range("D2:D38"), Type:=xlFillDefault
Range("D2:D38").Select
ActiveWindow.SmallScroll Down:=-39
End Sub
You cannot just add line breaks, you need to split the formula into multiple strings and concatenate them with &. Line breaks need to be concatenated with _ in the end of the line.
Range("D2").FormulaR1C1 = _
"=" & _
"IF(ISNUMBER(SEARCH(""California"",RC[-2],1)),""California"", " & _
"IF(ISNUMBER(SEARCH(""Florida"",RC[-2],1)),""Florida""," & _
"IF(ISNUMBER(SEARCH(""Texas"",RC[-2],1)),""Texas""," & _
"IF(ISNUMBER(SEARCH(""New Mexico"",RC[-2],1)),""New Mexico""," & _
"IF(ISNUMBER(SEARCH(""Alaska"",RC[-2],1)),""Alaska""," & _
"IF(ISNUMBER(SEARCH(""New Jersey"",RC[-2],1)),""New Jersey""," & _
"""""))))))&" & _
"IF(ISNUMBER(SEARCH(""Marikina"",RC[-2],1)),""Marikina""," & _
"IF(ISNUMBER(SEARCH(""Maryland"",RC[-2],1)),""Maryland""," & _
"IF(ISNUMBER(SEARCH(""Nebraska"",RC[-2],1)),""Nebraska""," & _
"IF(ISNUMBER(SEARCH(""Pennsylvania"",RC[-2],1)),""Pennsylvania""," & _
"IF(ISNUMBER(SEARCH(""Illinois"",RC[-2],1)),""Illinois""," & _
"IF(ISNUMBER(SEARCH(""Colorado"",RC[-2],1)),""Colorado""," & _
"""""))))))&" & _
"IF(ISNUMBER(SEARCH(""Louisiana"",RC[-2],1)),""Louisiana""," & _
"IF(ISNUMBER(SEARCH(""Idaho"",RC[-2],1)),""Idaho""," & _
"IF(ISNUMBER(SEARCH(""Hawaii"",RC[-2],1)),""Hawaii""," & _
"IF(ISNUMBER(SEARCH(""Vermont"",RC[-2],1)),""Vermont""," & _
"IF(ISNUMBER(SEARCH(""West Virginia"",RC[-2],1)),""West Virginia""," & _
"IF(ISNUMBER(SEARCH(""Connecticut"",RC[-2],1)),""Connecticut""," & _
"""""))))))"
Range("D2").AutoFill Destination:=Range("D2:D38"), Type:=xlFillDefault
You might benefit from reading
How to avoid using Select in Excel VBA.
To make the process less repeating create a function that can generate the formula by using a list of the states eg:
Option Explicit
Public Sub Example()
Dim ListOfStates() As Variant
ListOfStates = Array("California", "Florida", "Texas", "New Mexico", "Alaska", "New Jersey", "Marikina", "Maryland", "Nebraska", "Pennsylvania", "Illinois", "Colorado", "Louisiana", "Idaho", "Hawaii", "Vermont", "West Virginia", "Connecticut")
Range("D2").FormulaR1C1 = "=" & Join(CreateFormulaBlocks(ListOfStates), "&") 'join all blocks by &
End Sub
' returns an array of all blocks (each 6 states)
'
Public Function CreateFormulaBlocks(ByVal ListOfStates As Variant, Optional ByVal MaxPerBlock As Long = 6) As Variant
' how many blocks do we need
Dim MaxBlocks As Long
MaxBlocks = (UBound(ListOfStates) + 1) \ 6 ' note this is no normal division / but an integer division \
' create array for blocks
Dim ReturnBlocks() As Variant
ReDim ReturnBlocks(MaxBlocks - 1) As Variant
' create blocks
Dim iBlock As Long
For iBlock = 0 To MaxBlocks - 1
Dim BlockStates() As Variant
ReDim BlockStates(MaxPerBlock - 1) As Variant
Dim iState As Long
For iState = 0 To MaxPerBlock - 1
BlockStates(iState) = ListOfStates(iBlock * 6 + iState)
Next iState
' create one block of 6 states
ReturnBlocks(iBlock) = CreateFromulaBlock(BlockStates)
Next iBlock
' return all blocks as array
CreateFormulaBlocks = ReturnBlocks
End Function
' returns one block of 6 states
' eg IF(ISNUMBER(SEARCH("California",RC[-2],1)),"California", IF(ISNUMBER(SEARCH("Florida",RC[-2],1)),"Florida", IF(ISNUMBER(SEARCH("Texas",RC[-2],1)),"Texas", IF(ISNUMBER(SEARCH("New Mexico",RC[-2],1)),"New Mexico", IF(ISNUMBER(SEARCH("Alaska",RC[-2],1)),"Alaska", IF(ISNUMBER(SEARCH("New Jersey",RC[-2],1)),"New Jersey", ""))))))
'
Public Function CreateFromulaBlock(ByVal States As Variant) As String
Dim FormulaString As String
Dim State As Variant
For Each State In States
FormulaString = FormulaString & "IF(ISNUMBER(SEARCH(""" & State & """,RC[-2],1)),""" & State & """, "
Next State
CreateFromulaBlock = FormulaString & """""" & String(UBound(States) + 1, ")")
End Function

Data validation allows numbers and some strings?

I want to do a data validation in BFF!range("A3:A40"). I want to only allow numbers from 0 to 24 and in the same time the list of strings "A" , "B", "C", "D". The list is present in Liste!range("C2:C100").
here is the code for the first part (list of strings), but i don't know how to add the second part (numbers between 0 and 24).
Sub Data_Validation_Nom()
'change Sheet1 to suit
Set wsListe = ThisWorkbook.Worksheets("Liste")
Set wsBFF = ThisWorkbook.Worksheets("BFF")
Set range1 = wsListe.Range("C2:C100")
Set rng = wsBFF.Range("A3:A40")
With rng.Validation
.Delete 'delete previous validation
.Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
Formula1:="='" & wsListe.Name & "'!" & range1.Address
End With
End Sub
Can someone helps me please

Macro for Text to columns

Sub Macro9()
'
' Macro9 Macro
'
'
Selection.TextToColumns Destination := Range("A3"), DataType := xlFixedWidth, _
FieldInfo := Array(Array(0,1),Array(60,1),Array(63,1),Array(68,1),Array(71,1), _
Array(85,1),Array(88,1),Array(93,1),Array(99,1),Array(107,1),Array(111,1),Array _
(120,1),Array(123,1),Array(127,1),Array(130,1),Array(134,1),Array(143,1),Array( _
147,1),Array(157,1),Array(162,1),Array(165,1),Array(170,1),Array(202,1),Array( _
233,1),Array(236,1),Array(238,1),Array(248,1),Array(251,1),Array(260,1),Array( _
265,1),Array(277,1),Array(283,1),Array(287,1),Array(291,1),Array(295,1),Array( _
299,1),Array(302,1),Array(306,1),Array(310,1),Array(322,1),Array(326,1),Array( _
332,1),Array(335,1),Array(338,1),Array(344,1),Array(348,1),Array(356,1),Array( _
360,1),Array(367,1),Array(373,1),Array(375,1),Array(384,1),Array(387,1),Array( _
394,1),Array(398,1),Array(403,1),Array(409,1),Array(413,1),Array(419,1),Array( _
424,1),Array(429,1),Array(432,1),Array(438,1),Array(444,1),Array(449,1),Array( _
454,1),Array(458,1),Array(463,1),Array(468,1),Array(474,1),Array(478,1),Array( _
481,1),Array(484,1),Array(489,1),Array(493,1),Array(524,1),Array(554,1),Array( _
557,1),Array(563,1),Array(565,1),Array(577,1),Array(594,1),Array(613,1),Array( _
616,1),Array(620,1),Array(626,1),Array(629,1),Array(634,1),Array(646,1),Array( _
654,1),Array(659,1),Array(667,1),Array(669,1),Array(675,1),Array(683,1),Array( _
689,1),Array(696,1),Array(699,1),Array(706,1),Array(714,1),Array(717,1),Array( _
721,1),Array(728,1),Array(730,1),Array(743,1),Array(751,1),Array(754,1),Array( _
758,1),Array(767,1),Array(774,1),Array(779,1),Array(787,1),Array(790,1),Array( _
798,1),Array(805,1),Array(808,1),Array(817,1),Array(822,1),Array(826,1),Array( _
835,1),Array(845,1),Array(853,1),Array(857,1),Array(864,1),Array(869,1),Array( _
877,1),Array(881,1),Array(891,1),Array(895,1),Array(903,1),Array(912,1),Array( _
916,1),Array(920,1),Array(927,1),Array(933,1),Array(937,1),Array(941,1),Array( _
End Sub
I have 800 words in cell A3 in sheet input1, i recorded above macro by using function "Text to columns" in Excel 2007 which is giving error "Too many line continuations".
Can someone tell me the exact code please, indeed I want to add all the 800 words in different individual cells as one word in each cell in the same row.
I do not believe it is possible to tell the Macro Recorder to create longer lines so I do not think TextToColumns can be made to record this code for you.
You are using the fixed width option so words are starting at position 0, 60, 63, 68, 71 and so on. The start positions for about 120 words have been have been recorded so, if you wanted to build an array like this, you will have a lot of typing.
You say "words". To me that implies variable length strings separated by spaces. If that is correct, try the code below. It uses function Split to split cell A3 into words by space. These are then spread out along row 4 with any gaps created by double or triple spaces ignored.
Option Explicit
Sub SplitCell()
Dim CellCrnt As Long
Dim InxW As Long
Dim Word() As String
With Worksheets("input1")
Word = Split(.Range("A3"), " ")
CellCrnt = 1
For InxW = LBound(Word) To UBound(Word)
' Any double spaces will cause empty entries in Word.
' Ignore these empty entries
If Word(InxW) <> "" Then
.Cells(4, CellCrnt).Value = Word(InxW)
CellCrnt = CellCrnt + 1
End If
Next
End With
End Sub

excel formulaarray

hi why do i get the runtime error 13: type mismatch error
while running the following code
Application.Goto Reference:="R1C1:R232C221"
Selection.FormulaArray = "=ROUND(a(),0)"
Selection.Replace What:="a()", Replacement:="IF(IF(Sheet4!A1:HM232+Sheet5!A1:HM232=2,0," & _
"Sheet4!A1:HM232+Sheet5!A1:HM232)+IF(Sheet4!A1:HM232+Sheet5!A1:HM232=2,0," & _
"Sheet4!A1:HM232+Sheet5!A1:HM232)=2,0,IF(Sheet4!A1:HM232+Sheet5!A1:HM232=2,0," & _
"Sheet4!A1:HM232+Sheet5!A1:HM232)+IF(Sheet4!A1:HM232+Sheet5!A1:HM232=2,0,Sheet4!A1:HM232+Sheet5!A1:HM232))", LookAt _
:=xlPart, SearchOrder:=xlByRows, MatchCase:=True, SearchFormat:=False, _
ReplaceFormat:=False
Range("I9").Select
1) i know that formulaarray should be in R1C1 style... but A1 style is not required, it also works without any problems in A1 style
http://msdn.microsoft.com/en-us/library/bb208529.aspx
2) i found this way of writing from
http://www.dailydoseofexcel.com/archives/2005/01/10/entering-long-array-formulas-in-vba/
Let's analyze your Replacement:
Replacement:="IF(IF(Sheet4!A1:HM232+Sheet5!A1:HM232=2,0," & _
"Sheet4!A1:HM232+Sheet5!A1:HM232)+IF(Sheet4!A1:HM232+Sheet5!A1:HM232=2,0," & _
"Sheet4!A1:HM232+Sheet5!A1:HM232)=2,0,IF(Sheet4!A1:HM232+Sheet5!A1:HM232=2,0," & _
"Sheet4!A1:HM232+Sheet5!A1:HM232)+IF(Sheet4!A1:HM232+Sheet5!A1:HM232=2,0,Sheet4!A1:HM232+Sheet5!A1:HM232))"
(1) change Sheet4!A1:HM232+Sheet5!A1:HM232 to X:
Replacement:="IF(IF(X=2,0," & _
"X)+IF(X=2,0," & _
"X)=2,0,IF(X=2,0," & _
"X)+IF(X=2,0,X))"
(2) glue the broken pieces back together:
Replacement:="IF(IF(X=2,0,X)+IF(X=2,0,X)=2,0,IF(X=2,0,X)+IF(X=2,0,X))"
(3) change IF(X=2,0,X) to Y:
Replacement:="IF(Y+Y=2,0,Y+Y)"
(4) some evaluation:
If X is 2, Y is 0, and the result is 0.
If X is 1, Y is 1, and the result is
0.
If X is anything else, Y is X, and the
result is 2*X.
(5) so the formula is equivalent to:
Replacement:="IF(OR(X=2,X=1),0,2*X)"
(6) so the next step would be to replace X (step 1 in reverse) ...
I'll just leave you with a question or two: How did it become so messy? Have you heard of "DRY" (Don't Repeat Yourself)?
I believe the "replacement" argument is too long. You need to keep that string under 255 characters. Put more of the formula into the Selection.FormulaArray line so that the replacement is less than 255 characters.

Resources