zoukankan      html  css  js  c++  java
  • 学习VBAVBA常用功能方法(一)

    一下提供一些VBA经常用的函数调用:

    代码
    1 Private Declare Function RegOpenKeyA Lib "ADVAPI32.DLL" (ByVal hKey As Long, ByVal sSubKey As String, ByRef hkeyResult As Long) As Long
    2 Private Declare Function RegCloseKey Lib "ADVAPI32.DLL" (ByVal hKey As Long) As Long
    3 Private Declare Function RegSetValueExA Lib "ADVAPI32.DLL" (ByVal hKey As Long, ByVal sValueName As String, ByVal dwReserved As Long, ByVal dwType As Long, ByVal sValue As String, ByVal dwSize As Long) As Long
    4 Private Declare Function RegCreateKeyA Lib "ADVAPI32.DLL" (ByVal hKey As Long, ByVal sSubKey As String, ByRef hkeyResult As Long) As Long
    5 Private Declare Function RegQueryValueExA Lib "ADVAPI32.DLL" (ByVal hKey As Long, ByVal sValueName As String, ByVal dwReserved As Long, ByRef lValueType As Long, ByVal sValue As String, ByRef lResultLen As Long) As Long
    6
    7 Function GetRegistry(Key, Path, ByVal ValueName As String)
    8 Dim hKey As Long
    9 Dim lValueType As Long
    10 Dim sResult As String
    11 Dim lResultLen As Long
    12 Dim ResultLen As Long
    13 Dim x, TheKey As Long
    14
    15 TheKey = -99
    16 Select Case UCase(Key)
    17 Case "HKEY_CLASSES_ROOT": TheKey = &H80000000
    18 Case "HKEY_CURRENT_USER": TheKey = &H80000001
    19 Case "HKEY_LOCAL_MACHINE": TheKey = &H80000002
    20 Case "HKEY_USERS": TheKey = &H80000003
    21 Case "HKEY_CURRENT_CONFIG": TheKey = &H80000004
    22 Case "HKEY_DYN_DATA": TheKey = &H80000005
    23 End Select
    24
    25 If TheKey = -99 Then
    26 GetRegistry = "Not Found"
    27 Exit Function
    28 End If
    29
    30 If RegOpenKeyA(TheKey, Path, hKey) <> 0 Then _
    31 x = RegCreateKeyA(TheKey, Path, hKey)
    32
    33 sResult = Space(100)
    34 lResultLen = 100
    35
    36 x = RegQueryValueExA(hKey, ValueName, 0, lValueType, _
    37 sResult, lResultLen)
    38
    39 Select Case x
    40 Case 0: GetRegistry = Left(sResult, lResultLen - 1)
    41 Case Else: GetRegistry = "Not Found"
    42 End Select
    43
    44 RegCloseKey hKey
    45 End Function
    46
    47 Function WriteRegistry(ByVal Key As String, _
    48 ByVal Path As String, ByVal entry As String, _
    49 ByVal value As String)
    50
    51 Dim hKey As Long
    52 Dim lValueType As Long
    53 Dim sResult As String
    54 Dim lResultLen As Long
    55
    56 TheKey = -99
    57 Select Case UCase(Key)
    58 Case "HKEY_CLASSES_ROOT": TheKey = &H80000000
    59 Case "HKEY_CURRENT_USER": TheKey = &H80000001
    60 Case "HKEY_LOCAL_MACHINE": TheKey = &H80000002
    61 Case "HKEY_USERS": TheKey = &H80000003
    62 Case "HKEY_CURRENT_CONFIG": TheKey = &H80000004
    63 Case "HKEY_DYN_DATA": TheKey = &H80000005
    64 End Select
    65
    66 If TheKey = -99 Then
    67 WriteRegistry = False
    68 Exit Function
    69 End If
    70
    71 If RegOpenKeyA(TheKey, Path, hKey) <> 0 Then
    72 x = RegCreateKeyA(TheKey, Path, hKey)
    73 End If
    74
    75 x = RegSetValueExA(hKey, entry, 0, 1, value, Len(value) + 1)
    76 If x = 0 Then WriteRegistry = True Else WriteRegistry = False
    77 End Function
    78
    79  '取得文件夹里文档的数目
    80  Sub tutorial_5_1()
    81 Dim dirStr As String
    82 Dim FileCount As Long
    83 dirStr = "c:\"
    84 With New IWshRuntimeLibrary.FileSystemObject
    85 FileCount = .GetFolder(dirStr).Files.Count
    86 End With
    87 MsgBox FileCount, vbInformation
    88 End Sub
    89
    90  '取得文件夹子目录数目
    91  Sub tutorial_5_2()
    92 Dim dirStr As String
    93 Dim FileCount As Long
    94 dirStr = "c:\"
    95 With New IWshRuntimeLibrary.FileSystemObject
    96 FileCount = .GetFolder(dirStr).SubFolders.Count
    97 End With
    98 MsgBox FileCount, vbInformation
    99 End Sub
    100
    101 '取得磁盘可用容量
    102 Sub tutorial_5_3()
    103 Dim myDrive As IWshRuntimeLibrary.Drive
    104 Dim i As Long
    105 Dim myValue() As Variant
    106 Const fletter As Long = 1
    107 Const ffreespace As Long = 2
    108 With New IWshRuntimeLibrary.FileSystemObject
    109 ReDim myValue(1 To .Drives.Count, fletter To ffreespace) As Variant
    110 For Each myDrive In .Drives
    111 i = i + 1
    112 With myDrive
    113 myValue(i, fletter) = .DriveLetter
    114 If .IsReady Then myValue(i, ffreespace) = .FreeSpace
    115 End With
    116 Next
    117 End With
    118 For i = 1 To UBound(myValue, 1)
    119
    120 MsgBox myValue(i, fletter) & " : " & Format(myValue(i, ffreespace), "#,##0")
    121 Next i
    122 End Sub
    123
    124 '取得系统文件夹
    125 Sub tutorial_5_4()
    126 Dim mypath As String
    127 With New IWshRuntimeLibrary.FileSystemObject
    128 mypath = .GetSpecialFolder(SystemFolder)
    129 End With
    130 MsgBox mypath, vbInformation
    131 End Sub
    132
    133 '取得桌面路径
    134 Sub tutorial_5_5()
    135 Dim mypath As String
    136 With New IWshRuntimeLibrary.WshShell
    137 mypath = .SpecialFolders("Desktop")
    138 End With
    139 MsgBox mypath, vbInformation
    140 End Sub
    141
    142 '取得电脑名称
    143 Sub tutorial_5_6()
    144 Dim myStr As String
    145 With New IWshRuntimeLibrary.WshNetwork
    146 myStr = .ComputerName
    147 End With
    148 MsgBox myStr, vbInformation
    149 End Sub
    150
    151 '使用者名称
    152 Sub tutorial_5_7()
    153 Dim myStr As String
    154 With New IWshRuntimeLibrary.WshNetwork
    155 myStr = .UserName
    156 End With
    157 MsgBox myStr, vbInformation
    158 End Sub
    159
    160 '复制档案
    161 Sub tutorial_5_8()
    162 FileCopy "C:\temp.csv", "C:\temp.xls"
    163 End Sub
    164
    165 '重命名档案
    166 Sub tutorial_5_9()
    167 Name "C:\temp.xls" As "C:\temp2.xls"
    168 End Sub
    169
    170 '复制资料夹
    171 Sub tutorial_5_10()
    172 Dim fso As Object
    173 Dim FromPath As String
    174 Dim ToPath As String
    175 FromPath = "C:\swsetup"
    176 ToPath = "C:\swsetup2"
    177 Set fso = CreateObject("scripting.filesystemobject")
    178 fso.CopyFolder Source:=FromPath, Destination:=ToPath
    179 End Sub
    180
    181 '重命名资料夹
    182 Sub tutorial_5_11()
    183 Dim fso As Object
    184 Dim FromPath As String
    185 Dim ToPath As String
    186 FromPath = "C:\swsetup"
    187 ToPath = "C:\swsetup1"
    188 Set fso = CreateObject("scripting.filesystemobject")
    189 If fso.FolderExists(FromPath) = False Then
    190 MsgBox FromPath & " doesn't exist"
    191 Exit Sub
    192 End If
    193 If fso.FolderExists(ToPath) = True Then
    194 MsgBox ToPath & " exist, not possible to move to a existing folder"
    195 Exit Sub
    196 End If
    197 fso.MoveFolder Source:=FromPath, Destination:=ToPath
    198 End Sub
    199
    200 '删除档案
    201 Sub tutorial_5_12()
    202 On Error Resume Next
    203 Kill "C:\swsetup\SP31858A\*.*"
    204 On Error GoTo 0
    205 End Sub
    206
    207 '删除指定类型档案
    208 Sub tutorial_5_13()
    209 On Error Resume Next
    210 Kill "C:\swsetup\SP31858A\*.xl*"
    211 On Error GoTo 0
    212 End Sub
    213
    214 '暂存资料夹
    215 Sub tutorial_5_14()
    216 MsgBox Environ("Temp")
    217 End Sub
    218
    219 '列出已开启的项目
    220 Sub tutorial_5_15()
    221 Dim WD, task, N As Long
    222 Set WD = CreateObject("Word.Application")
    223 For Each task In WD.Tasks
    224 If task.Visible = True Then
    225 N = N + 1
    226 Cells(N, 1) = task.Name
    227 End If
    228 Next
    229 WD.Quit
    230 Set WD = Nothing
    231 End Sub
    232
    233 '讲ie关闭
    234 Sub tutorial_5_16()
    235 Dim WD
    236 Set WD = CreateObject("Word.Application")
    237 If WD.Tasks.Exists("Internet Explorer") Then
    238 WD.Tasks("Internet Explorer").Close
    239 End If
    240 WD.Quit
    241 Set WD = Nothing
    242 End Sub
    243
    244 '播放音乐
    245 Sub tutorial_5_17()
    246 FullFileName = "C:\Windows\media\ringin.wav"
    247 ActiveWorkbook.FollowHyperlink Address:=FullFileName
    248 End Sub
    249
    250 '判断工资表是否已经存在
    251 Function tutorial_5_18(sname) As Boolean
    252 Dim x As Object
    253 On Error Resume Next
    254 Set x = ActiveWorkbook.Sheets(sname)
    255 If Err = 0 Then SheetExists = True _
    256 Else SheetExists = False
    257 End Function
    258
    259 '判断workbook是否已经开启
    260 Function tutorial_5_19(wbname) As Boolean
    261 Dim x As Workbook
    262 On Error Resume Next
    263 Set x = Workbooks(wbname)
    264 If Err = 0 Then WorkbookIsOpen = True _
    265 Else WorkbookIsOpen = False
    266 End Function
    267
    268 '到Gmail
    269 Sub tutorial_5_20()
    270 With CreateObject("InternetExplorer.Application")
    271 .Visible = True
    272 .navigate "http://www.gmail.com"
    273 Do Until .readyState = 4
    274 DoEvents
    275 Loop
    276 .document.Forms(0).all("email").value = "id"
    277 .document.Forms(0).all("passwd").value = "password"
    278 .document.Forms(0).all("signIn").Click
    279 End With
    280 End Sub
    281
    282 '到QQ
    283 Sub tutorial_5_21()
    284 With CreateObject("InternetExplorer.Application")
    285 .Visible = True
    286 .navigate "http://www.huaxiafax.com/"
    287 Do Until .readyState = 4
    288 DoEvents
    289 Loop
    290 .document.Forms(0).all("usernameshow").value = "id"
    291 .document.Forms(0).all("pwshow").value = "password"
    292 End With
    293 End Sub
    294
    295 '状态栏
    296 Sub tutorial_5_22()
    297 Application.StatusBar = "信息写在这"
    298 End Sub
    299
    300 '压缩ZIP
    301 Sub tutorial_5_23()
    302 Dim ShellApp As Object
    303 Dim FileNameZip As Variant
    304 Dim FileNames As Variant
    305 Dim i As Long, FileCount As Long
    306
    307 FileNames = Application.GetOpenFilename(FileFilter:="All Files (*.*),*.*", FilterIndex:=1, Title:="Select the files to ZIP", MultiSelect:=True)
    308
    309 If Not IsArray(FileNames) Then Exit Sub
    310
    311 FileCount = UBound(FileNames)
    312 FileNameZip = Application.DefaultFilePath & "\compressed.zip"
    313
    314 Open FileNameZip For Output As #1
    315 Print #1, Chr$(80) & Chr$(75) & Chr$(5) & Chr$(6) & String(18, 0)
    316 Close #1
    317
    318 Set ShellApp = CreateObject("Shell.Application")
    319 For i = LBound(FileNames) To UBound(FileNames)
    320 ShellApp.Namespace(FileNameZip).CopyHere FileNames(i)
    321 Next i
    322
    323 On Error Resume Next
    324 Do Until ShellApp.Namespace(FileNameZip).items.Count = FileCount
    325 Application.Wait (Now + TimeValue("0:00:01"))
    326 Loop
    327
    328 If MsgBox(FileCount & " files were zipped to:" & vbNewLine & FileNameZip & vbNewLine & vbNewLine & "View the zip file?", vbQuestion + vbYesNo) = vbYes Then
    329 Shell "Explorer.exe /e," & FileNameZip, vbNormalFocus
    330 End If
    331 End Sub
    332
    333 '解压Unzip
    334 Sub tutorial_5_24()
    335 Dim ShellApp As Object
    336 Dim TargetFile
    337 Dim ZipFolder
    338
    339 TargetFile = Application.GetOpenFilename(FileFilter:="Zip Files (*.zip), *.zip")
    340 If TargetFile = False Then Exit Sub
    341
    342 ZipFolder = Application.DefaultFilePath & "\Unzipped\"
    343
    344 On Error Resume Next
    345 RmDir ZipFolder
    346 MkDir ZipFolder
    347 On Error GoTo 0
    348
    349 Set ShellApp = CreateObject("Shell.Application")
    350 ShellApp.Namespace(ZipFolder).CopyHere _
    351 ShellApp.Namespace(TargetFile).items
    352
    353 If MsgBox("The files was unzipped to:" & vbNewLine & ZipFolder & vbNewLine & vbNewLine & "View the folder?", vbQuestion + vbYesNo) = vbYes Then
    354 Shell "Explorer.exe /e," & ZipFolder, vbNormalFocus
    355 End If
    356 End Sub
    357
    358 '更新注册UpdateReg
    359 Sub tutorial_5_25()
    360 RootKey = "hkey_current_user"
    361 Path = "software\Compal\VBA\ABO_FAI"
    362 RegEntry = "FilePath"
    363 RegVal = "U:\E-Bidding Project\"
    364
    365 Call WriteRegistry(RootKey, Path, RegEntry, RegVal)
    366 End Sub
    367
    368 '获取注册GetReg
    369 Sub tutorial_5_26()
    370 RootKey = "hkey_current_user"
    371 Path = "software\Compal\VBA\ABO_FAI"
    372 RegEntry = "FilePath"
    373 MsgBox GetRegistry(RootKey, Path, RegEntry), vbInformation, Path & "\RegEntry"
    374 End Sub
    375
    376 '连接网络(局域网)磁盘
    377 Sub tutorial_5_27()
    378 Dim myWshNw As WshNetwork
    379 Set myWshNw = CreateObject("Wscript.Network")
    380 myWshNw.MapNetworkDrive "H:", "\\10.128.2.19\Download"
    381 End Sub
    382
    383 '中断网络磁盘
    384 Sub tutorial_5_28()
    385 Dim myWshNw As WshNetwork
    386 Set myWshNw = CreateObject("Wscript.Network")
    387 myWshNw.RemoveNetworkDrive "H:"
    388 End Sub
    389
    390 'Mail选择的区块
    391 Sub tutorial_5_29()
    392 Dim Rng As Range
    393 Dim OutApp As Object
    394 Dim OutMail As Object
    395
    396 Set Rng = Nothing
    397 On Error Resume Next
    398 Set Rng = Selection.SpecialCells(xlCellTypeVisible)
    399 On Error GoTo 0
    400
    401 If Rng Is Nothing Then
    402 MsgBox "The selection is not a range or the sheet is protected" & vbNewLine & "please correct and try again.", vbOKOnly
    403 Exit Sub
    404 End If
    405
    406 With Application
    407 .EnableEvents = False
    408 .ScreenUpdating = False
    409 End With
    410
    411 Set OutApp = CreateObject("Outlook.Application")
    412 OutApp.Session.Logon
    413 Set OutMail = OutApp.CreateItem(0)
    414
    415 On Error Resume Next
    416 With OutMail
    417 .To = "shengming_lee@compal.com"
    418 .CC = ""
    419 .BCC = ""
    420 .Subject = "This is the Subject line"
    421 .HTMLBody = RangetoHTML(Rng)
    422 .Send
    423 End With
    424 On Error GoTo 0
    425
    426 With Application
    427 .EnableEvents = True
    428 .ScreenUpdating = True
    429 End With
    430
    431 Set OutMail = Nothing
    432 Set OutApp = Nothing
    433 End Sub
    434 Function RangetoHTML(Rng As Range)
    435 Dim fso As Object
    436 Dim ts As Object
    437 Dim TempFile As String
    438 Dim TempWB As Workbook
    439
    440 TempFile = Environ$("temp") & "/" & Format(Now, "dd-mm-yy h-mm-ss") & ".htm"
    441
    442 Rng.Copy
    443 Set TempWB = Workbooks.Add(1)
    444 With TempWB.Sheets(1)
    445 .Cells(1).PasteSpecial Paste:=8
    446 .Cells(1).PasteSpecial xlPasteValues, , False, False
    447 .Cells(1).PasteSpecial xlPasteFormats, , False, False
    448 .Cells(1).Select
    449 Application.CutCopyMode = False
    450 On Error Resume Next
    451 .DrawingObjects.Visible = True
    452 .DrawingObjects.Delete
    453 On Error GoTo 0
    454 End With
    455
    456 With TempWB.PublishObjects.Add( _
    457 SourceType:=xlSourceRange, _
    458 Filename:=TempFile, _
    459 Sheet:=TempWB.Sheets(1).Name, _
    460 Source:=TempWB.Sheets(1).UsedRange.Address, _
    461 HtmlType:=xlHtmlStatic)
    462 .Publish (True)
    463 End With
    464
    465 Set fso = CreateObject("Scripting.FileSystemObject")
    466 Set ts = fso.GetFile(TempFile).OpenAsTextStream(1, -2)
    467 RangetoHTML = ts.ReadAll
    468 ts.Close
    469 RangetoHTML = Replace(RangetoHTML, "align=center x:publishsource=", _
    470 "align=left x:publishsource=")
    471
    472 TempWB.Close savechanges:=False
    473
    474 Kill TempFile
    475
    476 Set ts = Nothing
    477 Set fso = Nothing
    478 Set TempWB = Nothing
    479 End Function
    480
    481 '发送Mail,不跳出提示
    482 Sub tutorial_5_30()
    483 Dim iMsg As Object
    484 Dim iConf As Object
    485 Dim strbody As String
    486
    487 Set iMsg = CreateObject("CDO.Message")
    488 Set iConf = CreateObject("CDO.Configuration")
    489
    490 strbody = "Hi there" & vbNewLine & vbNewLine & _
    491 "This is line 1" & vbNewLine & _
    492 "This is line 2" & vbNewLine & _
    493 "This is line 3" & vbNewLine & _
    494 "This is line 4"
    495 iConf.Load -1
    496 Set Flds = iConf.Fields
    497 With Flds
    498 .Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
    499 .Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "webmail.compal.com"
    500 .Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
    501 .Update
    502 End With
    503
    504 With iMsg
    505 Set .Configuration = iConf
    506 .To = "shengming_lee@compal.com"
    507 .CC = ""
    508 .BCC = ""
    509 .From = """Shengming"" <shengming_lee@compal.com>"
    510 .Subject = "Important message"
    511 .TextBody = strbody
    512 .Send
    513 End With
    514 End Sub
    515
    516 '特定栏位找资料,并移除该栏位
    517 Sub tutorial_5_31()
    518 Dim FindString As String
    519 Dim Rng As Range
    520 FindString = InputBox("Enter a Search value")
    521 If Trim(FindString) <> "" Then
    522 With Sheets("Sheet2").Range("A:A")
    523 Set Rng = .Find(What:=FindString, _
    524 After:=.Cells(.Cells.Count), _
    525 LookIn:=xlValues, _
    526 LookAt:=xlWhole, _
    527 SearchOrder:=xlByRows, _
    528 SearchDirection:=xlNext, _
    529 MatchCase:=False)
    530 If Not Rng Is Nothing Then
    531 Application.Goto Rng, True
    532 Else
    533 MsgBox "Nothing found"
    534 End If
    535 End With
    536 End If
    537 End Sub
    538
    539 '回传数组范围
    540 Sub tutorial_5_32()
    541 t = Test
    542 MsgBox UBound(t, 1)
    543 MsgBox UBound(t, 2)
    544 End Sub
    545 Function Test() As Variant
    546 Dim CallerRows As Long
    547 Dim CallerCols As Long
    548 Dim CallerAddr As String
    549 Dim Result() As Long
    550 Dim N As Long
    551 Dim RowNdx As Long
    552 Dim ColNdx As Long
    553
    554 With Application.ActiveSheet
    555 CallerRows = .UsedRange.Rows.Count
    556 CallerCols = .UsedRange.Columns.Count
    557 End With
    558 ReDim Result(1 To CallerRows, 1 To CallerCols)
    559 For RowNdx = 1 To CallerRows
    560 For ColNdx = 1 To CallerCols
    561 N = N + 1
    562 Result(RowNdx, ColNdx) = N
    563 Next ColNdx
    564 Next RowNdx
    565 Test = Result
    566 End Function
    567

    我们使用一些功能的时候也要增加一些程序集vba增加程序集步骤:

    1.

    2.

    outlook:

    outlook代码:

    代码
    1 Set File_Search = Excel.Application.filesearch
    2 rPath = "d:\aa"
    3 查找文件夹aa下文件excel数量,
    4 With File_Search
    5 .NewSearch
    6 .fileName = "*.xls"
    7 .LookIn = rPath
    8 .SearchSubFolders = True
    9 .Execute msoSortByFileName, msoSortOrderAscending
    10 If .Execute > 0 Then
    11 filecount = .FoundFiles.count
    12 Else
    13 filecount = 0
    14 End If
    15 End With
    16 查找文件夹aa下文件csv数量,
    17 With File_Search
    18 .NewSearch
    19 .fileName = "*.csv"
    20 .LookIn = rPath
    21 .SearchSubFolders = True
    22 .Execute msoSortByFileName, msoSortOrderAscending
    23 If .Execute > 0 Then
    24 csvcount = .FoundFiles.count
    25 Else
    26 csvcount = 0
    27 End If
    28 End With
    29
    30 doYN = MsgBox("Please confirm you didn't select extra files about ESL,APCC." & vbCrLf & " Especially of ESL return files! ", vbYesNo, "Save file to this path ?")
    31 If doYN = vbYes Then
    32 Set fso = CreateObject("Scripting.FileSystemObject")
    33 If fso.FolderExists("d:\GDS_HUB_Report_Used_by_Rita") Then
    34 'Set f = fso.getFOLDER("d:\GDS_HUB_Report_Used_by_Rita") '判斷文件是否存在
    35 'fso.DeleteFolder ("d:\GDS_HUB_Report_Used_by_Rita")
    36 'If fso.getFOLDER("d:\GDS_HUB_Report_Used_by_Rita") Then
    37 If filecount > 0 Or csvcount > 0 Then
    38 删除所有文件
    39 Kill "D:\GDS_HUB_Report_Used_by_Rita\*.*"
    40 End If
    41 'End If
    42 'f.Delete
    43 'MkDir "D:\GDS_HUB_Report_Used_by_Rita"
    44 'Shell "del d:\GDS_HUB_Report_Used_by_Rita\*.*", 1
    45 Else
    46 MkDir "D:\GDS_HUB_Report_Used_by_Rita"
    47 End If
    48
  • 相关阅读:
    乔布斯《遗失的访谈》全文:尘封16年的预见
    Java开发超级工具集
    android root权限破解分析
    android linux 命令
    Dom加载让图片加载完再执行
    关于chrome dev tools一些技巧
    1 MySQL基础知识笔记
    教我SQL的老师
    SQL limit和offset的使用
    一次批量复制多个不同结果到剪贴板不用在粘贴文本与被粘贴文本之间反复横跳啦,
  • 原文地址:https://www.cnblogs.com/MR_ke/p/1677199.html
Copyright © 2011-2022 走看看