6_1.[D E F]

VB/VBAの 組み込み関数 TOP-Pageへ

こちらも役に立つ情報
各関数の使用例

Date

現在のシステム日付を含む Variant (Date) を返します

システム日付を設定するには、Date ステートメントを使用します
        
記述凡例
Dim MyDate
MyDate = Date    ' MyDate contains the current system date.
      

DateAdd

指定した時間間隔を日付に加算してその日付を含む Variant (Date) を返します
DateAdd(interval, number, date)
DateAdd 関数を使用すると、指定した時間間隔を日付に加算したり、日付から減算したりできます。 たとえば、DateAdd を使用して、今日から 30 日後の日付、または今から 45 分後の時刻を計算することができます
        
記述凡例
Dim FirstDate As Date    ' Declare variables.
Dim IntervalType As String
Dim Number As Integer
Dim Msg As String
IntervalType = "m"    ' "m" specifies months as interval.
FirstDate = InputBox("Enter a date")
Number = InputBox("Enter number of months to add")
Msg = "New date: " & DateAdd(IntervalType, Number, FirstDate)
MsgBox Msg
      

DateDiff

2 つの指定した日付の時間間隔を指定する Variant (Long) を返します
DateDiff(interval, date1, date2, [ firstdayofweek, [ firstweekofyear ]] )
DateDiff 関数を使用して、2 つの日付の間に指定した時間間隔がどのくらい存在するかを確認します。 たとえば、DateDiff を使用して、2 つの日付間の日数や、今日から年末までの週数を計算することができます
        
記述凡例
Dim TheDate As Date
' Declare variables.
Dim Msg
TheDate = InputBox("Enter a date")
Msg = "Days from today: " & DateDiff("d", Now, TheDate)
MsgBox Msg 
      

DatePart

この関数の使用に問題がありますと警告が出ています
DatePart(interval, date, [ firstdayofweek, [ firstweekofyear ]])
DatePart 関数を使用して 日付を評価し、特定の間隔を返します。 たとえば、曜日または現在の時間を計算するために、DatePart を使用する場合があります
        
記述凡例
Dim TheDate As Date    ' Declare variables.
Dim Msg    
TheDate = InputBox("Enter a date:")
Msg = "Quarter: " & DatePart("q", TheDate)
MsgBox Msg
      

DateSerial

指定した年、月、日の Variant (Date) を返します
DateSerial(year, month, day)
        
記述凡例
Dim MyDate
' MyDate contains the date for February 12, 1969.
MyDate = DateSerial(1969, 2, 12)    ' Return a date.
      

DateValue

Variant (Date) を返します
DateValue(date)
必須の date 引数は、通常、100 年 1 月 1 日から 9999 年 12 月 31 日までの日付を表す 文字列式です。 また、date には、この範囲内の日付や時刻、または日付と時刻の両方を表す任意の 式を指定することもできます
date が有効な 日付の区切り記号で区切られた数字のみを含む文字列である場合、DateValue は、ユーザーがシステムに対して指定した短い日付形式に従って月、日、年の順序を認識します。 また、DateValue は、月の名前 (長い形式または省略形) を含んだ明確な日付も認識します。 たとえば、DateValue は、"12/30/1991" と "12/30/91" だけでなく "December 30, 1991" と "Dec 30, 1991" も認識します。
date の年の部分を省略した場合、DateValue はコンピューターのシステム日付の現在の年を使用します
記述凡例
Dim MyDate
MyDate = DateValue("February 12, 1969")    ' Return a date.
      

Day

月の特定の 1 日を表す 1 から 31 の範囲の整数を指定する Variant (Integer) を返します
Day(date)
必須の date 引数は、日を表す任意の Variant、数式、文字列式、または任意の組み合わせです。 date に Null が含まれている場合は Null が返されます
        
記述凡例
Dim MyDate, MyDay
MyDate = #February 12, 1969#    ' Assign a date.
MyDay = Day(MyDate)    ' MyDay contains 12.
      

