Excel精英培训网

 找回密码
 注册
数据透视表40+个常用小技巧,让你一次学会!
查看: 2134|回复: 3

[已解决]能否用VBA实现提取磁盘容量的功能,谢谢爱疯老师!

[复制链接]
发表于 2016-6-9 08:00 | 显示全部楼层 |阅读模式
本帖最后由 lhj323323 于 2016-6-10 23:01 编辑

老师端午节快乐!

我想实现如下效果:
1、本模板所在的电脑(指台式电脑)的硬盘内一共有几个区(不包含光盘驱动器);
2、每个区的【已用空间】和【可用空间】
3、通过EXCEL的VBA程序把上述信息导入到sheet2工作表中

先谢谢各位老师了,(没有上传EXCEL模板)

我需要的效果是这样:
快照2.png
最佳答案
2016-6-9 08:54
Sub test()
    Dim fso As Object, dri As Object
    Dim i As Integer

    Range("a1").CurrentRegion.Clear
    i = 1
    Cells(i, 1).Resize(1, 3) = Array("盘符", "已用空间", "容量")
    Set fso = CreateObject("Scripting.FileSystemObject")
    For Each dri In fso.Drives
        If dri.IsReady Then
            i = i + 1
            Cells(i, 1) = dri.DriveLetter    '盘符
            Cells(i, 2) = Format((dri.TotalSize - dri.AvailableSpace) / 1024 ^ 3, "0.0G")    '已用空间
            Cells(i, 3) = Format(dri.TotalSize / 1024 ^ 3, "0G")    '容量
        End If
    Next
End Sub
 楼主| 发表于 2016-6-9 08:07 | 显示全部楼层
本帖最后由 lhj323323 于 2016-6-9 08:09 编辑

这是我在本论坛搜索到的不解木野狐老师的语句

Sub 磁盘信息()
    Dim 盘符 As String, 类型 As String
    For i = 1 To 26
        On Error Resume Next
        盘符 = Mid("ABCDEFGHIJKLMNOPQRSTUVWXYZ", i, 1)
        Select Case CreateObject("Scripting.FileSystemObject").GetDrive(盘符 & ":").DriveType
        Case 0: 类型 = "无法识别"
        Case 1: 类型 = "移动磁盘"
        Case 2: 类型 = "固定磁盘"
        Case 3: 类型 = "网络磁盘"
        Case 4: 类型 = "光盘DVD"
        Case 5: 类型 = "虚拟磁盘"
        End Select
        If Err.Number <> 68 Then
            msg = msg & CreateObject("Scripting.FileSystemObject").GetDrive(盘符 & ":").DriveLetter & "   " & 类型 & "   " & CreateObject("Scripting.FileSystemObject").GetDrive(盘符 & ":").SerialNumber & "   " & CreateObject("Scripting.FileSystemObject").GetDrive(盘符 & ":").TotalSize / 1024 & "   " & CreateObject("Scripting.FileSystemObject").GetDrive(盘符 & ":").FreeSpace / 1024 & Chr(10)
        End If
    Next i
    MsgBox msg
End Sub

但显示的各磁盘的容量与实际并不相符

请看附图
快照3.png
回复

使用道具 举报

发表于 2016-6-9 08:54 | 显示全部楼层    本楼为最佳答案   
Sub test()
    Dim fso As Object, dri As Object
    Dim i As Integer

    Range("a1").CurrentRegion.Clear
    i = 1
    Cells(i, 1).Resize(1, 3) = Array("盘符", "已用空间", "容量")
    Set fso = CreateObject("Scripting.FileSystemObject")
    For Each dri In fso.Drives
        If dri.IsReady Then
            i = i + 1
            Cells(i, 1) = dri.DriveLetter    '盘符
            Cells(i, 2) = Format((dri.TotalSize - dri.AvailableSpace) / 1024 ^ 3, "0.0G")    '已用空间
            Cells(i, 3) = Format(dri.TotalSize / 1024 ^ 3, "0G")    '容量
        End If
    Next
End Sub
回复

使用道具 举报

 楼主| 发表于 2016-6-10 23:00 | 显示全部楼层
爱疯 发表于 2016-6-9 08:54
Sub test()
    Dim fso As Object, dri As Object
    Dim i As Integer

谢谢爱疯老师!

今天研究这个东西一整天了,还是入不了门。

快照3.png
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

小黑屋|手机版|Archiver|Excel精英培训 ( 豫ICP备11015029号 )

GMT+8, 2024-4-25 08:54 , Processed in 0.177827 second(s), 9 queries , Gzip On, Yac On.

Powered by Discuz! X3.4

Copyright © 2001-2020, Tencent Cloud.

快速回复 返回顶部 返回列表