VBA formula from one workbook to another with named cells - vba

I can't get my formula to work. You can see that I am simply trying to subtract one value (there is a formula in the cells) from another from one workbook to another. What am I missing? It copies the formula in the correct cell but does not calculate. Results #NAME?.
Sub changeReports()
Dim currentWk As Worksheet
Dim prevYr As Worksheet
Dim prevWk As Worksheet
Dim File_Path As String
Dim Source_Workbook As Workbook
Dim Target_workbook As Workbook
File_Path = "B:\Operations\Aging 031416Wk11.xlsm"
Destination_Path = "B:\Operations\Aging 032116Wk12.xlsm"
Set Source_Workbook = Workbooks.Open(File_Path)
Set Target_workbook = Workbooks.Open(Destination_Path)
Set prevWk = Source_Workbook.Worksheets("2016 Reports")
Set currentWk = Target_workbook.Worksheets("2016 Reports")
currentWk.Activate
' code works to insert formula in cell but formula not working the way it is written
Range("chgBox").formula = "=currentWk.Range(""grBox"")- prevWk.Range(""grBox"")"
End Sub

If you want the result of the subtraction in the Range("chgBox") cell then performthe actual calculation.
Range("chgBox") = currentWk.Range("grBox") - prevWk.Range("grBox")
If you want the formula to remain in the Range("chgBox") cell then convert the VBA cell references to addresses and concatenate a string that will represent the worksheet formula.
Range("chgBox").Formula = "=" & currentWk.Range("grBox").Address(external:=true) & _
"-" & prevWk.Range("grBox").Address(external:=true)
You were getting the #NAME! error because the worksheet doesn't understand what currentWk.Range(""grBox"") is.
Addendum:
I've run through a full sample testing environment and both the formula and direct result work as provided above. I've cleaned up the remainder of the code below.
Option Explicit
Sub changeReports()
Dim currentWk As Worksheet
Dim prevWk As Worksheet
Dim filePath As String, destinationPath As String
Dim sourceWorkbook As Workbook, targetWorkbook As Workbook
filePath = "B:\Operations\Aging 031416Wk11.xlsm"
destinationPath = "B:\Operations\Aging 032116Wk12.xlsm"
filePath = Environ("TMP") & "\Aging 031416Wk11.xlsm"
destinationPath = Environ("TMP") & "\Aging 032116Wk12.xlsm"
Set sourceWorkbook = Workbooks.Open(filePath)
Set targetWorkbook = Workbooks.Open(destinationPath)
Set prevWk = sourceWorkbook.Worksheets("2016 Reports")
Set currentWk = targetWorkbook.Worksheets("2016 Reports")
With currentWk
.Range("chgBox") = .Range("grBox") - prevWk.Range("grBox")
'.Range("chgBox").Formula = "=" & currentWk.Range("grBox").Address & _
"-" & prevWk.Range("grBox").Address(external:=True)
End With
sourceWorkbook.Close savechanges:=False
targetWorkbook.Close savechanges:=True
End Sub

Related

Adding series from multiple workbooks

The following code is used to add a chart at the workbook that is opened. The chart data series values are taken from Worksheets(1) of every workbook inside "InputPathName" directory using a loop. Then I apply a template graph saved at "TemplatePath". Two problems arise:
Series Name will not have the value of cell B7. I tried 2 ways but did not work (marked as: ATTEMPT 1 & 2)
Some of the workbooks of directory "InputPathName" have more than one worksheet. If any worksheet other than worksheets(1) is active, I have a Run-time error '1004' Method 'Range' of object '_Worksheet' failed (highlighted line: Set xRange =...). If I add ws.Activate after Set ws=.... (as commented out), the graph will be a mess and won't show the correct results.
Note: If the active sheet in every workbook is worksheets(1), then the code works well.
DEVELOPING: How can I loop inside every worksheet of the workbooks without knowing the number of the worksheets?
Sub InputFromOtherWorksheets()
Dim ch As Chart
Dim ws As Worksheet
Dim wb As Workbook
Dim xRange As Range
Dim yRange As Range
Dim TemplatePath As String
Dim TemplateName As String
Dim InputPathName As String
Dim InputFileName As String
TemplatePath = "C:\Charts"
TemplateName = "templ4"
InputPathName = "C:\New folder\"
Set ch = Charts.Add2
InputFileName = Dir(InputPathName)
Do While InputFileName <> ""
Set wb = Workbooks.Open(InputPathName & InputFileName)
Set ws = wb.Worksheets(1)
'ws.Activate
Set xRange = ws.Range("B18", Range("B18").End(xlDown))
Set yRange = ws.Range("C18", Range("C18").End(xlDown))
With ch.SeriesCollection.NewSeries
.Name = ws.Range("B7") 'ATTEMPT 1
.XValues = xRange
.Values = yRange
End With
ch.SeriesCollection(1).Name = ws.Range("B7") 'ATTEMPT 2
wb.Close SaveChanges:=False
InputFileName = Dir()
Loop
ch.ApplyChartTemplate TemplatePath & "\" & TemplateName
ch.ChartTitle.Text = "Specimen 1"
End Sub
Try the code below:
With ch.SeriesCollection.NewSeries
.Name = "=" & ws.Range("B7").Address(False, False, xlA1, xlExternal)
' rest of your code
End With
To loop through every sheet of a workbook, you have to use Worksheets collection. Let's say we have set Workbook object in wb variable:
Dim ws As Worksheet
' some code
For Each ws in wb.Worksheets
' do some operations on ws object
Next