DDB

倍額定率法や、ユーザーが指定した他の方法を使用して、特定の期における資産の減価償却費を指定する Double を返します
DDB(cost, salvage, life, period, [ factor ])
倍額定率法では、減価償却費が加速的に計算されます。 減価償却費は、最初の期が最も多く、その後の期では減少します。
DDB 関数では、次の数式を使用して、指定した期の減価償却費を計算します
価償却費/period = ((cost - salvage) * factor) / life
        
記述凡例
Dim Fmt, InitCost, SalvageVal, MonthLife, LifeTime, DepYear, Depr
Const YRMOS = 12    ' Number of months in a year.
Fmt = "###,##0.00"
InitCost = InputBox("What's the initial cost of the asset?")
SalvageVal = InputBox("Enter the asset's value at end of its life.")
MonthLife = InputBox("What's the asset's useful life in months?")
Do While MonthLife < YRMOS    ' Ensure period is >= 1 year.
   MsgBox "Asset life must be a year or more."
   MonthLife = InputBox("What's the asset's useful life in months?")
Loop
LifeTime = MonthLife / YRMOS    ' Convert months to years.
If LifeTime <> Int(MonthLife / YRMOS) Then
   LifeTime = Int(LifeTime + 1)    ' Round up to nearest year.
End If 
DepYear = CInt(InputBox("Enter year for depreciation calculation."))
Do While DepYear < 1 Or DepYear > LifeTime
   MsgBox "You must enter at least 1 but not more than " & LifeTime
   DepYear = InputBox("Enter year for depreciation calculation.")
Loop
Depr = DDB(InitCost, SalvageVal, LifeTime, DepYear)
MsgBox "The depreciation for year " & DepYear & " is " & Format(Depr, Fmt) & "."
      

Dir

指定したパターンまたはファイル属性に一致するファイル、ディレクトリ、フォルダーの名前、またはドライブのボリューム ラベルを表す String を返します
Dir [ (pathname, [ attributes ] ) ]
        
記述凡例

      

DoEvents

オペレーティング システムが他のイベントを処理できるように、実行を渡します
DoEvents( )
DoEvents 関数は、単体バージョンの Visual Basic (Visual Basic Professional Edition など) で開かれているフォームの数を表す Integer を返します。 他のすべてのアプリケーションでは、DoEvents はゼロを返します。
DoEvents はオペレーティング システムに制御を渡します。 オペレーティング システムがキュー内のイベントの処理を終了し、SendKeys キューのすべてのキーが送信された後、制御が戻されます
        
記述凡例
' Create a variable to hold number of Visual Basic forms loaded 
' and visible.
Dim I, OpenForms
For I = 1 To 150000    ' Start loop.
   If I Mod 1000 = 0 Then     ' If loop has repeated 1000 times.
      OpenForms = DoEvents    ' Yield to operating system.
   End If
Next I    ' Increment loop counter.
      

Environ

オペレーティング システムの環境変数に関連付けられた String を返します。 Macintosh では使用できません
Environ( { envstring | number } )
envstring が環境文字列テーブル内にない場合は、長さ 0 の文字列 ("") が返されます。 それ以外の場合、Environ は指定された envstring に割り当てられているテキストを返します。つまり、環境文字列テーブルでその環境変数の等号 (=) の後にあるテキストを返します
        
記述凡例
Dim EnvString, Indx, Msg, PathLen    ' Declare variables.
Indx = 1    ' Initialize index to 1.
Do
  EnvString = Environ(Indx)    ' Get environment 
  ' variable.
  If Left(EnvString, 5) = "PATH=" Then    ' Check PATH entry.
     PathLen = Len(Environ("PATH"))    ' Get length.
     Msg = "PATH entry = " & Indx & " and length = " & PathLen
     Exit Do
  Else
     Indx = Indx + 1    ' Not PATH entry,
  End If    ' so increment.
