VBA Cell Value - Get, Set, or Change - Automate Excel

文章推薦指數: 80 %
投票人數:10人

This tutorial will teach you how to interact with Cell Values using VBA. Set Cell Value. To set a Cell Value, use the Value property of the Range or Cells ... VBACodeExamples  InDepthTutorialsyes PowerPointVBAMacroExamples&Tutorial Sorting FindandFindandReplace CheatSheets–Commands&SyntaxLists WordMacroExamples&VBATutorial Basicsyes If,ElseIf,Else(UltimateGuidetoIfStatements) ValuePaste&PasteSpecial VBA–Cut,Copy,PastefromaMacro VBASaveFile–20EasyExamples VBACodingConceptsyes CommentinginVBA Creating(Custom)UserDefinedFunctions(UDFs) ExcelVBA–NamedRangesandProgramming HowtoRenameorDeleteaModuleorForm Opening&UsingtheVisualBasicEditor(VBE)inExcel ReturnaValuefromaSubProcedure ShortcutsfortheVisualBasicEditor CallFunctionfromaSub Function–Call,ReturnValue,&Parameters ObjectModel OnError–ErrorHandlingBestPractices PrivatevsPublicProcedures(Subs&Functions) SelectCaseStatement SubProcedure WhatisaVBAModule? WhatisaVBAProject?(AndHowtoEdit) VBA–HideaMacro VBA–LanguageReferences VBA–ModifytheRight-ClickMenutoCallaMacro VBA–RunaMacrofromaMacro VBA–RunaMacroLinebyLine VBA–Wait,Delay,CreateaTimerWhileRunningCode Debug.PrintandImmediateWindow VBADoEvents VBAEnd VBAExitSuborFunction VBAOnErrorExitSub VBAOptionExplicit VBA:ImproveSpeed&OtherBestPractices Loopsyes VBAForLoop–LoopThroughaRangeofCells Loops-UltimateGuide ForEachExamples(QuickReference) VBAExitFor VBAExitLoop WhileWendLoop RangesandCellsyes RangesandCells-UltimateGuide Formulas-UltimateGuide UnionandIntersect ResizeRange VBA–AutofillwithaMacro VBA–ChangeaCell;sBackgroundColor VBA–ClearFormats–RemoveFormattingForEachCellInRange VBA–ConditionalFormatting–HighlightDuplicatesinaRange VBA–DeleteAllNamedRanges VBA–DeleteHyperlinks VBA–DetermineStartandEndColumnofaMergedCell VBA–Excel’sColorScheme VBA–FindtheMaximumValueForEachColumninaRange VBA–FormatPainter VBA–GettheActiveCell’sColumnorRow VBA–ResizeanObjecttoaRangeSize VBA–SelectAllCells VBA–SumbyColor VBA–TestifSelectionisaRangeorObject CellValue–Get,Set,orChange ClearContents/ClearCells CopyDestination(CopyRangetoAnotherSheet) CurrentRegion DynamicRange VBAFunction–PopulatingaRangeWithRandomValues HighlightCell VBAMergeCells&UnmergeCells OffsetRangeorCell Range/CellAddress Range.End(xlDown,xlUp,xlToRight,xlToLeft) VBARoutinetoreturnColumnLetterofCell VBASelectRangeorCells VBAUnion–JoinMultipleRanges VBAWrapText ActivecellOffsetVBA Rows&Columnsyes Select(andworkwith)EntireRows&Columns DeleteorInsertRowsBasedonCellValue DeleteRowsthatMeetCertainCriteriainVBA Hide/UnhideColumns&Rows UnhideAllRows/Columns VBA–AutofitColumns VBA–CounttherowsinaSelection VBA–DeleteBlankRows VBA–SelectEvery5thRow VBA–SelectNonContiguousColumns Copy/PasteRows&Columns DeleteEntireRoworColumn GroupRows&Columns InsertRoworColumn VBASetColumnWidthorRowHeight VBAUsedRange–CountNumberofUsedRowsorColumns Sheetsyes Sheets–TheUltimateGuide VBA–CounttheSheetsinaWorkbook VBA–CreateaHyperlinkMenuofWorksheets VBA–Hide(orUnhide)aWorksheet VBA–HideWorkSheetTabs VBA–HowtoUseWorksheetFunctions(andaFullList) VBA–LoopThroughallWorksheetswithForEach VBA–MacrotoListallSheetsinaWorkbook SendWorksheetsbyEmailasSeparateWorkbooks VBA–SortSheetsAlphabetically VBA–UnhideAllWorksheets ClearEntireSheet VBACopyWorksheet VBADeleteorClearWorksheet GetSheetName/RenameSheet VBAProtect/UnprotectWorksheets VBARoutinetoAddandNameWorksheets VBASelectSheet,ActivateSheet,andGetActivesheet WorksheetRange VBA:SettheDefaultSheetWhenaWorkBookOpens HowtoSortTabs/WorksheetswithaVBAMacro Workbooksyes CombineWorkbooks CreateNewWorkbook(Workbooks.Add) ActivateWorkbook ActiveWorkbookvs.ThisWorkbook VBAOpen/CloseWorkbook WorkbookName(Get,Set,withoutExtension) WorkbookProtection(PasswordProtect/Unprotect) WorkingwithWorkbooks(TheWorkbookObject) Arraysyes Arrays VBA–ArrayExamples DictionaryObjects Collections ArrayList ArrayofObjects VariantArray DynamicArray(Redim&RedimPreserve) Declare&InitilizeStringArray Declare(Dim),Create,andInitializeArrayVariable ArrayLength/Size AssignRangetoArray ClearArray–EraseFunction LoopThroughArray/ForEachIteminArray SortArray TransposeArray Searchfor(Find)ValueinArray PopulateArraywithUniqueValuesfromColumn RemoveDuplicatesFromArray FunctionReturnArray Multi-DimensionalArray(2DArrays) Output(Print)ArraytoRange Errorsyes TryCatchErrors ObjectRequiredError SyntaxErrorVBA TypeMismatch(Run-timeError13) AutomationError CompileError Error1004–Application-DefinedorObject-DefinedError IgnoreError OnErrorResumeNextorGoto0 OutofMemoryError Throw/RaiseError–Err.Raise–CustomErrorMsg Can’tFindProjectorLibrary–VBACompileError CompileErrorinHiddenModule–VBA FixError400 FixVBAError438–ObjectDoesn’tSupportPropertyorMethod FixVBARunTimeError32809 FixVBARunTimeError57121 Variablesyes DimVBA–DeclareVariable VBA–DetermineaVariable’sUnderlyingType VBAArrayVariables BooleanDataType(DimVariable) Constant VBAConstantExpressionRequired VBADataTypes–VariablesandConstants VBADateVariable DoubleDataType(DimVariable) VBAGlobalVariable Int/IntegerDataType(DimVariable) LongDataType(DimVariable) VBAPublicVariable–UseaVariableinMultipleModulesorSubs VBARangeObjectVariables(Dim/SetRange) SetObjectVariables–Workbooks,Worksheets,&More SingleDataType(DimVariable) VBAStaticVariable StringDataType(DimVariable) VariantDataType(DimVariable) Settingsyes GetandChangeUserNamewithVBA VBA–DisplayStatusBarMessage VBA–Modifythetitlebar VBA–Preventwarningmessagesfromamacro VBA–TurnAutomaticCalculationsOff(orOn) VBA–TurnFormulaBarOff(orOn) VBA–TurnoffScreenUpdating VBATurnScrollBarsOnorOff TextandStringsyes SplitStringintoCells PreventVBACaseSensitive–OptionCompareText VBA–ExtractNumberFromString VBA–FindthenthWordinaStringofText VBA–ForceProper,Upper,orLowercaseautomatically VBA–LineBreakorLineFeedinaMessageBox VBA–LoopThroughaString VBA–RemoveCharactersfromLeftorRightSideofVariableLengthString VBA–ReverseaStringofText VBAChar/ChrFunction VBACompareStrings–StrComp VBAComparisonOperators–NotEqualto&More VBAConcatenateTextStringsTogether(&–Ampersand) ConvertInteger(Number)toString ConvertStringtoDate ConvertTextStringtoNumber VBAFunctionToCalculateNumberofWordsinaString VBAINSTR–FindTextinaString VBALikeOperator VBALogicalOperators–OR,AND,XOR,NOT,IS,&LIKE VBANewLine/CarriageReturn ParseString VBASpaceFunction–AddSpacestoaString VBAStringsandSubstringsFunctions TexttoColumns Trim,LTrim,andRTrimFunctions–RemoveSpacesFromText VBAUpper,Lower,andProperCase–CaseFunctions Viewyes VBA–ActiveWindow.WindowState VBA–Display(orExit)Fullscreen VBA–FreezePanes VBA–HideExcel(TheEntireApplication) VBA–PageBreakPreviewModeOnorOff VBA–ScrollVerticallyandScrollHorizontally VBA–Zoom–FitSelection VBA–ZoominandOutofWorksheets Filesyes FileSystemObject MoveFileswithVBAFileSystemObject(MoveFile) VBA–ConvertExceltoCSV(CommaDelimitedTextFile) CreateTextFilewithCreateTextFile VBA–Deletefilesfromtheharddrive VBA–ExportRangetoCSV(DelimitedTextFile) ImportFileNamestoClickableLinks VBA–ListofallfilescontainedwithinaDirectory ReadTextFileintoString ReadTextFileLinebyLine VBA–TestifWorkbookisOpenbyWorkbookName ValidateFilenames WritetoTextFile VBACheckifFileorFolderExists CombineMultipleExcelFilesintoOneWorkbook CopyaFolderwithCopyFolder(FSO) VBACopyFile/Workbook VBADeleteFile/Workbook DeleteFolderwithDeleteFolder(FSO) FileCopyStatement GetFileNamewithGetFileName(FSO) GetFolder&GetFile(GetFile&FolderProperties) VBAListFilesinFolder VBAOpenFileDialogBox OpenTextFilewithOpenTextFile ReadTextFile(Read,Parse,andImport) VBARenameFile Shapes,Charts,Objectsyes VBAAutoFilter VBAGuideForChartsandGraphs VBAGuidetoPivotTables VBAObjects ExcelAddVBAButton HowtouseVBAControlsinUserForms VBA–CreateaBarChart VBA–DeleteAllAutoshapes VBA–ProgrammaticallyDrawBoxeswithCode Listbox–SelectedItem VBATablesandListObjects TextBox Formattingyes ConditionalFormatting Bold CellBorders CellFont–ChangeColor,Size,Style,&More CenterText–CellAlignment(Horizontal&Vertical) DisplayPageBreaksSetting FormatCells FormatDate FormatTime Eventsyes Events VBA–ExitWithoutSavePrompt VBA–ForceaWorkbooktoSaveBeforeClose VBA–RunaMacrowhenExcelCloses–Auto_Close VBA–RunamacrowhenExcelstarts VBAWorksheetChangeEvent–RunaMacroWhenaCellChanges VBA:ShoworloadaformwhenExcelstarts UserForms,MsgBoxes&Controlsyes VBA–MakeUserformTransparent VBA–YesNoMessageBox(Msgbox) VBAInputBox–GetInputfromaUser CreatingVBAUserforms OptionButtonExcelVBA SpinbuttonExcelVBA VBACheckbox VBAComboBox VBAListbox VBAOpenorCloseUserForm Formattingyes ConditionalFormatting Bold CellBorders CellFont–ChangeColor,Size,Style,&More CenterText–CellAlignment(Horizontal&Vertical) DisplayPageBreaksSetting FormatCells FormatDate FormatTime Misc.yes ClearClipboard Pause(Break/Stop)&ResumeaMacro SaveAs(Print)toPDF ColorIndexCodesList FormatNumbers HowtoInstall(orUninstall)aVBAadd-in(.xlamfile)forMicrosoftExcel HowtouseVBAStructures RemovingDuplicateValuesinExcelVBA SpeedupyourVBACode VBA–AddorRemoveCellComments AllOperatorsExplained BuildaCustomImportInterface CheckifOfficeAppisRunning DialogBox GetToday’sDate(CurrentDate) PivotTableFilter RefreshPivotTable/AllPivotTables RefreshPivotTablewhenDataChanges UsingGoalSeekinVBA UsingtheAnalysisToolPakinVBA AdvancedFilter Application.CutCopyMode=False Calculate–Now,Workbook,Worksheet,orRange Call/RunSubFromanotherSubroutine CopytoClipboard FindValueinColumn GoToaLineLabel IIFFunction InputStatement isNothing IsOperator LineInputStatement Multiple(Nested)IfStatements ProjectPassword/Protectcode Reference Solver Wait&SleepFunctions–Pause/DelayCode Wildcards With/EndWithStatement WhatistheDifferenceBetweenVBandVBA? PersonalMacroWorkbook VBA–CheckSpelling VBA–TurnOffAutoFilter/ClearFilters VBADropDownList(DataValidation) VBAHyperlinks VBARandomNumber Functionsyes CheckifSheetand/orRangeExistsFunction EnvironFunction–ExcelVBA IsEmptyFunction UsingIsnumericandIsnumberinVBA VBA–CompareDates AbsFunction AVERAGE,AVERAGEA,AVERAGEIF CCurFunction CDblFunction–ConverttoDouble CDecFunction ChDirStatement ChDriveStatement CIntFunction–ConverttoInteger CLngFunction–ConvertExpressiontoLong CLngLngFunction CloseStatement COUNTFunction COUNTIFandCOUNTIFSFunctions CreateObject(CreateObject) CSngFunction CurDirFunction VBADateFunctions DateAddFunction DateDiffFunction DatePartFunction DateSerialFunction DateValueFunction DayFunction DirFunction EnvironFunctions EOFFunction FileDateTimeFunction FilterArrays FormatFunction FreeFileFunction VBAFunctiontoShowCellFormula FunctionsList GetAttrFunction HexFunction HourFunction InStrRevFunction–FindTextFromRight IsArrayFunction IsDateFunction IsEmptyFunction IsErrorFunction IsMissingFunction IsNullFunction IsNumericFunction JoinFunction LBoundFunction LeftFunction–ExtractTextFromLeft LenFunction–GetStringLength LOFFunction LogFunction MacIDFunction MidFunction–ExtractCharactersFromMiddleofString MinuteFunction MkDirStatement MonthFunction MonthNameFunction NowFunction–GetCurrentDate&Time OpenStatement PrintStatement RandomizeStatement ReplaceFunction–ReplaceString RightFunction–ExtractTextFromRight RndFunction RoundFunction Round,RoundUp,andRoundDown SecondFunction SplitFunction–SplitStringofTextintoArray SqrFunction SumFunction(Ranges,Columns,&More) SUMIFandSUMIFSFunctions SwitchStatement TextFunction TimeFunction TimeFunctions TimerFunction TimeSerialFunction TimeValueFunction TypeName TypeOf UBound&LBoundFunctions ValFunction VarType WeekdayFunction WeekdayNameFunction WriteStatement YearFunction Vlookup–MultipleResultswithVBA VlookupMultipleCriteriawithVBAUDF AdvancedProgrammingyes AdvancedVBAProgrammingExamples EarlyLateBinding ClassConstructor ClassModuleTutorial&Examples Matrix–Create&More Shell VBA–ConvertMatrixtoVector VBA–ProgrammingtheVBE(VisualBasicEditor) VBARegex VBASendKeys VBATimerFunction Internetyes AutomateInternetExplorer(IE)UsingVBA VBA–ConsumeSoapWebServices VBA–WinHttpRequestwithLoginandPassword–MiscBloglines SendEmailsfromExcelthroughGmail SendEmailsfromExcelthroughOutlook Accessyes AccessVBARecordsets–Open,Count,LoopandMore AccessVBA–Import/ExportExcel–Query,Report,Table,andForms AccessVBA–Open/CloseForm AccessVBA–OpenExcelFile AccessVBADatabase–Open,Connect,Login,&More AccessVBAFindfirst AccessVBAMe AccessVBAQuery AccessVBARecordsets–Open,Count,LoopandMore AccessVBARefreshForm AccessVBAReports–Print,Export,Filter AccessVBASQLExamples AccessVBATables–Update,Count,Delete,Create,Rename,Export Wordyes WordBookmarks–VBAMacrostoAdd,Delete,Goto,Modify WordVBA–MacrotoOpenWordDocument WordVBAMacros–AddNewDocument WordVBAMacros–CountWordsinSelection WordVBAMacros–Find,Find&Replace WordVBAMacros–SaveAs(PDForNewFileName) WordVBAMacros–Tables:Add,Select,Loop,InsertFromExcel WordVBAMacros–Templates(MakeNew) WordVBAMacros–TextBox:Add,Delete,Write OtherExcelGuides "HowTo"Guides "Formulas"Guides "Shortcuts"Guides VBAGuides ReturntoVBACodeExamples InthisArticleSetCellValueRange.Value&Cells.ValueSetMultipleCells’ValuesatOnceSetCellValue–TextSetCellValue–VariableGetCellValueGetActiveCellValueAssignCellValuetoVariableOtherCellValueExamplesCopyCellValueCompareCellValues ThistutorialwillteachyouhowtointeractwithCellValuesusingVBA. SetCellValue TosetaCellValue,usetheValuepropertyoftheRangeorCellsobject. Range.Value&Cells.Value Therearetwowaystoreferencecell(s)inVBA: RangeObject–Range(“A2”).Value CellsObject–Cells(2,1).Value TheRangeobjectallowsyoutoreferenceacellusingthestandard“A1”notation. ThiswillsettherangeA2’svalue=1: 1 Range("A2").Value=1 TheCellsobjectallowsyoutoreferenceacellbyit’srownumberandcolumnnumber. ThiswillsetrangeA2’svalue=1: 1 Cells(2,1).Value=1 Noticethatyouentertherownumberfirst: 1 Cells(Row_num,Col_num) SetMultipleCells’ValuesatOnce Insteadofreferencingasinglecell,youcanreferencearangeofcellsandchangeallofthecellvaluesatonce: 1 Range("A2:A5").Value=1 SetCellValue–Text Intheaboveexamples,wesetthecellvalueequaltoanumber(1). Instead,youcansetthecellvalueequaltoastringoftext. InVBA,alltextmustbesurroundedbyquotations: 1 Range("A2").Value="Text" Ifyoudon’tsurroundthetextwithquotations,VBAwillthinkyoureferencingavariable… SetCellValue–Variable Youcanalsosetacellvalueequaltoavariable 1234 DimstrTextasStringstrText="StringofText" Range("A2").Value=strText GetCellValue YoucangetcellvaluesusingthesameValuepropertythatweusedabove. VBACodingMadeEasy StopsearchingforVBAcodeonline.LearnmoreaboutAutoMacro-AVBACodeBuilderthatallowsbeginnerstocodeproceduresfromscratchwithminimalcodingknowledgeandwithmanytime-savingfeaturesforallusers! LearnMore!! GetActiveCellValue TogettheActiveCellvalueanddisplayitinamessagebox: 1 MsgBoxActiveCell.Value AssignCellValuetoVariable Togetacellvalueandassignittoavariable: 123 DimvarasVariant var=Range("A1").Value HereweusedavariableoftypeVariant.Variantvariablescanacceptanytypeofvalues. Instead,youcoulduseaStringvariabletype: 123 DimvarasString var=Range("A1").Value AStringvariabletypewillacceptnumericalvalues,butitwillstorethenumbersastext. Ifyouknowyourcellvaluewillbenumerical,youcoulduseaDoublevariabletype(Doublevariablescanstoredecimalvalues): 123 DimvarasDouble var=Range("A1").Value However,ifyouattempttostoreacellvaluecontainingtextinadoublevariable,youwillreceiveantypemismatcherror: OtherCellValueExamples VBAProgramming|CodeGeneratordoesworkforyou!CopyCellValue It’seasytosetacellvalueequaltoanothercellvalue(or“Copy”acellvalue): 1 Range("A1").Value=Range("B1").Value Youcanevendothiswithrangesofcells(therangesmustbethesamesize): 1 Range("A1:A5").Value=Range("B1:B5").Value CompareCellValues Youcancomparecellvaluesusingthestandardcomparisonoperators. Testifcellvaluesareequal: 1 MsgBoxRange("A1").Value=Range("B1").Value WillreturnTRUEifcellvaluesareequal.OtherwiseFALSE. YoucanalsocreateanIfStatementtocomparecellvalues: 12345678910111213 IfRange("A1").Value>Range("B1").ValueThen  Range("C1").Value="GreaterThan" ElseifRange("A1").Value=Range("B1").ValueThen  Range("C1").Value="Equal" Else  Range("C1").Value="LessThan" EndIf Youcancomparetextinthesameway(RememberthatVBAisCaseSensitive) VBACodeGenerator LearnMore VBACodeExamplesAdd-in Easilyaccessallofthecodeexamplesfoundonoursite. Simplynavigatetothemenu,click,andthecodewillbeinserteddirectlyintoyourmodule..xlamadd-in. (Noinstallationrequired!) FreeDownload ReturntoVBACodeExamples AutoMacro:VBAAdd-inwithHundredsofReady-To-UseVBACodeExamples&muchmore! LearnMore WhatisAutoMacro? AutoMacroisanadd-inforVBAthatinstallsdirectlyintotheVisualBasicEditor.Itcomesloadedwithcodegenerators,anextensivecodelibrary,theabilitytocreateyourowncodelibrary,andmanyotherhelpfultime-savingtoolsandutilities. LearnMore VBA(Macros)CodeExamplesAdd-in TryforFree UltimateVBAAdd-in off-Sale! Offerexpiressoon! SaleEndsFridayatMidnight 0   0 days 0   0 hours 0   0 minutes 0   0 seconds 1004Reviews DownloadourVBAMacroCodeExamplesAdd-in Download 100%Free AutoMacro:TheUltimateAdd-inforVBA off-Sale!



請為這篇文章評分?