I am using following code to read csv file and finally the data is converted into array.
Function Sample(strPath) As String()
Dim MyData As String, strData() As String
Open strPath For Binary As #1
MyData = Space$(LOF(1))
Get #1, , MyData
Close #1
Sample = Split(MyData, vbCrLf)
End Function
Following code convert each comma separated line into array.
SaleRows = Sample(filepath)
For Each SaleRow In SaleRows
SaleRowArray = Split(SaleRow, ",")
Next SaleRow
Everything works fine but when a cell contains comma, my above function fails. Is there any way to handle comma in a particular cell?
Sample csv
Please observe comma in second row.
When I get array from the comma record, I get below.
It's likely that the strings in your CSV file are escaped with quote marks. If you want to parse the CSV using your own code, then your code needs to be able to ignore commas which occur inside quotes.
A quick way to do this would be to use RegEx. You could try the following:
Private Function changeDelimiter(line as String) as String
Dim regEx As Object
Set regEx = CreateObject("VBScript.regexp")
regEx.IgnoreCase = True
regEx.Global = True
regex.Pattern = ",(?=([^" & Chr(34) & "]*" & Chr(34) & "[^" & Chr(34) & "]*" & Chr(34) & ")*(?![^" & Chr(34) & "]*" & Chr(34) & "))"
changeDelimiter = regex.Replace(line, "#|#")
End Function
Then change the Split() line in your code as follows:
SaleRowArray = Split(changeDelimiter(SaleRow), "#|#")
The function replaces all commas outside quote marks with #|# (which I assume won't ever come up in your input data). You then split the lines into data fields on #|# instead of comma.
Related
so I have this check combo box data source from SQL Server
Let's say I have these string value from the combo box
ABC, DEF, GHI
What I wanted next is get those string
and make them become like this
'ABC', 'DEF', 'GHI'
I've tried combining them with "'" & comboBox.Text & "'"
but it looks like this
'ABC, DEF, GHI'
You're starting with a delimited string and you want to process each substring separately, so that means splitting, processing and joining the string. There are a number of variations on a theme that will do that. Here are a couple of examples:
Dim substrings = comboBox.Text.Split(","c)
For i = 0 To substrings.getUpperBound(0)
substrings(i) = "'" & substrings(i).Trim() & "'"
Next
Dim result = String.Join(", ", substrings)
Dim result = String.Join(", ",
comboBox.Text.
Split(","c).
Select(Function(s) $"'{s.Trim()}'"))
Note that, if you're confident that there will always be a comma and one space between substrings then you can incorporate the space into the Split and do away with the Trim:
Dim substrings = comboBox.Text.Split({", "}, StringSplitOptions.None)
For i = 0 To substrings.getUpperBound(0)
substrings(i) = "'" & substrings(i) & "'"
Next
Well, you can do it LINQ style like:
Dim res as string = String.Join(“, “, String.Split(“,”c, original).Select(Function(f) $”’{f.Trim}’”))
The process is to split the original into its component parts, remove any white space, add surrounding quotes and combine back into a single string with “, “ as a separator.
This code specifies the name with which to save Word documents.
ActiveDocument.SaveAs FileName:=MyString & Mystring2 & MyString3 & MyString4
I am trying to remove special characters from a value I've added to the file name.
It works before the final step of removing special characters from MyString4.
MyString4 is Document.Bookmarks("Index").Range.Text
I'm trying to declare the whole line as a separate variable.
Dim Mystring
MyString4 = Document.Bookmarks("Index").Range.Text
and then use the Replace command to get rid of some specific characters.
Unfortunately, it will not let me declare the line as a separate variable. The files get saved without MyString4 at the end.
The simplest solution is to replace
MyString & Mystring2 & MyString3 & MyString4
with a call to a function that does the necessary replacments
SafeFileName(MyString & Mystring2 & MyString3 & MyString4)
Using
Public Function SafeFileName(ByVal ipFileName as String) as String
' Do as many replaces as you need
ipFileName=Replace(ipFileNAme, <your find text 1>, <your replace text>
ipFileName=Replace(ipFileNAme, <your find text 2>, <your replace text>
ipFileName=Replace(ipFileNAme, <your find text 3>, <your replace text>
SafeFileName = ipFilename
End Function
You can be smarter by using a regexp in your function but this might be a job for another day.
For example, the following replaces illegal filename characters with underscores:
Dim i As Long: Const StrExcl As String = """*./\:?|"
StrName = MyString & Mystring2 & MyString3 & MyString4
For i = 1 To Len(StrExcl)
StrName = Replace(StrName, Mid(StrExcl, i, 1), "_")
Next
StrName = Trim(StrName)
ActiveDocument.SaveAs FileName:=StrName & ".docx"
I am trying to split data using VBA within word.
I have got the data using the following method
d = ActiveDocument.Tables(1).Cell(1, 1).Range.Text
This works and gets the correct data. Data for this example is
This
is
a
test
However, when I need to split the string into a list of strings using the delimiter as \n
Here is an example of the desired output
This,is,a,test
I am currently using
Dim dataTesting() As String
dataTesting() = Split(d, vbLf)
Debug.Print dataTesting(0)
However, this returns all the data and not just the first line.
Here is what I have tried within the Split function
\n
\n\r
\r
vbNewLine
vbLf
vbCr
vbCrLf
Word uses vbCr (ANSI 13) to write a "new" paragraph (created when you press ENTER) - represented in the Word UI by ¶ if the display of non-printing characters is activated.
In this case, the table cell content you show would look like this
This¶
is¶
a¶
test¶
The correct way to split an array delimited by a pilcro in Word is:
Dim d as String
d = ActiveDocument.Tables(1).Cell(1, 1).Range.Text
Dim dataTesting() As String
dataTesting() = Split(d, vbCr)
Debug.Print dataTesting(0) 'result is "This"
You can try this (regex splitter from this thread)
Sub fff()
Dim d As String
Dim dataTesting() As String
d = ActiveDocument.Tables(1).Cell(1, 1).Range.Text
dataTesting() = SplitRe(d, "\s+")
Debug.Print "1:" & dataTesting(0)
Debug.Print "2:" & dataTesting(1)
Debug.Print "3:" & dataTesting(2)
Debug.Print "4:" & dataTesting(3)
End Sub
Public Function SplitRe(Text As String, Pattern As String, Optional IgnoreCase As Boolean) As String()
Static re As Object
If re Is Nothing Then
Set re = CreateObject("VBScript.RegExp")
re.Global = True
re.MultiLine = True
End If
re.IgnoreCase = IgnoreCase
re.Pattern = Pattern
SplitRe = Strings.Split(re.Replace(Text, ChrW(-1)), ChrW(-1))
End Function
If this doesn't work, there may be strange unicode/Wprd characters in your Word doc. It may be soft breaks, for instance. You could try to not split with "\W+" in stead of "\s+". I cannot test this without your document.
Dim dataTesting() As String
dataTesting() = Split(d, vbLf)
Debug.Print dataTesting(0)
works fine and thank you very much for your example,
for why it have returned a whole array is because you have used 0 as index, in many programming languages 0 is the whole array, so the first element is ,
so in my case counting from 1 this perfectly split a string that I had troubles with.
To be more exact this is how it was used in my case
Dim dataTesting() As String
dataTesting() = Split(Document.LatheMachineSetup.Heads.Item(1).Comment, vbCrLf)
MsgBox (dataTesting(1))
And that comment is a multiline string.
Image
So this msg box returned exactly first line.
I have a PDF file that contains a table. I want to use Excel-VBA to search just the first column for an array of values. I have a work around solution at the moment. I converted the PDF to a text file and search it like that. The problem is sometimes these values can be found in multiple columns, and I have no way of telling which one it's in. I ONLY want it if it's in the first column.
When the PDF converts to text, it converts it in a way such that there is an unpredictable amount of lines for each piece of information, so I can't convert it back to a table in an excel sheet based on the number of lines (believe me, I tried). The current method searches each line, and if it sees a match, it checks to see if the two strings are the same length. But like I mentioned earlier, (in a rare case but it does happen) there will be a match in a column that is NOT the column I want to search in. So, I'm wondering, is there a way to extract a single column from a PDF? Or even the entire table as it stands?
Public Sub checkNPCClist()
Dim lines As String
Dim linesArr() As String
Dim line As Variant
Dim these As String
lines = Sheet2.Range("F104").Value & ", " & Sheet2.Range("F105").Value & ", " & Sheet2.Range("F106").Value & ", " & Sheet2.Range("F107").Value
linesArr() = Split(lines, ",")
For Each line In linesArr()
If line <> " " Then
If matchlinename(CStr(line)) = True Then these = these & Trim(CStr(line)) & ", "
End If
Next line
If these <> "" Then
Sheet2.Range("H104").Value = Left(these, Len(these) - 2)
Else: Sheet2.Range("H104").Value = "Nope, none."
End If
End Sub
Function matchlinename(lookfor As String) As Boolean
Dim filename As String
Dim textdata As String
Dim textrow As String
Dim fileno As Integer
Dim temp As String
fileno = FreeFile
filename = "C:\Users\...filepath"
lookfor = Trim(lookfor)
Open filename For Input As #fileno
Do While Not EOF(fileno)
temp = textrow
Line Input #fileno, textrow
If InStr(1, textrow, lookfor, vbTextCompare) Then
If Len(Trim(textrow)) = Len(lookfor) Then
Close #fileno
matchlinename = True
GoTo endthis
End If
End If
'Debug.Print textdata
Loop
Close #fileno
matchlinename = False
endthis:
End Function
I'm rooky for VBA. I have some problem about reversing my data on VBA-Excel. My data is "3>8 , 6>15 , 26>41 (each data on difference cells)" that i could reverse "3>8" to "8>3" follow my requirement by using function reverse. But i couldn't reverse "6>15" and "26>41" to "15>6" and "41>26". It will be "51>6" and "14>62" that failure, I want to be "15>6" and "41>26".
Reverse = StrReverse(Trim(str))
Help me for solve my issue please and thank for comment.
You first need to find the position of the ">" in the cell. you do this by taking the contents of the cell and treating it as a String and finding the ">"
This is done in the line beginning arrowPosition. This is the integer value of the position of the ">" in you original string
Next use Left to extract the text up to the ">" and Right to extract the text after the ">"
Then build a new String of rightstr & ">" & leftStr.
Note I input my data from Sheet1 B5 but you can just use any source as long as it is a String in the correct format.
Sub Test()
Dim myString As String
myString = Sheets("Sheet1").Range("B5")
Debug.Print myString
Debug.Print reverseString(myString)
End Sub
Function reverseString(inputString As String) As String
Dim leftStr As String
Dim rightStr As String
Dim arrowPosition As Integer
arrowPosition = InStr(1, inputString, ">")
leftStr = Left(inputString, arrowPosition - 1)
rightStr = Right(inputString, Len(inputString) - arrowPosition)
reverseString = rightStr & ">" & leftStr
End Function
just because you look for a VBA, you can add this function into your code:
Function rev(t As String) As String
s = Split(t, ">", 2)
rev = s(1) & ">" & s(0)
End Function
of course only if you have to reverse 2 number, otherwise you'll loop the "s", but the function would lose its usefulness