Loop Until EnvString = ""
If PathLen > 0 Then
   MsgBox Msg    ' Display message.
Else
   MsgBox "No PATH environment variable exists."
End If
      

EOF

Random またはシーケンシャル Input で開かれたファイルの末尾に達した場合、Boolean 値 True を含む 整数を返します
EOF(filenumber)
EOF を使用して、ファイルの末尾を越える入力によるエラーが発生しないようにします。
ファイルの末尾に達するまで、EOF 関数は False を返します。 Random または Binary アクセスで開かれたファイルの場合、最後に実行した Get ステートメントでレコード全体を読み取れなくなるまで、EOF は False を返します。
Binary アクセス用に開かれたファイルでは、Input 関数を使って、EOF が True を返すまでファイルを読み取ろうとすると、エラーが発生します。 Input でバイナリ ファイルを読み取るときは、EOF の代わりに LOF 関数と Loc 関数を使用します。または、EOF 関数を使用しているときは Get を使用します。 Output で開かれたファイルの場合、EOF は常に True を返します
        
記述凡例
Dim InputData
Open "MYFILE" For Input As #1    ' Open file for input.
Do While Not EOF(1)    ' Check for end of file.
   Line Input #1, InputData    ' Read line of data.
   Debug.Print InputData    ' Print to the Immediate window.
Loop
Close #1    ' Close file.
      

Error

指定したエラー番号に対応するエラー メッセージを返します
Error [ (errornumber) ]
errornumber 引数は省略可能です。任意の有効なエラー番号を指定できます。 errornumber が有効なエラー番号でも、定義されていなければ、Error から "アプリケーション定義またはオブジェクト定義のエラーです。" という文字列が返されます。
        
記述凡例
Private Sub PrintError()
Dim ErrorNumber As Long, count As Long
count = 1: ErrorNumber = 1
On Error GoTo EOSb
Do While count < 100
   Do While Error(ErrorNumber) = "Application-defined or object-defined error": ErrorNumber = ErrorNumber + 1: Loop
   Debug.Print count & "-Error(" & ErrorNumber & "): " & Error(ErrorNumber)
   ErrorNumber = ErrorNumber + 1
   count = count + 1
Loop
EOSb: Debug.Print ErrorNumber
End Sub
      

Exp

e (自然対数の底) を底とする数値のべき乗を指定する Double を返します
Exp(number)
必須の number 引数は、Double または任意の有効な 数値式です
        
記述凡例
Dim MyAngle, MyHSin
' Define angle in radians.
MyAngle = 1.3    
' Calculate hyperbolic sine.
MyHSin = (Exp(MyAngle) - Exp(-1 * MyAngle)) / 2
      

FileAttr

Open ステートメントを使用して開かれたファイルのファイル モードを表す Long を返します
FileAttr(filenumber, returntype)
        
記述凡例
Dim FileNum, Mode, Handle
FileNum = 1    ' Assign file number.
Open "TESTFILE" For Append As FileNum    ' Open file.
Mode = FileAttr(FileNum, 1)    ' Returns 8 (Append file mode).
Handle = FileAttr(FileNum, 2)    ' Returns file handle.
Close FileNum    ' Close file.
      

FileDateTime

ファイルの作成日時または最終更新日時を示す Variant (Date) を返します
FileDateTime(pathname)
必須の pathname 引数は、ファイル名を指定する 文字列式です。 pathname には、ディレクトリまたはフォルダー、およびドライブを含めることができます
        
記述凡例
Dim MyStamp
' Assume TESTFILE was last modified on February 12, 1993 at 4:35:47 PM.
' Assume English/U.S. locale settings.
MyStamp = FileDateTime("TESTFILE")    ' Returns "2/12/93 4:35:47 PM".
      

FileLen

バイト単位でファイルの長さを指定する Long を返します
FileLen (pathname)
必須の pathname 引数は、ファイルを指定する 文字列式です。 pathname には、ディレクトリまたはフォルダー、およびドライブを含めることができます
        
