Sie sind auf Seite 1von 2

signup

login

tour

help
Dismiss

AnnouncingStackOverflowDocumentation
WestartedwithQ&A.Technicaldocumentationisnext,andweneedyourhelp.
Whetheryou'reabeginneroranexperienceddeveloper,youcancontribute.

Signupandstarthelping

LearnmoreaboutDocumentation

VBAVariablesheetnameinsumifformula

I'mtryingtouse SUMIF formulainVBA,basedonasheetthatcanhavediferentnames.


WhenI'monthis ActiveSheet (canvary),IwanttoaddanothersheettemplatefromanotherworkbookTemplate_testandputa SUMIF formula
referencedtotheactivesheet.
WhenIrunthemacro,erroroccurs(1004)andstopsattheformula.
ThisiswhatIhave:
Subtest()
SetCurBook=ThisWorkbook
DimwksheetAsWorksheet
Setwksheet=ActiveSheet
MsgBoxCurBook.Name&"_"&wksheet.Name
'Opentemplate
Workbooks.Openfilename:=_
"D:\Template_test.xlsm"
'Copynewsheet
Sheets("template").Select
Sheets("template").CopyAfter:=CurBook.ActiveSheet
'CloseTemplatefile
Windows("Template_test.xlsm").Activate
ActiveWindow.Close
'SUMIFFormulainTemplateregardingwksheetinCurBook
Range("E11").Select
ActiveCell.FormulaR1C1=_
"=SUMIF('&wksheet&!C2,""=PSEC"",'&wksheet&!C16)"EndSub

Isthereawaytosolvethisandmakeitwork?
excel vba excelvba
editedMar13'15at22:22

L42
12.3k

1Answer

Iseetwoissueshere:
i)wksheetisanobjectoftype'WorkSheet'andnotastring,soyoucan'tuseitasastring.
ii)wksheetisavailableinthecode,butnotintheworksheet,sowhenyoupastethefunctioninto
thecell,youneedtoexitthestringandappendthename.
Trythis:
ActiveCell.FormulaR1C1=_
"=SUMIF('"&wksheet.name&"'!C2,""=PSEC"","&wksheet.name&"!C16)"
EndSub

Note:Ifthesheetnamehasaspaceinit,youneedtosurrounditinapostrophesintheformula
otherwiseitwillcauseanerror.
editedMar19'15at19:26

answeredMar13'15at19:06

OpiesDad
2,352

19

Hi,triedwiththatchange.Gotthesameerror.Triedtochangetheplaceofthe"and&andgetthesame

erroralways. sekiumo Mar16'15at17:12


Trysettingtheformulaequaltoavariableso,testvar=""=SUMIF("&wksheet.name&"!C2,=""PSEC"","&

wksheet.name&"!C16)"andthendebug.printthevariableandmanuallyputthevalueintoacelltoseewhat
happens.OpiesDadMar16'15at17:53
Sorry,butdon'tknowhowdebug.printworks. sekiumo Mar18'15at10:56
TriedDebug.Printwiththefiistformulayouprovided,gotFALSEinImmediate.Triedtoputthevariable

testvar,butitshowsaCompileerrorinthe!beforeC2. sekiumo Mar18'15at11:12

askedMar13'15at18:42

sekiumo
5

20

42

Shouldhaveonlybeenonequoteatthebeginning.Mymistake.Trytestvar="=SUMIF("&wksheet.name&
"!C2,=""PSEC"","&wksheet.name&"!C16)"OpiesDadMar18'15at13:44

Das könnte Ihnen auch gefallen