How to extract worksheet name in VBA? - excel

I have a script that rips some data for me from a certain tab in multiple excel workbooks.
I am wondering how can I add to that to extract the workbook name for each workbook it goes through
This is what I am using:
Dim fPath As String
Dim iSheet As String
Dim oSheet As String
Dim BMsheet As String
Dim country, bas, play As String
Dim fileNames As Range
Dim file As Range
Dim oWorkbook As Excel.Workbook ' outlook workbook
Dim MyRange As Range
iSheet = "INPUT"
oSheet = "Data"
BMsheet = "Potential Discovery Phasing"
Dim fHandle As New FileSystemObject
ThisWorkbook.Worksheets(iSheet).Activate
Set fileNames = Range("files")
ThisWorkbook.Worksheets(oSheet).Activate
Range("start").Activate
On Error GoTo NotFound:
For Each file In fileNames.Cells
If fHandle.FileExists(file.Value) Then
Set oWorkbook = Workbooks.Open(file.Value, False, True)
'extract columns
''''''''''''''''''''''''''''''''''''''''''''''''
'
''''''''''''''''''''''''''''''''''''''''''''''''
oWorkbook.Worksheets(BMsheet).Select
If ActiveSheet.AutoFilterMode = True Then ActiveSheet.AutoFilterMode = False
Range("A6").Select
ActiveCell.Offset(1, 0).Select
Set MyRange = Range(ActiveCell, ActiveCell.Offset(32, 7))
MyRange.Select
Range(Selection, Selection.End(xlDown)).Select
Selection.Copy
ThisWorkbook.Activate
ThisWorkbook.Worksheets(oSheet).Select
Selection.PasteSpecial xlValues
'While ActiveCell.Value <> ""
'ActiveCell.Offset(0, -1).Value = file.Offset(0, -2).Value
ActiveCell.Offset(33, 0).Activate
'Wend
Application.CutCopyMode = False
oWorkbook.Close SaveChanges:=False
ActiveCell.Select
file.Offset(0, 1).Value = "Yes"
Else
file.Offset(0, 1).Value = "No"
End If
Skip: Next file
Exit Sub
NotFound:
GoTo Skip
End Sub
I am fairly new to VBA so excuse my lack of knowledge
Cheers

dim sheet as worksheet
dim wb as workbook
set wb = thisworkbook
for each sheet in wb.Sheets
debug.print; sheet.Name
next sheet
Because we're nerds and want to check things:
Private Sub this()
For i = 0 To 99
Debug.Print i;
'prints to the same line
Next i
For i = 0 To 99
Debug.Print ; i
prints to next line
Next i
End Sub

Related

Consolidate Worksheet from a Folder and Append by Column

