select entire value of a cell using VBA - vba

I have a column full of data with multiple lines inside a single cell like below:
I am looping through all the cells in the column and I have to select values inside every cell and search it in another sheet.I know i can split the cell value using the Split() function in vba.
But where I am struck is I am unable to select the whole value of the cell and parse it as input to the split () function. Here is my sample code where i am struck:
For Each C in Range ("A1:A" & ltrow)
If C.Value <> "" Then
SrcStrng = C.Value
TextArray () = Split(SrcStrng)
.....
........
.....
The problem I face here is in SrcStrng only the first value inside the cell for example in the first cell only t#234 is getting stored, so in split string only that is passed and it is not split properly, so I am unable to search t*567. It happens for every cell.
And also in the third cell, i want to parse only the value t#345 inside the loop for searching, neglecting L1:, I am struck with that too.
Could someone help me with this please.

Here is an example to show how this can be done. Use chr(10) as delimiter
Sub t()
Dim str As String
str = Range("A1").Value
Dim parts As Variant
parts = Split(str, Chr(10))
For i = LBound(parts) To UBound(parts)
MsgBox (parts(i))
Next i
End Sub

Related

VBA to format PNEZD string in Excel

I have a large list of points with PNEZD (point, northing, easting, elevation, description) fallowed by a few attributes for each point. how can I combine these extra attribute columns to my D column separated by a space? And can i do that with a push of a button?
example of a few points would be
10,1000,5000,50,tree,birch,12IN
11,1100,5500,55,tree,spruce,10IN
12,1130,5560,54,powerpole,tele,wood,12IN,guyed
I want to combine the last few so it will read:
10,1000,5000,50,tree birch 12IN
11,1100,5500,55,tree spruce 10IN
12,1130,5560,54,powerpole tele wood 12IN guyed
please help!
You can create a user-defined function in VBA that you can then use on your worksheet as any normal formula.
From Excel, press Alt+F11 to get to the VBA editor. Once there, press Ctrl+R to show or activate the Project Explorer. Right-click on the Modules node, and select Insert -> Module. Put the code below into the module:
Option Explicit
Public Function GetPnezdLabel(pnezd As Variant) As Variant
On Error GoTo errHandler
Dim result As Variant
Dim parts As Variant
Dim lastPartIndex As Long
Dim intermediatePartIndex As Long
Dim index As Long
result = ""
parts = Split(CStr(pnezd), ",", Compare:=VbCompareMethod.vbBinaryCompare)
lastPartIndex = UBound(parts)
intermediatePartIndex = Application.WorksheetFunction.Min(3, lastPartIndex)
For index = 0 To intermediatePartIndex
result = result & parts(index) & IIf(index < lastPartIndex, ",", "")
Next
For index = 4 To lastPartIndex
result = result & parts(index) & IIf(index < lastPartIndex, " ", "")
Next
Done:
GetPnezdLabel = result
Exit Function
errHandler:
result = XlCVError.xlErrValue
Resume Done
End Function
Press Alt+F11 to return to Excel. Now, assuming you have a PNEZD value in cell A1, you can create a formula in e.g. B1 as follows:
=GetPnezdLabel(A1)
and you'll see the result appear.
The principle behind the GetPnezdLabel function is to split the parameter's value at commas and to build the result from the parts.
For information, the same result can be achieved through following formula.
Assuming your data is in cell A2 then in cell D2 insert following formula and copy down.
=TRIM(LEFT(SUBSTITUTE(A2,",",REPT(" ",199),4),199))
&","&
SUBSTITUTE(TRIM(RIGHT(SUBSTITUTE(A2,",",REPT(" ",199),4),199)),","," ")
As you've indicated VBA specifically, you may not want a formula solution.

Copy part of text from the same cell

