VBA - Variable sheet name in sumif formula - vba

I'm trying to use SUMIF formula in VBA, based on a sheet that can have diferent names.
When I'm on this ActiveSheet (can vary), I want to add another sheet template from another workbook Template_test and put a SUMIF formula referenced to the activesheet.
When I run the macro, error occurs (1004) and stops at the formula.
This is what I have:
Sub test()
Set CurBook = ThisWorkbook
Dim wksheet As Worksheet
Set wksheet = ActiveSheet
MsgBox CurBook.Name & "_" & wksheet.Name
'Open template
Workbooks.Open filename:= _
"D:\Template_test.xlsm"
'Copy new sheet
Sheets("template").Select
Sheets("template").Copy After:=CurBook.ActiveSheet
'Close Template file
Windows("Template_test.xlsm").Activate
ActiveWindow.Close
'SUMIF Formula in Template regarding wksheet in CurBook
Range("E11").Select
ActiveCell.FormulaR1C1 = _
"=SUMIF('& wksheet &!C2,""=P-SEC"",'& wksheet &!C16)" End Sub
Is there a way to solve this and make it work?

I see two issues here:
i) wksheet is an object of type 'WorkSheet' and not a string, so you can't use it as a string.
ii) wksheet is available in the code, but not in the worksheet, so when you paste the function into the cell, you need to exit the string and append the name.
Try this:
ActiveCell.FormulaR1C1 = _
"=SUMIF('" & wksheet.name & "'!C2,""=P-SEC""," & wksheet.name & "!C16)"
End Sub
Note: If the sheet name has a space in it, you need to surround it in apostrophes in the formula otherwise it will cause an error.

Related

Copy data from one excel workbook to another while retaining formatting

I am new to excel VBA. I have already written VBA code to select any Excel file and copy path of that file to cell A1. Using the path I am trying to copy contents of source file, Sheet7, while retaining cell formatting i.e. bold, borders, colors, etc.
My first error is appearing for file path. Currently cell A1 value = C:\Users\Personal\Documents\Excel files\Dummy-Data - Copy.xlsx.
When I try to read value of A1 cell, VBA throws me an error "Sorry, we couldn't find. Is it possible it was moved, renamed or deleted?" and automatically clears the value of cell A1. But when I give the same path directly in VBA script, it works! Can someone tell me how to get this fixed?
My second doubt is around copying cell formats. When I use wksht.paste to paste copied content to Sheet2, it just pastes all cell values without formatting. But when I try to use PasteSpecial following error occurs- "Application-defined or object-defined error" . Can someone help me correct this please?
Sub Button1_Click()
' define variables
Dim lastRow As Long
Dim myApp As Excel.Application
Dim wbk As Workbook
Dim wkSht As Object
Dim filePath As Variant
'on error statement
On Error GoTo errHandler:
' Select file path
Set myApp = CreateObject("Excel.application")
Sheet2.Range("A1").Value = filePath
Set wbk = myApp.Workbooks.Open(filePath)
'Set wbk = myApp.Workbooks.Open("C:\Users\Personal\Documents\Excel files\Dummy-Data - Copy.xlsx")
' Copy contents
Application.ScreenUpdating = False
lastRow = wbk.Sheets(7).Range("A" & Rows.Count).End(xlUp).Row
wbk.Sheets(7).Range("A2:Q" & lastRow).Copy
myApp.DisplayAlerts = False
wbk.Close
myApp.Quit
' Paste contents
Set wbk = Nothing
Set myApp = Nothing
Set wbk = ActiveWorkbook
Set wkSht = wbk.Sheets("Sheet2")
wkSht.Activate
Range("A2").Select
wkSht.Paste
'wkSht.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:= _
False, Transpose:=False
Application.ScreenUpdating = True
Exit Sub
'error block
errHandler:
MsgBox "An Error has Occurred " & vbCrLf & "The error number is: " _
& Err.Number & vbCrLf & Err.Description & vbCrLf & _
"Please follow instruction sheet"
End Sub
My first error is appearing for file path. Currently cell A1 value = C:\Users\Personal\Documents\Excel files\Dummy-Data - Copy.xlsx. When I try to read value of A1 cell, VBA throws me an error "Sorry, we couldn't find. Is it possible it was moved, renamed or deleted?" and automatically clears the value of cell A1.
You're not setting a var's value to the value of a cell, you're setting the cell's value to a blank var thereby erasing the cell's value. It should be filePath = Sheet2.Range("A1").Value, (the reverse of what you have above).
When I use wksht.paste to paste copied content to Sheet2, it just pastes all cell values without formatting.
You're not just pasting between workbooks; you're pasting between workbooks open in separate application instances. You lose detail like formatting when pasting across instances. In any event, the separate Excel.Application seems wholly unnecessary.
Option Explicit
Sub Button1_Click()
' define variables
Dim lastRow As Long
Dim wbk As Workbook
Dim filePath As Variant
'on error statement
On Error GoTo errHandler:
' Select file path
filePath = Sheet2.Range("A1").Value
Set wbk = Workbooks.Open(filePath)
'Set wbk = Workbooks.Open("C:\Users\Personal\Documents\Excel files\Dummy-Data - Copy.xlsx")
' Copy contents & Paste contents
Application.ScreenUpdating = False
lastRow = wbk.Sheets(7).Range("A" & Rows.Count).End(xlUp).Row
wbk.Sheets(7).Range("A2:Q" & lastRow).Copy _
Destination:=Sheet2.Range("A2")
'shouldn't have to disable alerts
'Application.DisplayAlerts = False
wbk.Close savechanges:=False
'Application.DisplayAlerts = True
'
Application.ScreenUpdating = True
Exit Sub
'error block
errHandler:
MsgBox "An Error has Occurred " & vbCrLf & "The error number is: " _
& Err.Number & vbCrLf & Err.Description & vbCrLf & _
"Please follow instruction sheet"
End Sub
The naked worksheet codename references should be valid within ThisWorkbook.