I have to compile all the worksheets in a folder and append it by column (in addition to labelling the file name).
All of the worksheets are expected to have the following dimensions.
I am expected to provide the following outcome (to be able to merge the file name is a bonus):
Sub macro1()
'Define variables
Dim wbk As Workbook
Dim Filename As String
Dim Path As String
i = 3
ThisWorkbook.Activate
'Location of individual templates
Path = "filename\"
Filename = Dir(Path & "*.xlsx")
'Prevents screen from flickering when Macro is running
Application.ScreenUpdating = False
'Start of loop
Do While Len(Filename) > 0
'Opens excel file
Set wbk = Workbooks.Open(Path & Filename)
'Copies the file names
Sheets("1.Consol").Select
Range("C3:E3").Select
ActiveCell.Value = Replace(Filename, ".xlsx", "")
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues
'Labelling low
Range("C4").Select
ActiveCell.Value = "Low"
Range("C4").Select
Selection.Copy
Selection.PasteSpecial xlPasteValues
'Labelling Medium
Range("D4").Select
ActiveCell.Value = "Medium"
Range("D4").Select
Selection.Copy
Selection.PasteSpecial xlPasteValues
'Labelling High
Range("E4").Select
ActiveCell.Value = "High"
Range("E4").Select
Selection.Copy
Selection.PasteSpecial xlPasteValues
'Copies the whole range of data
Range("C3:E100").Copy
'Change to the sheet name you want to paste to
ThisWorkbook.Activate
Sheets("1.Consol").Select
Cells(3, i).Select
ActiveSheet.Paste
Selection.EntireColumn.ColumnWidth = 10
Selection.EntireRow.AutoFit
i = i + 3
Application.DisplayAlerts = False
wbk.Saved = True
wbk.Close True
Filename = Dir
Loop
End Sub
Based on this set up (see the location of data)
Source files:
Consolidated file:
Step through the code pressing F8 key
Read code's comments and adjust it to fit your needs
Public Sub OpenFilesAndCopyContents()
' Basic error handling
On Error GoTo CleanFail
' Turn off stuff
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
ThisWorkbook.UpdateLinks = xlUpdateLinksNever
' Define files path
Dim filesPath As String
filesPath = "C:\Temp\Test\"
' Define and set target sheet
Dim targetSheet As Worksheet
Set targetSheet = ThisWorkbook.Worksheets("1.Consol")
' Define initial cell in target sheet
Dim targetRange As Range
Set targetRange = targetSheet.Range("B1")
' Define file name string to match
Dim fileString As String
fileString = "samplefile"
' Define file name
Dim fileName As String
fileName = Dir(filesPath, vbNormal)
' Start a counter for worksheets
Dim sheetCounter As Long
' Loop through files
Do While fileName <> ""
'Set variable equal to opened workbook
If InStr(LCase(fileName), LCase(fileString)) > 0 Then
' Set a reference to the workbook
Dim sourceWorkbook As Workbook
Set sourceWorkbook = Workbooks.Open(fileName:=filesPath & fileName, UpdateLinks:=False)
'Ensure Workbook has opened before moving on to next line of code
DoEvents
' Loop through sheets in workbook
Dim sourceSheet As Worksheet
For Each sourceSheet In sourceWorkbook.Worksheets
' Add workbook and worksheet as title
targetRange.Offset(0, sheetCounter).Value = sourceWorkbook.Name & " " & sourceSheet.Name
' Copy paste values from worksheet
sourceSheet.Range("B1:D8").Copy targetRange.Offset(1, sheetCounter)
sheetCounter = sheetCounter + 3
Next sourceSheet
'Close Workbook without saving
sourceWorkbook.Close SaveChanges:=False
'Ensure Workbook has closed before moving on to next line of code
DoEvents
End If
fileName = Dir()
Loop
CleanExit:
' Turn on stuff
Application.ScreenUpdating = True
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
ThisWorkbook.UpdateLinks = xlUpdateLinksAlways
Exit Sub
CleanFail:
MsgBox "Error " & Err.Description
GoTo CleanExit
End Sub
Let me know if it works

Optimize Excel VBA Macro for Copy-PasteValues