記述凡例
Dim MySize
MySize = FileLen("TESTFILE")    ' Returns file length (bytes).
      

Filter

指定されたフィルター条件に基づいて、文字列配列のサブセットが含まれるゼロベース配列を返します
Filter(sourcearray, match, [ include, [ compare ]])
        
記述凡例
Dim xDada(5) As String, xReturn As Variant
xDada(0) = "鈴木"
xDada(1) = "山田"
xDada(2) = "佐藤"
xDada(3) = "中村"
xDada(4) = "山本"
'"山 のつく名前をフィルタリングします"
xReturn = Filter(xDada, "山", True)
MsgBox Join(xReturn, vbCrLf)
      

Fix

数値の整数部分を返します※類似Int
Fix(number)
必要な 数値引数 は、 Double または任意 の有効な数値式です。 number に Null が含まれている場合は Null が返されます
        
記述凡例
Dim MyNumber
MyNumber = Int(99.8)    ' Returns 99.
MyNumber = Fix(99.2)    ' Returns 99.
                
MyNumber = Int(-99.8)    ' Returns -100.
MyNumber = Fix(-99.8)    ' Returns -99.
                
MyNumber = Int(-99.2)    ' Returns -100.
MyNumber = Fix(-99.2)    ' Returns -99.
      

Format

書式指定式の指示に従って書式設定される 式を含む Variant (String) を戻します
Format(Expression, [Format], [FirstDayOfWeek], [FirstWeekOfYear])
format を指定せずに数値を書式設定する場合、Format は Str 関数と同様の、ただし国際対応がされた機能を提供します。 しかし、Format を使用して文字列として書式設定された正の数値には、値の記号用に予約済みの先頭のスペースは含まれません。Str を使用して変換された数値では、先頭のスペースは保持されます
        
記述凡例
Dim MyTime, MyDate, MyStr
MyTime = #17:04:23#
MyDate = #January 27, 1993#
        
' Returns current system time in the system-defined long time format.
MyStr = Format(Time, "Long Time")
        
' Returns current system date in the system-defined long date format.
MyStr = Format(Date, "Long Date")
        
MyStr = Format(MyTime, "h:m:s")    ' Returns "17:4:23".
MyStr = Format(MyTime, "hh:mm:ss am/pm")    ' Returns "05:04:23 pm".
MyStr = Format(MyTime, "hh:mm:ss AM/PM")    ' Returns "05:04:23 PM".
MyStr = Format(MyDate, "dddd, mmm d yyyy")    ' Returns "Wednesday, Jan 27 1993".
' If format is not supplied, a string is returned.
MyStr = Format(23)    ' Returns "23".
        
' User-defined formats.
MyStr = Format(5459.4, "##,##0.00")    ' Returns "5,459.40".
MyStr = Format(334.9, "###0.00")    ' Returns "334.90".
MyStr = Format(5, "0.00%")    ' Returns "500.00%".
MyStr = Format("HELLO", "<")    ' Returns "hello".
MyStr = Format("This is it", ">")    ' Returns "THIS IS IT".
      

FormatCurrency

システムのコントロール パネルで定義された通貨記号を使用して、通貨値として書式設定された式を返します
FormatCurrency(Expression, [ NumDigitsAfterDecimal, [ IncludeLeadingDigit, [ UseParensForNegativeNumbers, [ GroupDigits ]]]])
省略可能な引数を省略した場合は、コンピューターの地域の設定の値が使用されます。 通貨値に対する通貨記号の位置は、システムの地域の設定によって決まります
        
記述凡例
Dim xReturn As String
xReturn = FormatCurrency(-1234.56, 1, , vbTrue, vbTrue)
'少数点以下の桁が 1、負は ( ) 表示、桁区切り表示あり、を指定していますので、戻り値は「(\1,234.6)」になります。少数点第二位の数値が四捨五入される為、少数点第一位の値は「6」になります
MsgBox xReturn
      

