In an excel file I want to rewrite a string from left to write - excel-2007

In my excel file I have a column containing 123456789 (as an example)
I want to find an excel function to rewrite this string to 987654321

You need to make a new module for that. (alt+F11 then right click and 'insert new module')
then you can write something like this in your module :
Function Reverse(str As String) As String
Reverse = StrReverse(str)
End Function
with that you will be able to call =Reverse(A1) for exemple to reverse the cell text.

Related

Extracting substring based on different criterias and placing the extracted string in another cell of same row

I have an excel file, in which there is a column containing a specific string. This string doesn't follow any particular pattern. My requirement is to extract a sub-string (product id) which is a set of 8 consecutive numbers that have to be preceded/followed by any no of characters or must be at the start or end of the string.
Following are some examples.
Scenario 1:
product id is preceded by #
Id#53298632/BS TVR:003519
Function used in excel
=MID(N88,FIND("#",N88)+1,8)
* result : 53298632 *
Scenario 2:
product id is at the beginning
53298632:003519
Function used in excel
=MID(A1,1,8)
* result : 53298632 *
At the beginning I had to deal with only scenario 1 and hence used the specified formula. Now a days the string doesnt follow any particular pattern but my product id still comes as 8 digit consecutive numbers. I searched for a suitable solution and found this formula (which I dont clearly understand).
=LOOKUP(10^8,MID(N132,ROW(INDIRECT("1:"&LEN(N132)-7)),8)+0)
This does work in most of the cases but in some cases it fails
For example
Pdr#53298632/ QTY NOS 1031949
Here the result is 1031949 which is definitely not what I want. The result should have been 53298632
Please help me fix this. Can this be done using VBA macro? I am completely new to such excel functions VBA and macro.
Any help will be highly appreciated!
Thanks in advance.
If you are happy to specifically include the Microsoft RegEx module into your Excel project, regular expressions will solve this reasonably quickly.
To add the RegEx function to use in your Excel Macros, select the Developer menu in Excel and start the Visual Basic editor. Within the VBA for Applications window, Select Tools->References and select Microsoft VBScript Regular Expressions 5.5.
Create a new Module for your VBAProject (right-click on your Excel file name in the project tree and click Insert->Module)
Double click on the newly created Module (within the project tree) and enter the following code in the Module1 (Code) window:
Public Function getProductCode(source As String) As String
Dim strPattern As String: strPattern = "(\d{8})"
Dim result As String: result = ""
Dim results As Object
Dim regEx As New RegExp
With regEx
.Global = True
.MultiLine = False
.IgnoreCase = False
.Pattern = strPattern
End With
If regEx.Test(source) Then
Set results = regEx.Execute(source)
If (results.Count <> 0) Then
result = results.Item(0)
End If
End If
getProductCode = result
End Function
From the relevant cell in Excel, you can now call the macro:
=getProductCode(A1)
I guess you could also modify the original formula to pick up the first match of an 8-digit number
=MID(A1,MATCH(TRUE,ISNUMBER(MID(A1,ROW(INDIRECT("1:"&LEN(A1)-7)),8)+0),0),8)
(must be entered as an array formula using CtrlShiftEnter).

How to count the number of empty spaces in front of a String in VBA?

I have a YAML file which I am reading using VBA Excel plugin. I am getting a String of each line. I need to count the number of empty spaces in the front of the first line so that it will be a marker to find the next key. Let me know how to do that.
Option Explicit
Function empty_spaces(str_input)
empty_spaces = Len(str_input) - Len(LTrim(str_input))
End Function
harun24hr, your answer does not work with " My String " and similar.

VB.Net Read multi column text file and load into ListBox