VBA taking value from one workbook to another with having formulas pasted

I am looking to copy the values of specific cells from one workbook to another. I have the code below but it only returns the cells with the formulas and not just the value. I know need to add a line somewhere about pastespecial etc. but not sure where. Any help?
Sub PullClosedData()
On Error GoTo Errorcatch
Dim filePath As String
Dim SourceWb As Workbook
Dim TargetWb As Workbook
Set TargetWb = ActiveWorkbook
Dim emptyRow As Long
emptyRow = Range("A" & Rows.Count).End(xlUp).Offset(1)
filePath = TargetWb.Sheets("results").Range("A1").Value
Set SourceWb = Workbooks.Open(filePath)
SourceWb.Sheets("8").Range("D36:G36").Copy
Destination:=TargetWb.Sheets("Staff data").Range("a" &
Rows.Count).End(xlUp).Offset(1)
SourceWb.Close SaveChanges:=False
MsgBox "Staff data sheet updated"
Exit Sub
Errorcatch: MsgBox Err.Description
End Sub
You want values only?
Try changing the line below:
SourceWb.Sheets("8").Range("D36:G36").Copy Destination:=TargetWb.Sheets("Staff data").Range("a" & Rows.Count).End(xlUp).Offset(1)
To:
SourceWb.Sheets("8").Range("D36:G36").Copy
TargetWb.Sheets("Staff data").Range("a" & Rows.Count).End(xlUp).Offset(1).pastespecial xlPasteValues 'Or xlPasteValuesAndNumberFormats might suit you better.'
You can also assign:
destinationrange.value2
= sourcerange.value2
If you only want internal values.

Excel VBA How to copy and paste a section of cells into a newly made sheet

I'm making a budgeter sort of thing that helps people keep track of their money. I currently have a bunch of code that checks the current month and attempts to make a new sheet with the name (MM/YYYY) unless that sheet has already been made, if it has been made then nothing will happen.
Private Sub Worksheet_Change(ByVal Target As Range)
nowMonth = Month(Now)
nowYear = Year(Now)
sheetNameStr = nowMonth & "," & nowYear
sheetExists = False
For Each Sheet In Worksheets
If sheetNameStr = Sheet.Name Then
sheetExists = True
End If
Next Sheet
If sheetExists = False Then
Set ws = ThisWorkbook.Sheets.Add(After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count))
ws.Name = sheetNameStr
MsgBox ("New sheet named " & sheetNameStr & "was created")
End If
Sheets("Main").Activate
Worksheets("Main").Range("A5:D300").Copy Worksheets("sheetNameStr").Range("A1")
End Sub
The problem I am having is trying to copy and paste the history of my purchases/income and pasting it into the new sheet. I always get the
Run-time error '9': Subscript out of range
error.
If anyone could help that'd be great thanks!
Your line saying
Worksheets("Main").Range("A5:D300").Copy Worksheets("sheetNameStr").Range("A1")
is referring to a worksheet called "sheetNameStr", but you really want to refer to a sheet with the name contained in the variable sheetNameStr, i.e.
Worksheets("Main").Range("A5:D300").Copy Worksheets(sheetNameStr).Range("A1")

Excel VBA reference named workbook in vlookup formula in DoWhile loop

