VBA Code to reference unnamed workbooks

suresh ullanki

Board Regular
Joined
Apr 29, 2013
Messages
67
Hi,

I need to copy data from one workbook to another workbook. but macro will be run from third workbook. The following code is throwing an error saying subscript out of range. Can somebody help

Private Sub CommandButton1_Click() ' macro is run from command button from other workbook
Dim GetFile As Variant
MsgBox "Please select Source File and Target File"
GetFile = Application.GetOpenFilename(FileFilter:="Excel Files (*.xls), *.xls", Title:="Open The Workbook", MultiSelect:=True)
On Error Resume Next
If GetFile <> False Then
On Error GoTo 0
For j = 1 To UBound(GetFile)
Workbooks.Open Filename:=GetFile(j) 'two workbooks will be opened here,
Next j
End If
Dim lastrow As Long, wkb As Workbook, ws1 As Worksheet, ws2 As Worksheet 'Total three workbooks are present now
Dim i As Long
Set ws2 = ThisWorkbook.Sheets("Format") ' Target workbook
Set wkb = ActiveWorkbook ' Source Workbook,This Workbook name will be changing every month. Hence given active workbook
Set ws1 = wkb.Sheets("Headcount Reg")
Application.DisplayStatusBar = False
Application.Calculation = xlCalculationManual
Application.ScreenUpdating = False
Application.EnableEvents = False
lastrow = ws1.Range("A" & Rows.Count).End(xlUp).Row
For i = 1 To ws1.UsedRange.Columns.Count
Select Case i
Case Is <= 6
Range(ws1.Cells(2, i), ws1.Cells(lastrow, i)).Copy Destination:=ws2.Cells(2, i)
Case 8 To 14
Range(ws1.Cells(2, i), ws1.Cells(lastrow, i)).Copy Destination:=ws2.Cells(2, i - 1)
End Select
End Sub
 

Excel Facts

How to change case of text in Excel?
Use =UPPER() for upper case, =LOWER() for lower case, and =PROPER() for proper case. PROPER won't capitalize second c in Mccartney

Forum statistics

Threads
1,216,385
Messages
6,130,314
Members
449,572
Latest member
mayankshekhar

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top