FormatDateTime

日付または時刻として書式設定された式を返します
FormatDateTime(Date, [ NamedFormat ])
        
記述凡例
 Dim d As Date
d = ("1958-01-29 00:25")
MsgBox ("General date format : " & FormatDateTime(d))
MsgBox ("Long date format : " & FormatDateTime(d, vbLongDate))
MsgBox ("Short date format : " & FormatDateTime(d, vbShortDate))
MsgBox ("Long time format : " & FormatDateTime(d, 3))
MsgBox ("Short time format : " & FormatDateTime(d, vbShortTime))
      

FormatNumber

数値として書式設定された式を返します
FormatNumber(Expression, [ NumDigitsAfterDecimal, [ IncludeLeadingDigit, [ UseParensForNegativeNumbers, [ GroupDigits ]]]])
省略可能な引数を省略した場合は、コンピューターの地域の設定の値が使用されます
        
記述凡例
testName = "Testx: positive, 2 decimals"
str2 = "12.20"
str1 = FormatNumber("12.2", 2, vbFalse, vbFalse, vbFalse)
MsgBox ("FormatNumber returned: " + str1 + ", Expected: " + str2)
      

FormatPercent

パーセンテージとして(100倍して)書式設定された式を、末尾に % 記号を追加して返します
FormatPercent(Expression, [ NumDigitsAfterDecimal, [ IncludeLeadingDigit, [ UseParensForNegativeNumbers, [ GroupDigits ]]]])
省略可能な引数を省略した場合は、コンピューターの地域の設定の値が使用されます
        
記述凡例

      

FreeFile

Open ステートメントで使用できる次の ファイル番号を表す Integer を返します
FreeFile [ (rangenumber) ]
オプションの rangenumber 引数は、どの範囲から次の空きファイル番号を返すかを指定する Variant です。 0 (既定値) を指定すると 1 以上 255 以下の範囲のファイル番号を返します。 1 を指定すると 256 以上 511 以下の範囲のファイル番号を返します
        
記述凡例
Dim MyIndex, FileNumber
For MyIndex = 1 To 5    ' Loop 5 times.
   FileNumber = FreeFile    ' Get unused file
   ' number.
   Open "TEST" & MyIndex For Output As #FileNumber    ' Create file name.
   Write #FileNumber, "This is a sample."    ' Output text.
   Close #FileNumber    ' Close file.
Next MyIndex
      

FV

定額の支払いを定期的に行い、利率が一定であると仮定して投資の将来価値を指定する Double を返します
FV(rate, nper, pmt, [ pv, [ type ]])
引数rate と nper は、同じ単位で表した支払期間を使用して計算する必要があります。 たとえば、rate を月単位で計算する場合は、nper も月単位で計算する必要があります。
すべての引数に関して、定額預金の支払いのような出金は負の数で表し、配当金のような入金は正の数で表します
        
記述凡例
Dim Fmt, Payment, APR, TotPmts, PayType, PVal, FVal
        Const ENDPERIOD = 0, BEGINPERIOD = 1    ' 支払い時期.
        Fmt = "###,###,##0.00"    ' お金の形式を定義する.
        Payment = InputBox("毎月いくら投資出来ますか?")
        APR = InputBox("予想金利年率を入力してください")
        If APR > 1 Then APR = APR / 100    ' 適切なフォームを確認してください.
        TotPmts = InputBox("何ヶ月継続できると思いますか?")
        PayType = MsgBox("月末に支払いをしますか?", vbYesNo)
        If PayType = vbNo Then PayType = BEGINPERIOD Else PayType = ENDPERIOD
        PVal = InputBox("現在の残高はいくらですか?")
        FVal = FV(APR / 12, TotPmts, -Payment, -PVal, PayType)
        MsgBox "あなたの投資は成果が有るでしょう" & Format(FVal, Fmt) & "."