3

I have been trying all day to do something pretty simple. I am an absolute newbie with VB so I am sure I've missed something.

I have been trying to use MID to split up the numbers in a column on a spreadsheet.

Here is what I have so far (I have been trying to do only one to make sure it works):

Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
Set objWorkbook = objExcel.Workbooks.Open("C:\Documents and Settings\<username>\Desktop\New.csv")

Set objWorksheet = objWorkbook.Worksheets(1)
objWorksheet.Activate

sub_str = Mid(A1, 1, 4)

So the application opens, the worksheet is active, then... nothing. No error or anything. It's like it literally stops there and ignores the last line altogether. The numbers that I want to split look like the below in Excel. They are just dates that are backwards, hence the wanting to split, so I can separate and put it the right way round.

20140101

20140127

20140303

20140310

20140310

20140310

20140310

20140418

20140419

Any help is very appreciated!

Community
  • 1
  • 1
Chris
  • 219
  • 5
  • 18
  • VBS is VBScript and has nothing to do with Excel. VB.net can be used to run Excel via Interop or CreateObject. VBA is used in Excel's Visual Basic (for Applications) code window. Please edit your title and/or tags to be clear which language you are using. – D_Bester Oct 20 '14 at 06:21
  • What makes you think any of the code is running? Where is the code located? What triggers it to run? Workbook_Open? Button? Debug window? – D_Bester Oct 20 '14 at 06:23
  • @ps2goat I really don't think the OP is using VBA else why would they use `CreateObject()`. I'm thinking VBS or VB.net. I think VB.net tag might be appropriate here. – D_Bester Oct 20 '14 at 06:35
  • Well there certainly aren't any `Set`s in .NET. – ps2goat Oct 20 '14 at 06:36
  • @D_Bester, that's probably why it freezes on the OP. Too much recursion. – ps2goat Oct 20 '14 at 06:37
  • @ps2goat True! then probably VBS is it. I think the OP (Chris) should let us know. – D_Bester Oct 20 '14 at 06:37
  • @Chris, if you want to get the value of the cell, you need to do it like this: `Worksheets("Sheet1").Range("A1").Value` – ps2goat Oct 20 '14 at 06:38
  • @ps2goat ??? I don't see any recursion here. Agreed on how to get the A1 value. – D_Bester Oct 20 '14 at 06:39
  • @D_Bester, I'm still thinking VBA-- I haven't tested anything, and it depends on what the op is doing. If he has Excel open and then that immediately tries to get an ActiveX Excel object, then that object opens and tries to do the same thing, there'd be recursion. Not sure without more info. – ps2goat Oct 20 '14 at 06:42
  • @ps2goat Right. "Absolute newbie" as stated by the OP – D_Bester Oct 20 '14 at 06:44
  • @D_Bester, I was attempting VBS. The beginning of the code was running as Excel opened and selected whatever sheet I opted for. Then it did nothing when it hit sub_str. Sorry for not getting back earlier, yesterday got a bit crazy. And yes: absolute newbie! :) – Chris Oct 22 '14 at 00:33
  • @ps2goat, I was trying with VBS, but was obviously very wrong in my attempt. I have now been offered and answer, but thank you for your suggestion and your time. It is appreciated. – Chris Oct 22 '14 at 00:35

3 Answers3

2

Try this:

Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
Set objWorkbook = objExcel.Workbooks.Open("C:\Users\USER\Desktop\new1.csv")

Set objWorksheet = objWorkbook.Worksheets(1)
objWorksheet.Activate
rowCount=objWorksheet.usedrange.rows.count
Set rngA=objWorksheet.Range("A1:A" & rowCount)
'Set rngB=rngA.offset(,1)             'objWorksheet.Range("B1")