I'm new in Excel-VBA and I need to improve my macro performance. I have a macro that searches an excel, opens it, then goes through every sheet and copy-pastevalues for all cell with a specific color (yellow). Finally saves and closes the excel. In addition, excels sheets are locked and only those yellow cells are editable. This should be done for a list of excel that I indicate in a main template from where I call the macro. The problem is that it takes a lot of time and even gets blocked when the number of excels is more than 3.
I paste my code below and hope anyone can help. Thanks!
Sub Button1_Click()
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Dim filePath As String
Dim rng As Range
Dim cel As Range
Dim cartera As String
Dim plantilla As String
Dim wb As Workbook
Dim ws As Worksheet
Dim obj_Cell As Range
filePath = Application.ThisWorkbook.Path
Range("B9").Select
Set rng = Application.Range(Selection, Selection.End(xlDown))
For Each cel In rng.Cells
cartera = cel.Value
plantilla = cel.Offset(0, 1).Value
If cartera = vbNullString Or plantilla = vbNullString Then
GoTo Saltar
End If
Application.StatusBar = "Ejecutando Cartera: " & cartera & ", Plantilla: " & plantilla
Set wb = Workbooks.Open(filePath & "\" & cartera & "\" & plantilla, UpdateLinks:=3)
For Each ws In wb.Worksheets
If ws.Name <> "Index" And ws.Name <> "Instructions" And ws.Name <> "Glossary" Then
Worksheets(ws.Name).Activate
For Each obj_Cell In Range("A1:DW105")
With obj_Cell
If obj_Cell.Interior.Color = RGB(255, 255, 153) Then
obj_Cell.Select
If obj_Cell.MergeCells = True Then
obj_Cell.MergeArea.Select
End If
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=True, Transpose:=False
If obj_Cell.MergeCells = True Then
If obj_Cell.MergeArea(1).Value = vbNullString Then
obj_Cell.MergeArea.Cells(1, 1).Select
Selection.ClearContents
End If
Else
If obj_Cell.Value = vbNullString Then
obj_Cell.ClearContents
End If
End If
End If
End With
Next obj_Cell
Range("A1").Select
End If
Next ws
Sheets(1).Select
wb.Close SaveChanges:=True
Saltar:
Next cel
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Application.StatusBar = False
End Sub
Untested- just some "start" ideas for you to use (e.g. no selections, using arrays, fix With statement, no GoTo). I don't understand the logic behind clearing vbNullstring. If it is necessary adapt the code in your way.
I would also suggest opening files with displayalerts on because of few potential problems (e.g. "serious error occur last time file was opened" would hangs your macro)
Sub Button1_Click()
With Application
.ScreenUpdating = False
.StatusBar = True
End With
' If possible change this reference
' from active sheet to sheet's name/codename/index
Dim activeWs As Worksheet
Set activeWs = ActiveSheet
Dim filePath As String
filePath = Application.ThisWorkbook.Path
Dim wb As Workbook
Dim ws As Worksheet
Dim obj_Cell As Range
' range definition
' if lastRow not working change to yours xlDown
' if possible End(xlUp) method is more reliable
Dim rng As Range
Dim lastRw As Long
With activeWs
lastRw = .Cells(.Cells.Rows.Count, "B").End(xlUp).Row
Set rng = .Range("B9:B" & lastRw)
End With
' read whole ranges at once
' instead of offset it is possible also to read
' cartera and plantilla at the same time to 2Darray
Dim cartera As Variant
cartera = Application.Transpose(rng.Value2)
Dim plantilla As Variant
plantilla = Application.Transpose(rng.Offset(, 1).Value2)
' main loop
Dim i As Long
For i = 1 To UBound(cartera)
If cartera(i) <> vbNullString Or plantilla(i) <> vbNullString Then
Application.StatusBar = "Ejecutando Cartera: " & cartera(i) & ", Plantilla: " & plantilla(i)
Set wb = Workbooks.Open(filePath & "\" & cartera(i) & "\" & plantilla(i), UpdateLinks:=3)
For Each ws In wb.Worksheets
If ws.Name <> "Index" And ws.Name <> "Instructions" And ws.Name <> "Glossary" Then
For Each obj_Cell In ws.Range("A1:DW105")
With obj_Cell
If .Interior.Color = RGB(255, 255, 153) Then
.Value2 = .Value2
' I commented this part beacuse it does not make sense for me...
' If .MergeCells Then
' If .MergeArea(1).Value = vbNullString Then _
.MergeArea.Cells(1, 1).ClearContents
' Else
' If .Value = vbNullString Then .ClearContents
' End If
End If
End With
Next obj_Cell
End If
Next ws
' I would place diplayalerts off here because of potential problems
' with opening files
' if problem occurs it can macro hangs
Application.DisplayAlerts = False
wb.Close SaveChanges:=True
Application.DisplayAlerts = True
End If
Next i
With Application
.ScreenUpdating = True
.DisplayAlerts = True
.StatusBar = False
End With
End Sub

Is there a way to skip error "filename is not found" and move to the next file

Is there a way to skip error "filename is not found" and move to the next file?
Sub CopyDataAndMoveDown()
Application.ScreenUpdating = False
Dim wb As Workbook: Set wb = ThisWorkbook
Dim ws As Worksheet: Set ws = wb.ActiveSheet
Dim rngToCopy As Range, rngToPaste As Range
Dim x As Long
Dim breakdown1
Dim breakdown As Worksheet: Set breakdown = wb.ActiveSheet
For x = 4 To 504 Step 6
With wb.Sheets("Sheet1")
breakdown1 = breakdown.Cells(9, x - 2)
End With
If IsEmpty(breakdown1) Then
Call MoveBelow
Else
With wb.Sheets("Sheet1")
Set rngToCopy = .Range(.Cells(4, x - 2), .Cells(24, x + 3))
Debug.Print rngToCopy.Address
End With
With wb.Sheets("Sheet2")
Set rngToPaste = .Range(.Cells(4, x - 2), .Cells(rngToCopy.Rows.Count + 3, x + 3))
Debug.Print rngToPaste.Address
End With
rngToPaste = rngToCopy.Value
End If
Next x
Application.ScreenUpdating = True
MsgBox "Valmis."
End Sub
Sub MoveBelow ()
Application.ScreenUpdating = False
Dim wb As Workbook: Set wb = ThisWorkbook
Dim ws As Worksheet: Set ws = wb.ActiveSheet
Dim rngToCopy As Range, rngToPaste As Range
Dim x As Long
Dim breakdown1
Dim breakdown As Worksheet: Set breakdown = wb.ActiveSheet
For x = 4 To 504 Step 6
With wb.Sheets("Sheet1")
breakdown1 = breakdown.Cells(9, x - 2)
End With
If IsEmpty(breakdown1) Then
' At this point when the macro meet again a empty cell
' it should keep moving from the same counted X
' but start the paste operation from 24 rows below.
Else
With wb.Sheets("Sheet1")
Set rngToCopy = .Range(.Cells(4, x - 2), .Cells(24, x + 3))
Debug.Print rngToCopy.Address
End With
With wb.Sheets("Sheet2")
Set rngToPaste = .Range(.Cells(28, x - 2), .Cells(rngToCopy.Rows.Count + 3, x + 3))
Debug.Print rngToPaste.Address
End With
rngToPaste = rngToCopy.Value
End If
Next x
Application.ScreenUpdating = True
MsgBox "Valmis."
End Sub
So when the macro is copying / pasting data from Sheet 1 to Sheet 2 and meets an empty cell it should keep going, copying next available data, but paste it 24 rows below.
--------Below the old question.
I have a VBA which is opening and closing file for that INDEX function get data. My problem is that. VBA is getting the filename from reference cell which contain the full path. But some of the reference cells are blanks/zeros and then the running VBA stops and give me error "filename is not found". Is there a way to skip that and move to next step?
Sub HaeReseptiTiedot()
Dim myfile As String
Dim myfile1 As String
Dim myfile2 As String
Dim myfile3 As String
Dim myfile4 As String
Dim myfile5 As String
Dim myfile6 As String
Dim myfile7 As String
Dim myfile8 As String
Dim myfile9 As String
myfile = Cells(19, 4).Value
myfile1 = Cells(19, 9).Value
myfile2 = Cells(19, 14).Value
myfile3 = Cells(19, 19).Value
myfile4 = Cells(19, 24).Value
myfile5 = Cells(19, 29).Value
myfile6 = Cells(19, 34).Value
myfile7 = Cells(19, 39).Value
myfile8 = Cells(19, 44).Value
myfile9 = Cells(19, 49).Value
Application.ScreenUpdating = False
Workbooks.Open Filename:=myfile, UpdateLinks:=0
ActiveWorkbook.Close False
Sheets("Aputaulukko 2").Select
Range("D16:G30").Select
Selection.Copy
Sheets("Aputaulukko 3").Select
Range("B4").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
Workbooks.Open Filename:=myfile1, UpdateLinks:=0
ActiveWorkbook.Close False
Sheets("Aputaulukko 2").Select
Range("I16:L30").Select
Application.CutCopyMode = False
Selection.Copy
Sheets("Aputaulukko 3").Select
Range("G4").Select
Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
:=False, Transpose:=False
The best way I have found to handle this is to use the "On Error" statement. You can keep it really simple and use On Error Resume Next, which tells the code to skip the error entirely and move to the next statement (that does not have an error). The main issue with this is that it covers ALL errors, not just the specific one you are having issues with currently. It can make it hard to know if errors are occurring/if your code is functioning as you expect.
The other option, which can help avoid the issues mentioned above, is to use something like this:
On Error GoTo ErrH
'Main Body of Your Code
Exit Sub 'Use to avoid continuing on to the ErrH section.
ErrH:
'Some method for handling the error, such as a message box or other notification.
This usually isn't necessary with small chunks of code, but when you start combining your subs and functions it can be a life saver!
Good Luck!
Edit: You could/should also consider removing those blanks if they are not necessary for the sheet to work.
Here is a function that can check if a file exists:
'********************************************************************************************************************************
' To check if a particular file exists
' Set excelFile = False, if it is not an Excel file that is being checked
'********************************************************************************************************************************
Public Function isAnExistingFile(ByVal fileNameStr As Variant, Optional ByVal excelFile As Boolean = True) As Boolean
Dim wb As Workbook
isAnExistingFile = True
Err.Clear
On Error GoTo errHandler
If Not VarType(fileNameStr) = vbString Then
isAnExistingFile = False
ElseIf Len(fileNameStr) = 0 Then
isAnExistingFile = False
ElseIf Len(Dir(fileNameStr)) = 0 Then
isAnExistingFile = False
ElseIf ((GetAttr(fileNameStr) And vbDirectory) <> vbDirectory) = False Then
isAnExistingFile = False
Else
If excelFile Then
On Error Resume Next
Set wb = Application.Workbooks.Open(Filename:=fileNameStr, UpdateLinks:=0, ReadOnly:=True)
If wb Is Nothing Then isAnExistingFile = False
If Not wb Is Nothing Then
wb.Close False
Set wb = Nothing
End If
GoTo Out
End If
End If
errHandler:
If Not Err.Number = 0 Then isAnExistingFile = False
Out:
Err.Clear: On Error GoTo 0
End Function
I took the liberty to rewrite your code... i'm still not quite sure why you are openning and closing the workbook immediately, but in essence this is what your code does at the moment:
Option Explicit
Sub HaeReseptiTiedot()
Application.ScreenUpdating = False
Dim wbSource As Workbook
Dim wb As Workbook: Set wb = ThisWorkbook 'Or ActiveWorkbook or Workbooks("book name")
Dim ws As Worksheet: Set ws = wb.ActiveSheet 'Or wb.Sheets("Sheet Name")
Dim rngToCopy As Range, rngToPaste As Range
Dim X As Long
For X = 4 To 49 Step 5
On Error Resume Next
Set wbSource = Workbooks.Open(FileName:=ws.Cells(19, X), UpdateLinks:=0)
On Error GoTo 0
If Not wbSource Is Nothing Then
wbSource.Close False
With wb.Sheets("Aputaulukko 2")
Set rngToCopy = .Range(.Cells(16, X), .Cells(30, X + 3))
'Debug.Print rngToCopy.Address
End With
With wb.Sheets("Aputaulukko 3")
Set rngToPaste = .Range(.Cells(4, X - 2), .Cells(rngToCopy.Rows.Count + 3, X + 1))
'Debug.Print rngToPaste.Address
End With
rngToPaste = rngToCopy.Value
End If
Set wbSource = Nothing
Next X
Application.ScreenUpdating = True
End Sub
You could work around this by creating a second Sub that opens the file and handles the error if the file doesn't exist. That way you are still able to catch other Errors in the main Sub without going to next. Example:
Sub MainSub()
myFile1 = "C:\Temp\New1.xlsx"
myFile2 = "C:\Temp\New2.xlsx"
CheckAndOpen (myFile1)
CheckAndOpen (myFile2)
End Sub
Sub CheckAndOpen(myFileName As String)
On Error Resume Next
Workbooks.Open Filename:=myFileName
Debug.Print Err.Number, myFileName
End Sub
You could, alternatively, just put the following in your code:
If dir("FILENAME") <> "" Then
Add the rest of your code
End If
I usually run 3 or 4 for loops inside of each other with different variables to get the full path of each file, then put this to ensure I do not open files where there are blanks.

Change ActiveCell to update a worksheet with data from various workbooks

I have multiple workbooks with invoice information laid out in an invoice format.
I need to extract various pieces of data and compile a worksheet that can be imported into another software.
Here is the code I have written:
Sub GetFile()
Dim fNameAndPath As Variant
Dim wbdata As Workbook
Dim wbsource As Workbook
Dim ShToCopy As Worksheet
Dim rangedata As Range
'set data workbook
Set wbdata = ThisWorkbook
Set rangedata = ActiveCell
'open other workbook and set as source workbook
fNameAndPath = Application.GetOpenFilename
If fNameAndPath = False Then Exit Sub
Set wbsource = Workbooks.Open(fNameAndPath)
Set ShToCopy = wbsource.Worksheets("PCO #")
Call Extract_Invoice_Data_1(wbdata, wbsource, ShToCopy, rangedata)
Call Extract_Invoice_Data_2(wbdata, wbsource, ShToCopy)
Call Extract_Invoice_Data_3(wbdata, wbsource, ShToCopy)
Call Extract_Invoice_Data_4(wbdata, wbsource, ShToCopy)
Call Extract_Invoice_Data_5(wbdata, wbsource, ShToCopy)
Call Extract_Invoice_Data_6(wbdata, wbsource, ShToCopy)
Call Extract_Invoice_Data_7(wbdata, wbsource, ShToCopy)
Call Extract_Invoice_Data_8(wbdata, wbsource, ShToCopy)
Call Extract_Invoice_Data_9(wbdata, wbsource, ShToCopy)
Call Extract_Invoice_Data_10(wbdata, wbsource, ShToCopy)
Call Extract_Invoice_Data_11(wbdata, wbsource, ShToCopy)
wbsource.Close SaveChanges:=False
Set wbsource = Nothing
End Sub
Sub Extract_Invoice_Data_1(wbdata As Workbook, wbsource As Workbook,
ShToCopy As Worksheet, rangedata As Range)
rangedata.Value = ShToCopy.Range("G5").Value
ActiveCell.Offset(0, 1).Activate
End Sub
Sub Extract_Invoice_Data_2(wbdata As Workbook, wbsource As Workbook,
ShToCopy As Worksheet)
Set rangedata = ActiveCell
rangedata.Value = ShToCopy.Range("G4").Value
ActiveCell.Offset(0, 1).Activate
End Sub
Sub Extract_Invoice_Data_3(wbdata As Workbook, wbsource As Workbook,
ShToCopy As Worksheet)
Set rangedata = ActiveCell
rangedata.Value = ShToCopy.Range("C3").Value
ActiveCell.Offset(0, 1).Activate
End Sub
Sub Extract_Invoice_Data_4(wbdata As Workbook, wbsource As Workbook,
ShToCopy As Worksheet)
Set rangedata = ActiveCell
rangedata.Value = ShToCopy.Range("C4").Value
ActiveCell.Offset(0, 1).Activate
End Sub
Sub Extract_Invoice_Data_5(wbdata As Workbook, wbsource As Workbook,
ShToCopy As Worksheet)
Set rangedata = ActiveCell
rangedata.Value = ShToCopy.Range("C5").Value
ActiveCell.Offset(0, 1).Activate
End Sub
Sub Extract_Invoice_Data_6(wbdata As Workbook, wbsource As Workbook,
ShToCopy As Worksheet)
Set rangedata = ActiveCell
rangedata.Value = ShToCopy.Range("C6").Value
ActiveCell.Offset(0, 1).Activate
End Sub
Sub Extract_Invoice_Data_7(wbdata As Workbook, wbsource As Workbook,
ShToCopy As Worksheet)
Set rangedata = ActiveCell
rangedata.Value = ShToCopy.Range("G32").Value
ActiveCell.Offset(0, 1).Activate
End Sub
Sub Extract_Invoice_Data_8(wbdata As Workbook, wbsource As Workbook,
ShToCopy As Worksheet)
Set rangedata = ActiveCell
rangedata.Value = ShToCopy.Range("G25").Value
ActiveCell.Offset(0, 1).Activate
End Sub
Sub Extract_Invoice_Data_9(wbdata As Workbook, wbsource As Workbook,
ShToCopy As Worksheet)
Set rangedata = ActiveCell
rangedata.Value = ShToCopy.Range("G28").Value
ActiveCell.Offset(0, 1).Activate
ActiveCell = "=RC[-1]*0.15"
ActiveCell.Offset(0, 1).Activate
End Sub
Sub Extract_Invoice_Data_10(wbdata As Workbook, wbsource As Workbook,
ShToCopy As Worksheet)
Set rangedata = ActiveCell
rangedata.Value = ShToCopy.Range("G21").Value
ActiveCell.Offset(0, 1).Activate
End Sub
Sub Extract_Invoice_Data_11(wbdata As Workbook, wbsource As Workbook,
ShToCopy As Worksheet)
Set rangedata = ActiveCell
rangedata.Value = ShToCopy.Range("G22").Value
ActiveCell.Offset(0, 1).Activate
ActiveCell = "=RC[-1]*0.15"
ActiveCell.Offset(0, 1).Activate
ActiveCell = "=SUM(RC[-4]:RC[-1])"
ActiveCell.Offset(0, 1).Activate
End Sub
The problem is I can't change ActiveCell. It will enter the data in the first cell of the worksheet and then not extract any of the other data.
Note: I am attempting to execute this on a Mac.
Untested but you see how this can work without using ActiveCell/Activate etc:
Sub ChooseInputFileAndExtractData()
Dim fNameAndPath As Variant
Dim wbsource As Workbook
Dim destRow As Range
Set destRow = ActiveCell.EntireRow 'get the selected Row
'open other workbook and set as source workbook
fNameAndPath = Application.GetOpenFilename
If fNameAndPath <> False Then
Set wbsource = Workbooks.Open(fNameAndPath)
ExtractInvoiceData destRow, wbsource.Worksheets("PCO #")
wbsource.Close SaveChanges:=False
Set wbsource = Nothing
End If
End Sub
Sub ExtractInvoiceData(destRow As Range, SourceSheet As Worksheet)
With destRow
.Cells(1).Value = SourceSheet.Range("G5").Value
.Cells(2).Value = SourceSheet.Range("G4").Value
.Cells(3).Value = SourceSheet.Range("C3").Value
.Cells(4).Value = SourceSheet.Range("C4").Value
.Cells(5).Value = SourceSheet.Range("C5").Value
.Cells(6).Value = SourceSheet.Range("C6").Value
.Cells(7).Value = SourceSheet.Range("G32").Value
.Cells(8).Value = SourceSheet.Range("G25").Value
.Cells(9).Value = SourceSheet.Range("G28").Value
.Cells(10).FormulaR1C1 = "=RC[-1]*0.15" '
'etc etc you get the idea
End With
End Sub

Excel VBA: Transpose data from columns in one Workbook to rows in another workbook

I am new to VBA.
Transposing data from columns in one Workbook to another as rows is throwing errors. Tried suggestions from Stack Overflow and elsewhere but no success.
Error Runtime Error 1004 -> PasteSpecial method of Range class failed
Code:
Sub Button1_Click()
Dim MyFile As String
Dim erow
Dim FilePath As String
FilePath = "C:\trial\"
MyFile = Dir(FilePath)
Do While Len(MyFile) > 0
If MyFile = "here.xlsm" Then
Exit Sub
End If
'Opening data.xls to pull data from one column with 2 values (E6 and E7)
Workbooks.Open (FilePath & MyFile), Editable:=True
Dim SourceRange As Range
Set SourceRange = ActiveSheet.Range("E6:E7")
SourceRange.Copy
ActiveWorkbook.Close SaveChanges:=True
'Back to calling file - here.xlsm and pasting both values in single row (for e.g. A2 and B2)
erow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row
Dim targetRange As Range
Set targetRange = ActiveSheet.Cells(erow, 1)
targetRange.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=True
MyFile = Dir
Loop
End Sub
It is because you cannot do both values only and transpose at the same time.
Try this:
Sub Button1_Click()
Dim MyFile As String
Dim erow
Dim FilePath As String
Dim swb As Workbook
Dim twb As Workbook
Set twb = ThisWorkbook
FilePath = "C:\trial\"
MyFile = Dir(FilePath)
Do While Len(MyFile) > 0
If MyFile = "here.xlsm" Then
Exit Sub
End If
'Change "Sheet1" below to the actual name of the sheet
erow = twb.Sheets("Sheet1").Cells(twb.Sheets("Sheet1").Rows.Count, 1).End(xlUp).Offset(1, 0).Row
'Opening data.xls to pull data from one column with 2 values (E6 and E7)
Set swb = Workbooks.Open(FilePath & MyFile)
'assign values
twb.Sheets("Sheet1").Cells(erow, 1).Resize(, 2).Value = Application.Transpose(swb.ActiveSheet.Range("E6:E7").Value)
'close
swb.Close SaveChanges:=True
MyFile = Dir
Loop
End Sub
This seems to work:
Its a simpler example that does same thing
copy/paste method applies only to active objects (like, sheets, ranges, etc)
so you need to activate one, then the other,
Sub tst1()
Dim inbook, outbook As Workbook
Dim inSheet, outSheet As Worksheet
Dim inRange, outRange As Range
Set inbook = Application.Workbooks("temp1.xlsx")
Set outbook = Application.Workbooks("temp2.xlsx")
Set inSheet = inbook.Worksheets("sheet1")
Set outSheet = outbook.Worksheets("sheet1")
inSheet.Activate
Set inRange = ActiveSheet.Range("a1:b4")
inRange.Copy
outSheet.Activate
Set outRange = ActiveSheet.Range("a1:d2")
outRange.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=True
End Sub

Resources