Given tab delimited data that I am importing from Excel, how do I insert it into the spreadsheet so that it ends up in multiple cells like it does when I paste it.
Edit: I have the text in a variable, so I don't want to go through the file system.
This is basically what I finally came up with, it was a little more complex and used arrays, but that is the gist of it.
i = 1
For Each Row In VBA.Split(text, vbCrLf)
j = 1
For Each Col In VBA.Split(Row, vbTab)
ActiveSheet.Cells(i, j).Value = Col
j = j + 1
Next Col
i = i + 1
Next Row
It should not be too hard. Please try: http://www.zerrtech.com/content/excel-vba-open-csv-file-and-import
If you want to do it from string variable, split text by end line:
Dim linesSplit As Variant
linesSplit = Split(yourTextVar, "\n")
For each linesSplit, split by comma:
Dim lineSplit As Variant
lineSplit = Split(linesSplit[i], ",")
Put result in worksheet. GL!
Related
I have been using this code as a starting point: https://danwagner.co/how-to-transpose-horizontal-data-to-vertical-data-for-easy-pivot-tables/
One one of my cells Ax (x referring to the number), the content is ABCDEFGHI and I want to substring the cells every 2 characters, and the last set is 3 characters. Final result looks like:
AB CD EF GHI
At line 44, using the variable
varDetails = .Range(.Cells(lngIdx, 1), .Cells(lngIdx, 4))
and think that is where I need to modify the code. I am not fluent enough with VBA and need some help.
To split the data from your string you can use the following code
Sub SplitStringEveryTwoCharacters()
Dim arrayWithValuesByTwo() As String
Dim myString As String
'Just replace with your data
myString = "ABCDEFGHIJKLM"
'Resize
ReDim arrayWithValuesByTwo(Len(myString) - 1)
'For each 2 character in string
For i = 1 To Len(myString) Step 2
'Add in array
If (i <= Len(myString) - 1) Then
arrayWithValuesByTwo(i - 1) = Mid$(myString, i, 2)
End If
If (i = Len(myString)) Then
arrayWithValuesByTwo(i - 1) = Mid$(myString, i, 1)
End If
Next
End Sub
What you need to change
Here I have set my string into a variable with myString = "ABCDEFGHIJKLM" but you can easily change this and take it directly from a cell with something like myString = Range("A5").
You can access you data with arrayWithValuesByTwo(1) for example. Just loop through it to get all of the values.
I'm currently busy with Excel tooling and learning a lot but i got a question. Currently i have a couple rows with data in the rows. In the rows there is a lot of data but i need a specific part of the row. Of course i can delete it all manually but to do that for 3000 rows i will be wasting a lot of time.
Can any one help me with a macro that filters data. The data i need is between [ and ] so for example [data]
I hope you guys can help me out and if you need more information just ask me! I hope you guys can help me!
Example String ROW:
[Sandwitch]><xsd:element name="T8436283"
So what do i need?
So i need a macro that only gets the Sandwitch out of it and paste it in the B column. The string with all the information stays at column A and the Sandwitch goes to Column B and that for all rows.
Option 1: Find/Replace
1) Copy data in another column (just saving original copy)
2) Perform Find/Replace "*["
3) Perform Find/Replace "]"
Now you have data which was between [].
Option 2: Use formulas
1) Lets assume that original data in Column "A"
2) Apply this formula in column "B" which will extract data between []
=MID(A1,FIND("[",A1)+1,FIND("]",A1)-FIND("[",A1)-1)
Option 3: Macro
If it is absolutely needed, I can help create a macro, otherwise try first two easier options.
A general purpose "find element in s starting x up to next y":
Function GenExtract(FromStr As String, _
StartSep As String, EndSep As String) _
As Variant
Dim StPos As Long
Dim EnPos As Long
GenExtract = CVErr(xlErrNA)
If StartSep = "" Or EndSep = "" Then Exit Function 'fail
StPos = InStr(1, FromStr, Left(StartSep, 1))
If StPos = 0 Or StPos = Len(FromStr) Then Exit Function 'fail
EnPos = InStr(StPos + 1, FromStr, Left(EndSep, 1))
If EnPos = 0 Then Exit Function 'fail
GenExtract = Mid(FromStr, StPos + 1, EnPos - StPos - 1)
End Function
If the two separators are the same, as per quotes, it gives the first string enclosed by those.
If you want to get your feet wet in Regular Expressions, the following code will take you there. You have to add a reference to the VB Scripting Library
Tools > References > Microsoft VBScript Regular Expressions 5.5
Then the code is as follows:
Sub textBetweenStuffs()
Dim str As String
Dim regEx As RegExp
Dim m As Match
Dim sHolder As MatchCollection
Dim bracketCollection As Collection
Dim quoteCollection As Collection
Set regEx = New RegExp
'Matches anything in between an opening bracket and first closing bracket
regEx.Pattern = "\[(.*?\])"
str = "[Sandwitch]><xsd:element name=""T8436283"""
'populates matches into match collection
Set sHolder = regEx.Execute(str)
Set bracketCollection = New Collection
'loop through values in match collection to do with as you wish
For Each m In sHolder
bracketCollection.Add m.Value
Next i
Set sHolder = Nothing
'get values between Quotations
regEx.Pattern = "\"(.*?\")"
'populates matches into match collection
Set sHolder = regEx.Execute(str)
Set quoteCollection = New Collection
'loop through values in match collection to do with as you wish
For Each m In sHolder
quoteCollection.Add m.Value
Next i
End Sub
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.
I have an Excel 2010 spreadsheet, and I am reading in information from a .txt file (and another .xls file in future).
This text file has 3 elements per row; firtname, surname and Job title, and each element is separated by a comma. I have the data reading and pasting into Excel, however each row is pasted into the one cell. I am looking to paste each element into different columns. I know that I should try and delimit, but I just can't figure out the syntax.
My question is how do I separate each element and paste it into it's own cell? I currently use commas to separate each element on my .txt file, but future files might use tabs, full-stops, semi-colons etc. How do I extend it so all bases are covered?
Below is my code, and under my code is a sample of dummy data
Sub FetchDataFromTextFile()
Dim i As Long
Dim LineText As String
Open "C:\mytxtfile.txt" For Input As #24
i = 2
While Not EOF(24)
Line Input #24, LineText
ActiveSheet.Cells(i, 2).Value = LineText
P = Split(Record, ",")
i = i + 1
Wend
Close #24
End Sub
John, Doe, Boss
Johnny, Steele, Manager
Jane, Smith, Employee
NOTE: Competant in other programming languages, however not done VB in about 6 or 7 years. I can never seem to wrap my head around VB Syntax, so please treat me like a novice for this.
Sub FetchDataFromTextFile()
Dim i As Long
Dim LineText As String
Open "C:\mytxtfile.txt" For Input As #24
i = 2
While Not EOF(24)
Line Input #24, LineText
Dim arr
arr = Split(CStr(LineText), ", ")
For j = 1 To
ActiveSheet.Cells(i, j).Value = arr(j - 1)
Next j
i = i + 1
Wend
Close #24
End Sub
For different delimiters, make use of the answers in here
I have a file with a bunch of numbers in columns. These numbers are separated by a variable number of spaces. I want to skip the first line and get all the other lines and separate each number on the line. Finally, I want to write each number in Excel. I've been able to get the lines and write them on Excel but I can't separate each number (I'm getting the whole line as one string).
Does any body know how to split a string that has a variable number of spaces?
Here is my code.
Sub Test()
r = 0
With New Scripting.FileSystemObject
With .OpenTextFile("C:\Users\User\Desktop\File.tab", ForReading)
If Not .AtEndOfStream Then .SkipLine
Do Until .AtEndOfStream
ActiveCell.Offset(r, 0) = Split(.ReadLine, vbCrLf)
r = r + 1
Loop
End With
End With
End Sub
If you use the Excel worksheet function trim in place of the VBA function then excel will remove multiple spaces within a cell (not just from the left and right ends). Something like the below should solve the problem. I'm afraid I've not tested it as I haven't a copy of Excel handy.
Sub Test()
Dim splitValues As Variant
Dim i As Long
r = 0
With New Scripting.FileSystemObject
With .OpenTextFile("C:\Users\User\Desktop\File.tab", ForReading)
If Not .AtEndOfStream Then .SkipLine
Do Until .AtEndOfStream
ActiveCell.Offset(r, 0) = Split(.ReadLine, vbCrLf)
Application.Trim(ActiveCell.Offset(r, 0))
splitValues = Split(ActiveCell.Offset(r, 0), " ")
For i = 0 To UBound(x)
ActiveCell.Offset(r, i+1) = splitValues(i)
Next
Loop
r = r + 1
End With
End With