Excel的宏不能記錄移至當(dāng)前行的第一個(gè)單元格的動(dòng)作(即你按下“Home”鍵的動(dòng)作),下面的語(yǔ)句則可以做到:
ActiveCell.Offset(0, -ActiveCell.Column + 1).Select
移至當(dāng)前列的第一個(gè)單元格:
ActiveCell.Offset( -ActiveCell.Row + 1,0).Select
關(guān)于If..Then...EndIf
如果只有一個(gè)條件及一個(gè)動(dòng)作,你可以用以下語(yǔ)句:
If Selection.Value > 10 Then
Selection.Offset(1,0) = 100
End If
或者更簡(jiǎn)單的:
If Selection.Value > 10 Then Selection.Offset(1,0) = 100
如果有兩個(gè)條件及兩個(gè)動(dòng)作,你可以用下面的語(yǔ)句
If Selection.Value > 10 Then
If Selection.Value = 12 Then
Selection.Offset(1,0) = 100
End If
Selection.Offset(1,0) = 20
End If
關(guān)于If..Then...And...EndIf
當(dāng)有雙重條件和一個(gè)動(dòng)作時(shí),你可以用下面的語(yǔ)句:
If Selection.Value = 10 And Selection.Offset(0,1).Value = 20 Then
Selection.Offset(1,0) = 100
End If
關(guān)于If..Then...Or...EndIf
當(dāng)有雙重條件和一個(gè)動(dòng)作時(shí),你可以用下面的語(yǔ)句:
If Selection.Value = 10 Or Selection.Offset(0,1).Value = 20 Then
Selection.Offset(1,0) = 100
End If
關(guān)于If..Then...Else...EndIf
當(dāng)只有一個(gè)條件和兩個(gè)動(dòng)作時(shí),你可以用下面的語(yǔ)句:
If Selection.Value > 10 Then
Selection.Offset(1,0) = 100
Else
Selection.Offset(1,0) = 0
End If
關(guān)于If..Then..ElseIf...EndIf
當(dāng)有不止一個(gè)條件,且每個(gè)條件都跟隨不同的動(dòng)作時(shí),你可以用下面的語(yǔ)句:
If Selection.Value = 1 Then
Selection.Offset(1, 0) = 10
ElseIf Selection.Value = 2 Then
Selection.Offset(1, 0) = 20
ElseIf Selection.Value = 3 Then
Selection.Offset(1, 0) = 30
ElseIf Selection.Value = 4 Then
Selection.Offset(1, 0) = 40
ElseIf Selection.Value = 5 Then
Selection.Offset(1, 0) = 50
End If
關(guān)于Select Case
當(dāng)你不得不測(cè)試很多條件,你可以用Select Case 語(yǔ)句來(lái)代替If Then..ElseIf 。語(yǔ)法如下:
Sub test()
Select Case Selection.Value
Case Is >= 85
Selection.Offset(0, 1) = "A"
Case Is >= 75
Selection.Offset(0, 1) = "B"
Case Is >= 65
Selection.Offset(0, 1) = "C"
Case Is >= 50
Selection.Offset(0, 1) = "D"
Case Else
Selection.Offset(0, 1) = "F"
End Select
End Sub
這段語(yǔ)句的意思就是:如果所選單元格的值大于85時(shí),則其右邊那個(gè)單元格的值為“A”…… 所選單元格的值小于50時(shí),其右邊那個(gè)單元格的值為“F”
這里有一些關(guān)于VBA函數(shù) LCase, Now(), UCase 的例子:
注意:很多EXCEL函數(shù)都可以以下面的形式用在VBA中:
varAnswer = Application.WorksheetFunction.Sum(Range("A1:A32"))
或者
varAnswer = Application.Sum(Range("A1:A32"))
LCase
當(dāng)對(duì)輸入的字符做判斷時(shí),我們無(wú)法知道用戶輸入的字符是大寫(xiě)還是小寫(xiě),用LCase函數(shù)可以將其轉(zhuǎn)化為小寫(xiě):
If LCase(Selection.value)= "toto" then...
or
Select Case LCase(Selection.value)
or
DO WHILE LCase(Selection.value)<>"toto"
NOW()
NOW() 既是Excel 函數(shù)也是VBA 函數(shù)。
通過(guò)下面的語(yǔ)句,在打開(kāi)工作簿時(shí),單元格 "A1"就會(huì)顯示為當(dāng)前時(shí)間:
Range("A1").Formula = "=Now()"
下面的語(yǔ)句則在執(zhí)行后賦予單元格“A1”當(dāng)前時(shí)間,該時(shí)間不會(huì)改變除非你再次執(zhí)行語(yǔ)句。并且你每次打開(kāi)工作簿后,單元格“A1”的值不會(huì)改變。
Range("A1").Value = Now()
UCase
當(dāng)對(duì)輸入的字符做判斷時(shí),我們無(wú)法知道用戶輸入的字符是大寫(xiě)還是小寫(xiě),用LCase函數(shù)可以將其轉(zhuǎn)化為大寫(xiě):
If UCase(Selection.value)= "TOTO" then...
or
Select Case UCase(Selection.value)
or
DO WHILE UCase(Selection.value)<>"TOTO"
聯(lián)系客服