Reading files into a spreadsheet using VBA is very slow - macos

I am using the following VBA code to import a rather large text file into a spreadsheet, however this seems to take ages. (Approximately 0.0064 seconds per cell, which quickly becomes too much when the files are substantially larger.) The file is simply stored locally so this could not be an issue.
My code currently looks like this:
Public Sub DataImport(fullFileName As String, worksheetName As String, cellName As String)
'Move to the sheet and desired first cell
ActiveWorkbook.Sheets(worksheetName).Activate
Range(cellName).Activate
Open fullFileName For Input As #1
' Copy the file into the excel sheet
row_number = 0
Do Until EOF(1)
Line Input #1, LineFromFile
LineItems = Split(LineFromFile, vbTab)
For i1 = LBound(LineItems) To UBound(LineItems)
ActiveCell.Offset(row_number, i1).Value = LineItems(i1)
On Error Resume Next
ActiveCell.Offset(row_number, i1).Value = ActiveCell.Offset(row_number, i1).Value * 1
Next i1
row_number = row_number + 1
Loop
Close #1
End Sub
EDIT: I am working on Office For Mac and the final product should work on both Windows and OS X.
All help on this is greatly appreciated!
Kind regards

The code in question works with active sheet with updates switched on (default). This means Excel has to redraw the screen and recalculate the sheet every time a cell is updated. Try disable updates during import with "Application.ScreenUpdating = False". The drawback is, that Excel becomes unresponsive during the update. Finally , turn the screen updating back on.

Related

Odd problem. Step through works, runtime doesn't

Morning all.
I've seen numerous posts about this problem on here, but nothing specific to my situation so would appreciate some assistance with this.
Essentially, I'm attempting to rearrange the order of tabpages on a tabcontrol, based on the order of entries in a listbox (lbxBuildings). The number of pages always matches the number of listbox entries, and their text values also match up.
Now I've written the following code which works perfectly when I step through it, but doesn't work (or error) at runtime.
Private Sub cmdBlgSetDown_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdBlgSetDown.Click
'Make sure our item is not the last one on the list.
If lbxBuildings.SelectedIndex < lbxBuildings.Items.Count - 1 Then
'Insert places items above the index you supply, since we want
'to move it down the list we have to do + 2
Dim I = lbxBuildings.SelectedIndex + 2
Dim j As Integer = lbxBuildings.SelectedIndex
Dim NTP As TabPage = TabControl2.TabPages(j)
TabControl2.TabPages.Insert(I, NTP)
TabControl2.SelectedIndex = I - 1
TabControl2.TabPages.Remove(NTP)
lbxBuildings.Items.Insert(I, lbxBuildings.SelectedItem)
lbxBuildings.Items.RemoveAt(lbxBuildings.SelectedIndex)
lbxBuildings.SelectedIndex = I - 1
End If
End Sub
The rearranging of the listbox is controlled by two buttons (one up and one down) and that all works fine, so I now want the same buttons to rearrange the tabpages as well. There may well be information already entered on these pages prior to their being rearranged, so deleting one and adding a new one won't work for me (as far as I can tell).
My 'solution' of adding in a copy in the correct place then deleting the original makes perfect sense to me and as I say, it works when I step through. But at runtime, it seems to skip right over the 'insert' line and just deletes the orignal tab.
All suggestions welcome.
Many thanks!
Well after a load more digging I found mention of this specific problem on a C# site. More digging still and it turns out that there's a bug in the program with the following workaround.
Dim h As IntPtr = TabControl2.Handle
Call this 'before' doing anything with the tabcontrol and it works as expected. It's a bit odd but there it is.

Missing events in properties for VB6

I am a self taught amateur Visual Basic programmer. My programs are for myself, friends and some non-profit organizations. I have a situation that I thought would be reasonably simple but doesn't seems the case.
I have a text box array of 6 elements (1 -6) named "txtBilled" .When the value is entered into any but element 6 I want to add the values in 1-5 and put result in element 6. My problems start due to the fact that the properties for the text array does not provide for a lost focus option. Searching the inter provides statements that this is normal, others say the "Lost Focus" should always be there.
As a second approach I tried to use the validate element. Never used this before created a sub as follows that I found on the web.
Private sub txtBilled__Validate(Cancel as Boolean)
Found that the Validate event is also not included in the properties for the array
I am using VB6 version 8176 under Windows 10.
Any ideal as to what I am doing incorrectly would be appreciated.
Can you not create your own LostFocus sub using the Index of the textbox array?
Private Sub txtBilled_LostFocus(Index As Integer)
Dim i As Integer
dim sngTotal As Single
' Calculate sum only if not in last textbox
If Index <> uBound(txtBilled) Then
For i = LBound(txtBilled) to UBound(txtBilled) - 1
sngTotal = sngTotal + txtBilled(i)
Next i
txtBilled(uBound(txtBilled)) = sngTotal
End If
End Sub