Excel VBA - Import from a closed Workbook in the same Folders

I'm trying to import some data from a closed workbook in the same folder into my active workbook. This is what i have so far
Sub Import_Data()
Dim rng As Range
Dim WB2 As Workbook
Dim FName As String
Dim c1 As Worksheet
Set c1 = Sheets("c")
FName = Application.ActiveWorkbook.Path + "\_w" & Format((WorksheetFunction.WeekNum(Now) - 1), "00")
Set WB2 = Workbooks.Open(Filename:=FName)
ThisWorkbook.ChampSpecific1.Range("L3:O6").Value = WB2.Worksheets(2).Range("M3:P6").Value
WB2.Close
End Sub
When I run the macro i get the error "Method or Data Member Not Found" highlights ThisWorkbook.C1.Range (The c1 Part). It should be pulling the Worksheet "c" shouldn't it?
Best Regards
Remove ThisWorkbook. from ThisWorkbook.ChampSpecific1.Range("L3:O6").Value and it should work. Like this:
ThisWorkbook.ChampSpecific1.Range("L3:O6")
The problem comes, because you have already pjut a set on ChampSpecific1 worksheet and it knows his Parent. Thus, if you try to refer a new Parent, it does not like it.
To get the Parent write the following Debug.Print ChampSpecific1.Parent.Name on the line before the error.
You don't need the ThisWorkbook qualifier as it's already set. Try this (using SourceSht and TargetSht to keep things from getting confusing:
Sub Import_Data()
Dim SourceSht As Worksheet
Dim TargetSht As Worksheet
Dim FName As String
FName = Application.ActiveWorkbook.Path + "\AIMS_Report_w" & Format((WorksheetFunction.WeekNum(Now) - 1), "00")
Set SourceSht = Workbooks.Open(Filename:=FName).Worksheets(2)
Set TargetSht = Sheets("Summary-Champion Specific")
TargetSht.Range("L3:O6").Value = SourceSht.Range("M3:P6").Value
End Sub

Setting wbkDest.worksheets("xxxxxxx") to Reflect a Range

I have a workbook that generates pages/page names. The worksheet name always reflects a job number. The job number is also always displayed in cell A1.
I want to copy data from another book, and paste it back into this worksheet, but I need to target the page I want to paste the data.
My issue is that I can't say wbkDest.Worksheets("sheet1").
I need to say something like wbk.Dest.Worksheets(Range("a1").value).
So again: Paste in the sheet with the same name as cell A1 in the workbook the macro is triggered from.
sub import()
Dim wbkSrc As Workbook, wbkDest As Workbook
Dim myFile As String
Dim Path As String
Dim emptyRow As Long
Dim wsOrig As Worksheet
Set wsOrig = ThisWorkbook.Worksheets(1)
emptyRow = 1
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Set wbkDest = Workbooks("lathe_project6-1-2017.xlsm")
Path = "G:\FIXTURES\" & Range("A1").Value & "\lists\new folder\"
myFile = Dir(Path & "*.xls??")
Set wbkSrc = Workbooks.Open(Path & myFile)
wbkSrc.Worksheets(1).Range("A1:I100").Copy
wbkDest.Worksheets(wsOrig.Range("A1").Value).Cells(emptyRow, 1).PasteSpecial Paste:=xlPasteValues
wbkSrc.Close
End Sub
This doesn't work:?
Dim wskVariableSheet as worksheet
Set wskVariableSheet = wbkDest.Sheets(Range("a1").Value)
And then just reference to wskVariableSheet.range where you want to paste.

VBA: Copy data from another workbook, based on cell value of current workbook

Currently I have a workbook that loops through workbooks in the same folder as it, end copies data from specific cells back to the master workbook. If I want to change to cells from where the code copies cells, I’ll have to change this value in the code.
However, I have co-workers who needs to use this sheet aswell, to collect data from other workbooks. – So I need to make this use friendly.
What I want to do, is to have the code read a cell value in the masterworkbook, and use this cell value as the cell that it copies from.
Example:
If I type “B3” in the masterworkbook cell A1 and run the macro, the macro will copy data from the originsheet B3, into the first cell of the masterworkbook. Does anyone have any idear how to accomplish this?
Or something like:
.Cells(1).Value = originsheet.Range(Range("CellValue from destinationsheet A1").Value).Value
Here is the code I use:
Sub Consolidate()
Dim wkbkorigin As Workbook
Dim originsheet As Worksheet
Dim destsheet As Worksheet
Dim ResultRow As Long
Dim Fname As String
Dim RngDest As Range
Set destsheet = ThisWorkbook.Worksheets("Sheet1")
Set RngDest = destsheet.Cells(Rows.Count, 1).End(xlUp) _
.Offset(1, 0).EntireRow
Fname = Dir(ThisWorkbook.Path & "/*.xlsx")
'loop through each file in folder (excluding this one)
Do While Fname <> "" And Fname <> ThisWorkbook.Name
If Fname <> ThisWorkbook.Name Then
Set wkbkorigin = Workbooks.Open(ThisWorkbook.Path & "/" & Fname)
Set originsheet = wkbkorigin.Worksheets(1)
With RngDest
.Cells(1).Value = originsheet.Range(Range("A1").Value).Value
.Cells(2).Value = originsheet.Range(Range("A2").Value).Value
.Cells(3).Value = originsheet.Range(Range("A3").Value).Value
.Cells(4).Value = originsheet.Range(Range("A4").Value).Value
.Cells(5).Value = originsheet.Range(Range("A5").Value).Value
End With
wkbkorigin.Close SaveChanges:=False 'close current file
Set RngDest = RngDest.Offset(1, 0)
End If
Fname = Dir() 'get next file
Loop
End Sub
And a picture of what i mean, in case im unclear:
enter image description here
I am sorry, but I believe you haven't made yourself clear. However, you may be trying to get something like this (correct me if I'm wrong):
destinationsheet.Range("A1") = originsheet.Range(destinationsheet.Range("A1"))
This will make the value in your Master Workbook be substituted by the content in cell address of the other worksheet.