I have a problem when I downloaded a file containing different kind of information that should be stored in different cells but all is written in the same cell.
For example A:9 contains:
2016.03.16,"8982266507","QLGJG","AHGLG","OKK","IK","ODEADKIK","DK57200028982561607","485979,12","65164,94","485979,12","65164,94","485979,12","65164,94","","","","","","",
I would like to have a macro that copies specific parts of this string for example the last part "65164,94" and paste in to cell A:10.
Thank you in advance
As well as Seb's answer, you can use the split function. So:
Sub splitting_string()
Dim arr1 As Variant, var1 As String
var1 = Range("A9")
arr1 = Split(var1, ",")
For i = 0 To UBound(arr1)
Cells(10 + i, 1) = arr1(i)
Next i
End Sub
This will separate the long string in A9 into smaller ones by splitting them every time there's a comma, placing them in the cells below.

Convert VBA Macro to Function

I have been trying to create a function to retrieve column titles found in row four in an excel sheet. This is what I have so far, can anybody help me please?
Sub Test_Click()
Dim text As String
Dim titles(200) As String
Dim nTitles As Integer
For i = 1 To 199
If Trim(Sheets("Sheet1").Cells(4, i).Value) = "" Then
nTitles = i - 1
Exit For
End If
titles(i - 1) = Sheets("Sheet1").Cells(4, i).Value
Next
For i = 0 To nTitles
Sheets("Sheet1").Cells(20 + i, 1).Value = titles(i)
Next
End Sub
You need to make an array function for this. So your function will take in inputs through a range
Function ReturnArray(Input as Range) as Variant
' Do stuff with the Input range
Dim Output(m,n) as Variant
'Loop through m,n to fill in the output values as you would in a range
ReturnArray = Output
End Function
And when you put in the function in excel, type it in the cell after highlighting where you want the output and press Ctrl-Shift-Return
Just as you write a Sub you can write a Function, just substitute the words at the beginning and at the end of your code.
Now, about how to return the values, obviously it will be an array, so you'll need to declare the array, set its size, fill its cells and return it. This can be done like this:
Function yourFunction() as String()
' You already have an array named "titles" which stores the values you want
' to return. Fill it exactly as you do in your original code.
yourFunction = titles ' This is the way to return the array.
End Function
If you want to use this function in a worksheet (as a formula), remember that this is an array-function, so you'll need to press Ctrl+Shitf+Enter after you enter the function in the cell instead of just [Enter].

Hlookup and Match equivalent in VBA

