Need some basic Excel/VBA coding help.

Status
Not open for further replies.

ChrisG

Ars Legatus Legionis
19,400
I'm not a programmer by any means and thus this might seem incredibly straightforward, but I need some suggestions to save myself several days of time. I have a set of plain text files containing anywhere up to 240 rows of 6 tab-delimited columns.

I want to randomly select 17 of these rows, copy & paste them out of the main block of columns, then delete the original columns leaving only the new random selection in the file.

I've manually iterated teh actions creating a script like this in Excel's VBA editor :


Sub Macro4()
'
' Macro4 Macro
'
' Keyboard Shortcut: Ctrl+Shift+K
'
Columns("A:B").Select
ActiveWindow.SmallScroll Down:=-3
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Range("A1").Select
ActiveCell.FormulaR1C1 = "=RAND()"
Range("A1").Select
Selection.AutoFill Destination:=Range("A1:A38"), Type:=xlFillDefault
Range("A1:A38").Select
ActiveWindow.SmallScroll Down:=12
Selection.AutoFill Destination:=Range("A1:A240"), Type:=xlFillDefault
Range("A1:A240").Select
ActiveWindow.SmallScroll Down:=-135
ActiveWindow.ScrollRow = 67
ActiveWindow.ScrollRow = 64
ActiveWindow.ScrollRow = 63
ActiveWindow.ScrollRow = 61
ActiveWindow.ScrollRow = 59
ActiveWindow.ScrollRow = 57
ActiveWindow.ScrollRow = 53
ActiveWindow.ScrollRow = 49
ActiveWindow.ScrollRow = 46
ActiveWindow.ScrollRow = 42
ActiveWindow.ScrollRow = 38
ActiveWindow.ScrollRow = 35
ActiveWindow.ScrollRow = 30
ActiveWindow.ScrollRow = 28
ActiveWindow.ScrollRow = 24
ActiveWindow.ScrollRow = 21
ActiveWindow.ScrollRow = 17
ActiveWindow.ScrollRow = 14
ActiveWindow.ScrollRow = 10
ActiveWindow.ScrollRow = 6
ActiveWindow.ScrollRow = 4
ActiveWindow.ScrollRow = 1
Cells.Select
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Clear
ActiveWindow.SmallScroll Down:=9
Selection.AutoFill Destination:=Range("A1:A44"), Type:=xlFillDefault
Range("A1:A44").Select
Cells.Select
Range("A10").Activate
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Clear
ActiveWindow.SmallScroll Down:=12
Selection.AutoFill Destination:=Range("A1:A40"), Type:=xlFillDefault
Range("A1:A40").Select
ActiveWindow.SmallScroll Down:=-18
Cells.Select
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Add Key:=Range("A1:A40") _
, SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("Sheet1").Sort
.SetRange Range("A1:H40")
.Header = xlGuess
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
Range("L20:M21").Select
Range("M21").Activate
End Sub

-My problem is the <ActiveWorkbook.Worksheets("Sheet1")> section. Obviously, this macro only acts on a worksheet called "Sheet1", and if it doesn't find it, it stalls.

What I need is for the macro to act on the only sheet in the file (there's only ever 1) no matter what that sheet is called.

Can anyone suggest what I need to do here to implement this ?
 

Mile Zero

Ars Praetorian
578
Subscriptor++
You can do this two ways. If you're going to be calling this from the macros menu, you could just use ActiveSheet to use the currently viewed worksheet. Or you can use numerical indexes in Workbook.Worksheets(N), where N is the index of your desired sheet, starting at 1.

Incidentally, I think you're going about this in a really complicated way. It would be a lot easier to simply set up a loop that picks a random index from Activesheet.Rows(), copies it to a second sheet or the bottom of the current sheet, do that 17 times, and then delete everything that's left over and move your 17 rows back up to the top. Something more like (untested, possibly bug-ridden code follows):

Code:
dim picked() as Integer
maxRow = 30 'Maximum number of rows in the sheet, set manually or programmatically
Randomize

for counter = 1 to 17
  randomRow = Int((maxRow * Rnd) + 1)
  for pickedIndex = 0 to UBound(picked)
    if picked(pickedIndex) = randomRow then
      counter = counter - 1
      goto cancel
    end if
  next pickedIndex
  activesheet.rows(randomRow).copy destination := activesheet.rows(maxRow + UBound(picked))
  redim preserve picked(UBound(picked) + 1)
  picked(UBound(picked)) = randomRow
  cancel:
next counter

'then delete everything under maxRow
 

calpan

Ars Scholae Palatinae
1,356
Subscriptor
If these really are plain text files with a .txt extension, the following Python script should take care of it:

Code:
import sys
import os
import os.path
from random import sample

if len(sys.argv) < 2:
    print >>sys.stderr, 'Usage: %s input_folder' % sys.argv[0]
    sys.exit(0)

folder = sys.argv[1]
filelist = [x for x in os.listdir(folder) if x.endswith('.txt')]
for fn in filelist:
    f = open(os.path.join(folder, fn))
    l = f.readlines()
    f.close()
    indices = sample(range(len(l)), 17)
    f = open(os.path.join(folder, fn), 'w')
    print >>f, ''.join([l[i] for i in indices])
    f.close()

If you already have python installed, save the script somewhere and run the following from the command line:
Code:
python [name of script you saved] [full path of folder containing input files]

On Windows, you may need to add the C:\Python27 folder to your path so the python executable can be found.
 
Status
Not open for further replies.