select all non-blank rows and cells using VBA

I'm new to VBA and I've been trying to figure out how to open an input file and copy those contents to a hidden sheet on my workbook, I saw an example on how to do this but the number of rows and columns is static, and I have to use 3 different input files one of them that changes constantly so, although I've been trying to use my intuition on how to do this, I can't seem to find out the answer.
Here's it is:
Sub s()
' Get customer workbook...
Dim customerBook As Workbook
Dim filter As String
Dim caption As String
Dim customerFilename As String
Dim customerWorkbook As Workbook
Dim targetWorkbook As Workbook
' make weak assumption that active workbook is the target
Set targetWorkbook = Application.ActiveWorkbook
' get the customer workbook
filter = "Text files (*.xlsx),*.xlsx"
caption = "Please Select an input file "
customerFilename = Application.GetOpenFilename(filter, , caption)
Set customerWorkbook = Application.Workbooks.Open(customerFilename)
' copy data from customer to target workbook
Dim targetSheet As Worksheet
Set targetSheet = targetWorkbook.Worksheets(1)
Dim sourceSheet As Worksheet
Set sourceSheet = customerWorkbook.Worksheets(1)
Dim lastRow As Long
lastRow = sourceSheet.Range("A" & Rows.Count).End(xlUp).Row
Dim lastColumn As Long
lastColumn = sourceSheet.Cells(1, Columns.Count).End(xlToLeft).Column
targetSheet.Range("A1:A" & lastRow).Value = sourceSheet.Range("A1:A" & lastRow).Value
' Close customer workbook
customerWorkbook.Close
End Sub
I'm using EXCEL 2007
I apologize in advance if this is an stupid noob question, but I honestly give up don't know what else to do to make it work.
The problem Is I don't know how to make it select first to last row and first to last cell (non blank both: cells and rows)
Tried this:
targetSheet.Range("A1:A" & lastRow).End(xlUp).Value = sourceSheet.Range("A1:A" & lastRow).End(xlUp).Value
and this targetSheet.Range("A1:A" & lastRow).End(xlRight).Value = sourceSheet.Range("A1:A" & lastRow).End(xlRight).Value
What about something like this:
SourceSheet.UsedRange.Copy TargetSheet.Range("A1")