This seems like it should be simple, but I'm really stuck on it.
This is code to get values from multiple workbooks in a directory and compile them in one workbook. I am using vlookup because the value is not always in the exact same cell, but always has the same row header. The code opens each workbook in the directory and names it wb.
I want to reference wb in the Vlookup formula but am having trouble doing it. When I try the code below it gives me a "loop without do" error (but when I run the same code without the formula, just copying and pasting ranges, it is fine). I've also tried naming a range in wb and referencing that.
'Target File Extension
myExtension = "*.xls"
'Target Path with Ending Extention
myFile = Dir(myPath & myExtension)
'Loop through each Excel file in folder
Do While myFile <> ""
'Set variable equal to opened workbook
Set wb = Workbooks.Open(fileName:=myPath & myFile)
'Put ID from filename into sheet
If right(wb.Name, 5) = "h.xls" Then
wb.Worksheets(1).Range("B16").Select
ActiveCell.Value = Left(wb.Name, 9)
'Get value from wb using Vlookup
MasterBook.Activate
ActiveCell.Offset(1, 0).Select
ActiveCell.FormulaR1C1 = "=VLOOKUP(""Sugar (g)"",wb!R18C1:R28C6,2,FALSE)"
'Close Workbook
wb.Close SaveChanges:=True
'Get next file name
myFile = Dir
Loop
'Message Box when done
MsgBox "Task Complete!"
For the formula, you need to add the name of the workbook into the string. You can't reference the variable wb while it is part of the string. You also need to reference the workbook and the sheet name.
So I'd suggest something like the following to get those names:
ActiveCell.FormulaR1C1 = "=VLOOKUP(""Sugar (g)"",[" & wb.name & "]" & wb.Worksheet(1).Name & "!R18C1:R28C6,2,FALSE)"
You cannot use the Range object directly when putting together a string to be used as a formula. Concatenate the Range.Address property into the string.
ActiveCell.FormulaR1C1 = "=VLOOKUP(""Sugar (g)"", " & _
wb.Worksheets(1).Range("A18:F28").address(External:=true, ReferenceStyle:=xlR1C1) & _
", 2, FALSE)"
'or,
ActiveCell.Formula = "=VLOOKUP(""Sugar (g)"", " & _
wb.Worksheets(1).Range("A18:F28").address(External:=true) & _
", 2, FALSE)"
What I do in these kinds of situations is keep removing parts of code until it works or gives a different error message or something. That way you can narrow down to where the error is.
The Do While .. Loop looks fine, I think you're missing an End If
If Right(wb.Name, 5) = "h.xls" Then
wb.Worksheets(1).Range("B16").Select
ActiveCell.Value = Left(wb.Name, 9)
End If

Finding a specific keyword in many workbooks along with a corresponding value and placing them in a column in one workbook

In a previous posting I asked about how to highlight a cell range that began with a certain keyphrase and ended when the next cell was blank. I would like to gain a better understanding of how to create a loop that performs this on multiple Excel files. Any help would be much appreciated. For reference, the code I am referring to is as follows:
Dim wk As Worksheet
Set wk = ActiveSheet
FirstRowColA = Application.WorksheetFunction.Match("keyphrase", wk.[A:A])
LastRowColA = Cells(wk.Rows.Count, "A").End(xlUp).Row
wk.Range("A" & FirstRowColA & ":A" & LastRowColA).Copy
Worksheets("Sheet2").Paste
In addition, I was curious about how to handle creating a "Sheet 2" if one does not exist already in the active workbook. Do I need to use something like Set WS = Sheets.Add and have Excel look at Worksheets(Sheets.Add).Paste?
I have also noticed that this code does not necessarily find what I am telling it to find, but this is an issue I should be able to resolve. For example, putting the phrase "Name" in the Match() function returns the text of a cell in column A containing a different word.
Let say u have excel files in the some folder
this code opens each workbook in the folder and searches specific string if found .copy and paste the required data.
Sub LoopThroughFiles()
Dim StrFile As String
Dim wk As Worksheet
StrFile = Dir("C:\Personal\Excel Report\*.xlsx")
Do While Len(StrFile) > 0
Workbooks.Open ("C:\Personal\Excel Report\" & StrFile)
Set wk = ActiveSheet
Set firstrowcola = activesheet.Range("A:A").Find("taskname") ' - search taskname in 1st row
If firstrowcola Is Nothing Then GoTo here:
LastRowColA = Cells(wk.Rows.Count, "A").End(xlUp).Row
wk.Range(firstrowcola.address & ":" & firstrowcola.offset(lastrowcola,0).address)).Copy
Set ws = Sheets.Add
ws.Range("A1").Select
ActiveSheet.Paste
here:
ActiveWorkbook.Close True
Loop
End Sub