First, I am not a programmer, I mainly just do simple scripts however there are somethings that are just easier to do in VB, I am pretty much self taught so forgive me if this sounds basic or if I can't explain it to well.
I have run into an issue trying to load a multi-column text file into a list box. There are two separate issues.
First issue is to read the text file and only grab the first column to use in the listbox, I am currently using ReadAllLines to copy the text file to a string first.
Dim RDPItems() As String = IO.File.ReadAllLines(MyDocsDir & "\RDPservers.txt")
However I am having a difficult time finding the correct code to only grab the first Column of this string to put in the listbox, if I use the split option I get an error that "Value of type '1-dimensional array of String' cannot be converted to 'String'"
The code looked like
frmRDP.lstRDP.Items.Add() = Split(RDPItems, ";", CompareMethod.Text)
This is the first hurdle, the second issue is what I want to do is if an item is selected from the List box, the value of the second column gets pulled into a variable to use.
This part I'm not even sure where to begin.
Example data of the text file
Server1 ; 10.1.1.1:3389
Server2 ; 192.168.1.1:8080
Server3 ; 172.16.0.1:9833
.....
When it's working the application will read a text file with a list of servers and their IPs and put the servers in a listbox, when you select the server from the listbox it and click a connect button it will then launch
c:\windows\system32\mstsc.exe /v:serverip
Any help would be appreciated, as I can hard code a large list of this into the VB application it would be easier to just have a text file with a list of servers and IPs to load instead.
The best practise for this would probably be to store your "columns" in a Dictionary. Declare this at class level (that is, outside any Sub or Function):
Dim Servers As New Dictionary(Of String, String)
When you load your items you read the file line-by-line, adding the items to the Dictionary and the ListBox at the same time:
Using Reader As New IO.StreamReader(IO.Path.Combine(MyDocsDir, "RDPservers.txt")) 'Open the file.
While Reader.EndOfStream = False 'Loop until the StreamReader has read the whole file.
Dim Line As String = Reader.ReadLine() 'Read a line.
Dim LineParts() As String = Line.Split(New String() {" ; "}, StringSplitOptions.None) 'Split the line into two parts.
Servers.Add(LineParts(0), LineParts(1)) 'Add them to the Dictionary. LineParts(0) is the name, LineParts(1) is the IP-address.
lstRDP.Items.Add(LineParts(0)) 'Add the name to the ListBox.
End While
End Using 'Dispose the StreamReader.
(Note that I used IO.Path.Combine() instead of simply concatenating the strings. I recommend using that instead for joining paths together)
Now, whenever you want to get the IP-address from the selected item you can just do for example:
Dim IP As String = Servers(lstRDP.SelectedItem.ToString())
Hope this helps!
EDIT:
Missed that you wanted to start a process with it... But it's like charliefox2 wrote:
Process.Start("c:\windows\system32\mstsc.exe", "/v:" & Servers(lstRDP.SelectedItem.ToString()))
Edit: #Visual Vincent's answer is way cleaner. I'll leave mine, but I recommend using his solution instead. That said, scroll down a little for how to open the server. He's got that too! Upvote his answer, and mark it as correct!
It looks like you're trying to split an array. Also, ListBox.Items.Add() works a bit differently than the way you've written your code. Let's take a look.
ListBox.Items.Add() requires that you provide it with a string inside the parameters. So you would do it like this:
frmRDP.lstRDP.Items.Add(Split(RDPItems, ";", CompareMethod.Text))
But don't do that!
When you call Split(), you must supply it with a string, not an array. In this case, RDPItems is an array, so we can't split the entire thing at once. This is the source of the error you were getting. Instead, we'll have to do it one item at a time. For this, we can use a For Each loop. See here for more info if you're not familiar with the concept.
A For Each loop will execute a block of code for each item in a collection. Using this, we get:
For Each item In RDPItems
Dim splitline() As String = Split(item, ";") 'splits the item by semicolon, and puts each portion into the array
frmRDP.lstRDP.Items.Add(splitline(0)) 'adds the first item in the array
Next
OK, so that gets us our server list put in our ListBox. But now, we want to open the server that our user has selected. To do that, we'll need an event handler (to know when the user has double clicked something), we'll have to find out which server they selected, and then we'll have to open that server.
We'll start by handling the double click by creating a sub to deal with it:
Private Sub lstRDP_MouseDoubleClick(sender As Object, e As MouseEventArgs) Handles lstRDP.MouseDoubleClick
Next, we'll get what the user has selected. Here, we're setting selection equal to the index that the user has selected (in this case, the first item is 0, the second is 1, and so on).
Dim selection As Integer = lstRDP.SelectedIndex
Lastly, we need to open the server. I'm assuming you want to do that in windows explorer, but if I'm mistaken please let me know.
Dim splitline() As String = Split(RDPItems(selection), ";")
Dim location As String = Trim(splitline(1))
We'll need to split the string again, but you'll notice this time I'm choosing the item whose location in the array is the same as the index of the list box the user has selected. Since we added our items to our listbox in the order they were added to our array, the first item in our listbox will be the first in the array, and so on. The location of the server will be the second part of the split function, or splitline(1). I've also included the Trim() function, which will remove any leading or trailing spaces.
Finally, we need to connect to our server. We'll use Process.Start() to launch the process.
Process.Start("c:\windows\system32\mstsc.exe", "/v:" & location)
For future reference, to first argument for Process.Start() is the location of the process, and the second argument is any argument the process might take (in this case, what to connect to).
Our final double click event handler looks something like this:
Private Sub lstRDP_MouseDoubleClick(sender As Object, e As MouseEventArgs) Handles lstRDP.MouseDoubleClick
Dim selection As Integer = lstRDP.SelectedIndex
Dim splitline() As String = Split(RDPItems(selection), ";")
Dim location As String = Trim(splitline(1))
Process.Start("c:\windows\system32\mstsc.exe", "/v:" & location)
End Sub
A final note: You may need to put
Dim RDPItems() As String = IO.File.ReadAllLines(MyDocsDir & "\RDPservers.txt")
outside of a sub, and instead just inside your class. This will ensure that both the click handler and your other sub where you populate the list box can both read from it.