sample.xls image
I have a code below, but it's not working properly. Something is missing in this code. Could you please help me with it?
Thanks in advance.
I added a sample.xls to show my request.
sample.xls
i dont have an error handler, my function with hlookup and match returns a value. but it returns with the same result (value) for each cell in range(N6:CQ7899). normally if i use formula in cell N6 =IFERROR(HLOOKUP(N$5,min!$C$2:$CF$7899,MATCH($E6,min!$B$2:$B$7899,0),FALSE);0) and go to last row and last col, each cell will have unique criteria with both hlookup and match. my request is how to do it by macro as follows;
do for rows in ranges N6:N7899, O6:O7899, ... and CQ6:CQ7899
N6
=IFERROR(HLOOKUP(N$5,min!$C$2:$CF$7899,MATCH($E6,min!$B$2:$B$7899,0),FALSE);0),
N7
=IFERROR(HLOOKUP(N$5,min!$C$2:$CF$7899,MATCH($E7,min!$B$2:$B$7899,0),FALSE);0)`,.,.,.,.
up to last row.
and do for columns;
O6
=IFERROR(HLOOKUP(**O$5**,min!$C$2:$CF$7899,MATCH(***$E6***,min!$B$2:$B$7899,0),FALSE);0),
O7
=IFERROR(HLOOKUP(**O$5**,min!$C$2:$CF$7899,MATCH(***$E7***,min!$B$2:$B$7899,0),FALSE);0).,.,.,.
up to last cell (CQ7899) in column CQ.
if possible, please check sample.xls image or xls file.
Function matcd()
Dim adegm As Range
Dim adizm As Range
Dim adegh As Range
Dim adizh As Range
Dim rnghFormulaCell As Range
Dim varResult1 As Variant
Set adegh = Worksheets("ara").Range("N5")
Set adizh = Worksheets("min").Range("C2:CF7899")
Set adegm = Worksheets("ara").Range("E5:E")
Set adizm = Worksheets("min").Range("B2:B7899")
Set rnghFormulaCell = Worksheets("ara").Range("N6:CQ7899") '
Worksheets("ara").Range("N6:CQ" & Rows.Count).ClearContents
varResult1 = Application.WorksheetFunction.HLookup(adegh, adizh, Application.WorksheetFunction.Match(adegm, adizm, 0), 0)
'.....
'i don't know how to Add results of varResult1 to an array in rnghFormulaCell
'.....
If Not IsError(varResult1) Then rnghFormulaCell = varResult1
End Function

Array from Range in Excel VBA

Well I've been struggling with the little bit of code and can't seem to get around it ...
I'm trying to get an array from a range of cells, the array however is showing up to be 1 element wide.
Well here's the code:
Dim item As Variant
MsgBox Range("D19:H19").Count
item = Range("D19:H19").Value
MsgBox LBound(item) & " " & UBound(item)
as per my understanding item should contain a 2D array... however I'm getting the following result
1st MsgBox prints 5
2nd MsgBox prints 1 1
What's going wrong?
The problem is in LBound and UBound
jtolle was correct about the LBound and UBound.
LBound(item, 2)
UBound(item, 2)
However, item must not be dimmed as an array (you'll get an error).
I think this is what you want
Dim item As Variant
MsgBox Range("D19:H19").Count
item = Range("D19:H19").Value
MsgBox LBound(item, 2) & " " & UBound(item, 2)
For i = LBound(item, 2) To UBound(item, 2)
MsgBox item(1, i)
Next
Your item should contain a 2-D array as expected. If you stick a breakpoint in your code and look at the little "Locals" window in the VBA editor, you should see that. Your calls to LBound and UBound are getting the bounds in the first dimension. If you call Lbound(item,2) and UBound(item,2), you should get 1 and 5 as you expect.
EDIT:
That is, once you've made the assignment, item would look like something you could have declared as such:
Dim item(1 to 1, 1 to 5)
One of the banes of VBA programming is that arrays can have arbitrary lower bounds. So all of your code needs to be aware of that.
That's correct as is. Even if you select an array of cells, you still have the option to select one single cell out of the array (and step for example with tab through the items of this array)
.Value
only gets you the content of the currently single-selected cell.
if you want the enumeration of the array, you may call the .Cells()-method of the Range-object
Assuming that D19 until H19 contain "a" through "e" respectively, calling
Range("D19:H19").Cells(2)
returns you "b". Note that this is a one-based array and can be 2-dimensional. Cells() takes at most 2 parameters to specify the inner offset from the selection's origin.
hope that clarifies... regards
Try this:
Dim item As Variant
MsgBox Range("D19:H19").Count
item = Application.Transpose(Range("D19:H19").Value)
MsgBox LBound(item) & " " & UBound(item)
if you want a 1D array, to join it for an IN clause, for example, you should transpose your range.
I've found you have to transpose twice for a row, once for a column of data like this:
Dim rngRow As Range, rngColumn As Range
Set rngRow = Sheets(1).Range("A1", "Z1")
Set rngColumn = Sheets(1).Range("A1", "A20")
Dim arrRowValues, arrColValues
arrRowValues = WorksheetFunction.Transpose(WorksheetFunction.Transpose(rngRow))
arrColValues = WorksheetFunction.Transpose(rngColumn)
Dim numList As String, stringList As String
numList = Join(arrRowValues, ",")
stringList = "'" & Join(arrColValues, "','") & "'"
worth a play.