with objWorksheet
for each cell in rngA
sub_strY = Mid(cell.value, 1, 4)
sub_strM=Mid(cell.value, 5, 2)
sub_strD=Mid(cell.value, 7, 2)
'msgbox sub_strY
'msgbox sub_strM
'msgbox sub_strD
strDate=sub_strD & "/" & sub_strM & "/" & sub_strY
msgbox strDate
'cell.offset(,1).value=strDate     ''to another column  
cell.value=strDate                 ''to overwrite
next
end with
ZAT
  • 1,347
  • 7
  • 10
  • This worked great, thanks so much! I kept [[strDate=sub_strD & "/" & sub_strM & "/" & sub_strY]] , but just removed the [["/"]] , as I am not sure what they want to do with the dates yet. I really appreciate the time you put into helping me :) I can't get code tags to work, so add double square brackets instead. – Chris Oct 21 '14 at 22:02
  • `tildecodetilde` is like this, replace tilde with actual character. Welcome and glad to help. – ZAT Oct 22 '14 at 07:06
  • No offense but can you tell me how is your code different than that I posted? Except that you used used range to find the last row which actually is the incorrect way of finding the last row ad you are using a different loop. see [THIS](http://stackoverflow.com/questions/11169445/error-finding-last-used-cell-in-vba) :) – Siddharth Rout Oct 22 '14 at 08:29
  • None taken. Actually I did not see what was inside your code. It appears you have used left and right. And yes, usedrange approach is not applicable for all case, but it served the purpose in this case. I feel sorry for any ambiguity and misunderstanding. – ZAT Oct 22 '14 at 08:49
1

You can use Mid in vbscript. The problem is not there. The problem is in A1 in the line sub_str = Mid(A1, 1, 4).

A1 has been treated like a variable. It's always best to work with objects. Also if you want 20140419 to be changed to 04192014 then you actually do not need Mid. You can use Left and Right for this.

I am assuming that the data is in the format yyyymmdd and you want output as mmddyyyy. If you want the output as ddmmyyyy, then you will have to use Mid. like this

sDate = Right(.Range("A" & i).Value, 2) & _
        Mid(.Range("A" & i).Value, 5, 2) & _
        Left(.Range("A" & i).Value, 4)

Is this what you are trying?

Const xlUp = -4162

Dim oXLApp, oXLwb, oXLws
Dim lRow, i
Dim sFile, sDate 

'~~> Change this to the relevant file
sFile = "C:\Users\Siddharth Rout\Desktop\book1.xlsx"

'~~> Establish an EXCEL application object
On Error Resume Next
Set oXLApp = GetObject(, "Excel.Application")

'~~> If not found then create new instance
If Err.Number <> 0 Then
    Set oXLApp = CreateObject("Excel.Application")
End If
Err.Clear
On Error GoTo 0

'~~> Hide Excel
oXLApp.Visible = False

'~~> Open files
Set oXLwb = oXLApp.Workbooks.Open(sFile)

'~~> Set the worksheet you want to work with
Set oXLws = oXLwb.Sheets(1)

'~~> work with the worksheet
With oXLws
    lRow = .Range("A" & .Rows.Count).End(xlUp).Row

    For i = 1 To lRow
        '~~> 20140101 becomes 01012014. If the Col A is formatted 
        '~~> as number then the leading `0` will disappear as 
        '~~> shown in the screenshot below
        sDate = Right(.Range("A" & i).Value, 4) & Left(.Range("A" & i).Value, 4)
        .Range("A" & i).Value = sDate
    Next
End With

'~~> Close and save
oXLwb.Close (True)

'~~> CLEANUP (VERY IMPROTANT)
Set oXLws = Nothing
Set oXLwb = Nothing
oXLApp.Quit
Set oXLApp = Nothing

MsgBox "DONE" 'OR wscript.echo "Done"

Screenshots:

Before

enter image description here

After

enter image description here

Siddharth Rout
  • 147,039
  • 17
  • 206
  • 250
  • I appreciate the time you put into helping me with this and apologize for taking so long to get back to you. Yesterday was one of those days, you know. I tried the code, but it failed at [[Dim sFile, sDate as string]] complaining about "Expected end of statement". From what I read, you cannot Dim variables as something in particular in VBS. I was unable to figure it out, though. ZAT's code above has worked perfectly, but thank you for your help :) – Chris Oct 21 '14 at 22:08
  • Yes, you are right, I have removed it. I had typed that in excel and had forgotten to delete it. NOw try it. it works just fine as shown in the screenshots :) – Siddharth Rout Oct 21 '14 at 23:26
  • Hey, spot on! Thanks again for that. I didn't think to remove it and instead was trying to 'fix' it. Ha! – Chris Oct 22 '14 at 00:29
  • That's ok :) Apologies for not taking care of that. I usually do not make these kind of mistakes... :( – Siddharth Rout Oct 22 '14 at 00:42
0

The Mid function is not a VBscript function but a VBA function therefore if anyway this might work:

objExcel.Mid([A1], 1, 4)

instead of this:

Mid(A1, 1, 4)

If this does not work a you need to run Excel then try putting all the logic in the Excel function and executing it from VBscript if needed (example below):

RunMacro
Sub RunMacro() 
  dim xl
  Set xl = CreateObject("Excel.application")
  Dim xlBook      
  Dim sCurPath
  path = CreateObject("Scripting.FileSystemObject").GetAbsolutePathName(".")
  Set xl = CreateObject("Excel.application")
  Set xlBook = xl.Workbooks.Open(path & "\Book1.xlsm", 0, True)      
  xl.Application.Visible = False
  xl.DisplayAlerts = False    
  xl.Application.run "Book1.xlsm!Module.MyMacro"
  xl.ActiveWindow.close
  Set xlBook = Nothing
  xl.Quit 
  Set xl = Nothing
End Sub
AnalystCave.com
  • 4,884
  • 2
  • 22
  • 30