Copy a Cell Below A Cell with a Constant Value (see screenshot) - excel [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
The picture will make it all make sense. But I'm just trying to copy the text from below the "Author information:" Cell to another cell location. This isn't difficult for a few because it's just a simple copy and paste but I need to search the entire worksheet and extract all of the info from the first cell below "Author information:" At this point there are thousands of entries...
Screenshot Dropbox link: https://www.dropbox.com/s/nbyg8lkay3c5c9s/Screenshot%202013-12-27%2016.32.38.png
Any help would be fantastic!
For ease, try the following.
In cell C2 type this formula =IF(A1="Author Information:",A2,"")
Copy this formula all the way down
copy the results in column C to another sheet and paste-special with values only
Sort that sheet to get rid of blanks
That should be a quick and dirty way to get it done.
Try this code:
Sub copyAuthorInfo()
Dim src As Worksheet, tgt As Worksheet
Dim irows As Long
Dim rrows As Long
Set src = ThisWorkbook.Sheets("Sheet1") ' this is the sheet with the original data
Set tgt = ThisWorkbook.Sheets("Sheet2") ' author info will be copied into this sheet
irows = src.UsedRange.Rows.Count ' count the number of used rows in sheet 1
rrows = 1 'row counter for the target sheet
For i = 1 To irows
If Cells(i, 1).Value = "Author information:" Then 'make sure to adjust the search text
' copying columns A to C. Change the 3 in the following line to copy more columns.
Range(Cells(i + 1, 1), Cells(i + 1, 3)).Copy tgt.Range("A" & rrows)
rrows = rrows + 1
End If
Next
End Sub
To run the code, you need to open the Visual Basic Editor (VBE) with Alt-F11 or your preferred method. Use Insert > Module and paste the code. You can run the code by hitting F5 while the cursor is somewhere in the code.
You have tagged with OSX. Does that mean you use a Mac? You also tagged with Excel 2007 and 2010. The code will run fine in these, but not in Excel 2008 for Mac, because it does not support VBA.

Insert Property of Picture Class

I have read all of the questions on here about this topic and none of them provided me with a workable solution, so I'm asking this one.
I am running a legitimate copy of Excel 2013 in Windows 7. I record a macros where I insert a picture, and in the open file dialog I paste this URL: http://ecx.images-amazon.com/images/I/41u%2BilIi00L._SL160_.jpg (simply a picture of a product on Amazon). This works as expected.
The resulting macros looks like this:
Sub insertImage()
'
' percent Macro
'
'
ActiveSheet.Pictures.Insert( _
"http://ecx.images-amazon.com/images/I/41u+ilIi00L._SL160_.jpg").Select
End Sub
However, when I attempt to run this, the Insert line breaks with the following error:
Run-time error '1004':
Unable to get the Insert property of the Picture class
I am trying to insert a number of pictures into an excel document and I am using the ActiveSheet.Pictures.Insert method to do this. I have been experiencing this issue there, so I recreated it in a way others could replicate to facilitate getting an answer...
An interesting thing to note is:
http://ecx.images-amazon.com/images/I/41u%2BilIi00L._SL160_.jpg 'This is what I pasted
http://ecx.images-amazon.com/images/I/41u+ilIi00L._SL160_.jpg 'This is what the recorded macros recorded
It looks like Excel automatically resolved the %2B to a +. I tried making that change, but to no success.
Another interesting thing to note is that sometimes this does work and sometimes it doesn't. This url is a case where it does not work. Here's one where it does: http://ecx.images-amazon.com/images/I/51mXQ-IjigL._SL160_.jpg
Why would Excel generate a macros it can't run? More importantly, how can I avoid this error and get on with my work!? Thanks!
Try this workaround:
Sub RetrieveImage()
Dim wsht As Worksheet: Set wsht = ThisWorkbook.ActiveSheet
wsht.Shapes.AddPicture "http://ecx.images-amazon.com/images/I/41u+ilIi00L._SL160_.jpg", _
msoFalse, msoTrue, 0, 0, 100, 100
End Sub
All fields are required, which is kind of a bummer since you cannot get the default size. The location offsets and sizes are in pixels/points. Also, the % turning to + is just alright, as % would cause it to be not recognized (dunno why).
Result:
Let us know if this helps.
I'm experiencing the same issue.
After some digging I found out Excel does a HTTP HEAD request before getting the image.
If this HEAD request is unsuccessful Excel will return the exact error messages mentioned in this discussion.
Your could easily test this using Fiddler.

Update PowerPoint pictures using VBA

My day to day work involves creating powerpoints for clients highlighting their campaign performance. Most of the charts have been linked to excel, which saves me a ton of time but I end up spending time updating the images in the powerpoint.
In order to preserve the size and postion of images, i use the change picture option when you right select the picture and paste in the link like this: https://fbcdn-sphotos-c-a.akamaihd.net/hphotos-ak-snc6/9943_10151547582895095_1006500471_n.jpg. All the links are ordered in excel which is given by the client.
I have already gone through a similar post here: Using VBA to insert/update image in PowerPoint?, but i was looking for a solution where the pictures get updated based on the links in excel. Any help here would be appreciated.
I found the answer at a different website. Posting it here in case anyone else is looking at solving the same challenge:
Sub recupererImageWeb_WinHttp()
'activate library : Microsoft WinHttp Services ,version 5.1
Dim b() As Byte
Dim h As Long
Dim oWinHttp1 As WinHttp.WinHttpRequest
Dim dex As String
dex = Worksheets("Sheet1").Cells(2, 11).Value
h = FreeFile
Open "C:\AAAA - Report\WWWWorkflow\cover.jpg" For Binary As #h
Set oWinHttp1 = New WinHttp.WinHttpRequest
oWinHttp1.Open "GET", _
dex, False
oWinHttp1.Send
oWinHttp1.WaitForResponse (30)
b() = oWinHttp1.ResponseBody
Set oWinHttp1 = Nothing
Put #h, 1, b()
Close #h
End Sub

Resources