Removing blank fields from a delimited file using VB.NET

Using VB.NET (VS2013) I'd like to read a delimited file and remove a field if all records have the same blank field (could be multiple fields per record). The delimited file can have "x" number of columns and "y" number of rows and once the blank fields are removed, I need to write it back out as a new delimited file.
The input file will have a header that has to be maintained and the order of the records has to be maintained. I'm familiar with using TextParser to read the file and familiar with writing the file -- what I need help with is reading for a blank field and removing it if it exists across the entire file.
I was thinking I would have to use a datagrid but never used them so looking for some insight to point me in the direction.
Thanks!
I assume each line is delimited with a newline... open as a text file, read a line at a time and use the Split method to break up the line into an array of strings. The split method will take an argument that defines the delimiter you are using. Open the destination file and write the array of strings using a loop.
UPDATE
After thinking about it, you may have records that have a couple of blank columns and the rest have data. I'm not sure if you'd want to remove those columns, because you would lose the structure of the row if you did.
So instead of using StringSplitOptions.RemoveEmptyEntries, you can just do the Split() and then perform some Linq to find out if the Split() produced an array of empty strings.
Something like (with the same results)...
Imports System
Imports System.Linq
Public Module Module1
Public Sub Main()
Dim data As String = "|||||"
Dim pieces As String() = data.Split("|"c)
If pieces.Where(Function(p) String.IsNullOrEmpty(p) = False).Count = 0 Then
Console.WriteLine("All elements are empty")
Else
' Do something
End If
End Sub
End Module
Demo
OLD ANSWER
The String.Split() has an overload that excepts StringSplitOptions. Use StringSplitOptions.RemoveEmptyEntries with your String.Split() and if all records are blank then you'll end up with an array with a length of 0 that you can ignore.
Imports System
Public Module Module1
Public Sub Main()
Dim data As String = "|||||"
Dim pieces As String() = data.Split(new Char() {"|"}, StringSplitOptions.RemoveEmptyEntries)
If pieces.length = 0 Then
Console.WriteLine("All elements are empty")
Else
' Do something
End If
End Sub
End Module
Results:
All elements are empty
Demo

How can I return the results of a function to a cell in Excel?

Suppose I have a function attached to one of my Excel sheets:
Public Function foo(bar As Integer) as integer
foo = 42
End Function
How can I get the results of foo returned to a cell on my sheet? I've tried "=foo(10)", but all it gives me is "#NAME?"
I've also tried =[filename]!foo(10) and [sheetname]!foo(10) with no change.
Try following the directions here to make sure you're doing everything correctly, specifically about where to put it. ( Insert->Module )
I can confirm that opening up the VBA editor, using Insert->Module, and the following code:
Function TimesTwo(Value As Integer)
TimesTwo = Value * 2
End Function
and on a sheet putting "=TimesTwo(100)" into a cell gives me 200.
Put the function in a new, separate module (Insert->Module), then use =foo(10) within a cell formula to invoke it.
Where did you put the "foo" function? I don't know why, but whenever I've seen this, the solution is to record a dimple macro, and let Excel create a new module for that macro's code. Then, put your "foo" function in that module. Your code works when I follow this procedure, but if I put it in the code module attached to "ThisWorkbook," I get the #NAME result you report.
include the file name like this
=PERSONAL.XLS!foo(10)