ExcelHome技术论坛

 找回密码
 免费注册

QQ登录

只需一步,快速开始

快捷登录

搜索
EH技术汇-专业的职场技能充电站 妙哉!函数段子手趣味讲函数 Excel服务器-会Excel,做管理系统 Excel Home精品图文教程库
HR薪酬管理数字化实战 Excel 2021函数公式学习大典 Excel数据透视表实战秘技 打造核心竞争力的职场宝典
让更多数据处理,一键完成 数据工作者的案头书 免费直播课集锦 ExcelHome出品 - VBA代码宝免费下载
用ChatGPT与VBA一键搞定Excel WPS表格从入门到精通 Excel VBA经典代码实践指南
楼主: jsgj2023

[分享] 常用代码归集

  [复制链接]

TA的精华主题

TA的得分主题

 楼主| 发表于 2017-2-13 16:00 | 显示全部楼层
Sub sql提取指定条件的数据()
Dim cnn As New ADODB.Connection
Dim rs As New ADODB.Recordset
Dim myCnnstr As String
Dim sql As String
Dim myfilename  As String
Dim i As Long
ActiveSheet.Cells.Clear
myfilename = "Adele.csv"
myCnnstr = "Driver={Microsoft Text Driver (*.txt; *.csv)};" & "DBQ=" & ThisWorkbook.Path & "\;"
cnn.Open "Provider=MSDASQL;" & myCnnstr
    sql = "select 姓名,班级,数学,语文 from " & myfilename _
    & " where 数学>=90 and 语文>=90"
    rs.Open sql, cnn, adOpenKeyset, adLockOptimistic
       For i = 1 To rs.Fields.Count
        Cells(1, i).Value = rs.Fields(i - 1).Name
    Next
    Range("a2").CopyFromRecordset rs
    rs.Close
    cnn.Close
    Set rs = Nothing
    Set cnn = Nothing
End Sub

TA的精华主题

TA的得分主题

 楼主| 发表于 2017-2-14 10:52 | 显示全部楼层
Sub 苏宁系统数量和金额匹配_以原始数据为基础()
If MsgBox("请选择苏宁系统各门店当期销售金额汇总工作簿," _
& "确保该簿中有《合并结果》表!", vbYesNo + vbQuestion + vbDefaultButton1) = vbYes Then
    GoTo 100
Else
    Exit Sub
End If
100:
strfind = Application.InputBox("请输入开始日期:", Type:=1)
Dim d As Object, sh As Worksheet
Dim arr, brr, crr(), wb As Workbook
Dim x&, y&, z&, k&
Dim i&, j&, n&
Application.ScreenUpdating = False
Set d = CreateObject("scripting.dictionary")
Set dnow = CreateObject("scripting.dictionary")
With Application.FileDialog(msoFileDialogFilePicker)
    .AllowMultiSelect = False
    If .Show Then p = .SelectedItems(1) Else: Exit Sub
End With
With GetObject(p)
    arr = .Sheets("合并结果").Range("a1").CurrentRegion
    .Close False
    For x = 2 To UBound(arr)
        If arr(x, 13) > strfind Then
            sell = arr(x, 10) & "+" & arr(x, 13) & "+" & arr(x, 16)
            d(sell) = d(sell) + arr(x, 18)
        End If
    Next
End With
Set wb = ActiveWorkbook
With wb
    brr = .Sheets("合并结果").Range("a1").CurrentRegion
    Application.DisplayAlerts = False
    For Each sh In .Sheets
        If sh.Name = "提取结果" Then sh.Delete
    Next
    Application.DisplayAlerts = True
    For y = 2 To UBound(brr)
        nowsell = brr(y, 3) & "+" & brr(y, 1) & "+" & brr(y, 7)
        dnow(nowsell) = dnow(nowsell) + brr(y, 9)
    Next y
    anow = dnow.keys
    bnow = dnow.items
    ReDim crr(1 To UBound(anow) + 1, 1 To 3)
    For z = 0 To UBound(anow)
        k = k + 1
        crr(k, 1) = anow(z)
        crr(k, 2) = bnow(z)
    Next z
    For i = 1 To UBound(crr)
        If d.exists(crr(i, 1)) Then
            crr(i, 3) = d(crr(i, 1))
        End If
    Next i
    ReDim Preserve crr(1 To UBound(crr), 1 To UBound(crr) + 3)
    For j = 1 To UBound(crr)
        n = n + 1
        spl = Split(crr(j, 1), "+")
        crr(j, 4) = spl(0)
        crr(j, 5) = spl(1)
        crr(j, 6) = spl(2)
    Next j
    .Sheets.Add(after:=Sheets(Sheets.Count)).Name = "提取结果"
    With .Sheets("提取结果")
        .[a1].Resize(1, 6) = Array("三项集合", "数量", "金额", "门店代码", "销售时间", "商品名称")
        .[a2].Resize(UBound(crr), UBound(crr, 2)) = crr
    End With
End With
Application.ScreenUpdating = True
End Sub

TA的精华主题

TA的得分主题

 楼主| 发表于 2017-2-14 11:34 | 显示全部楼层
Sub 统计指定文本文件的行数和列数()
Dim cnn As New ADODB.Connection
Dim rs  As New ADODB.Recordset
Dim mycnnstr  As String
Dim sql As String
Dim myfilename As String
Dim n As Long
Dim m As Integer
ActiveSheet.Cells.Clear
myfilename = "Adele.csv"
mycnnstr = "driver={microsoft text driver (*.txt; *.csv)};" & "dbq=" & ThisWorkbook.Path & "\;"
sql = "select * from " & myfilename
cnn.Open "provider=msdasql;" & mycnnstr
rs.Open sql, cnn, adOpenKeyset, adLockOptimistic
n = rs.RecordCount
m = rs.Fields.Count
MsgBox "该文本文件的行数为:" & n & "列数为:" & m, vbInformation
rs.Close: cnn.Close
Set rs = Nothing: Set cnn = Nothing
End Sub

TA的精华主题

TA的得分主题

 楼主| 发表于 2017-2-14 11:45 | 显示全部楼层
Sub 指定文件读入表格_input()
Dim filename As Variant
Dim mytext As Variant
Dim marr()   As String
Dim i As Long
Dim j As Long
filename = ThisWorkbook.Path & "\Adele.csv"
j = 1
With Sheets("sheet1")
    .Cells.ClearContents
    Open filename For Input As #1
    Do While Not EOF(1)
        Line Input #1, mytext
        marr = Split(mytext, ",")
        For i = 0 To UBound(marr)
            .Cells(j, i + 1) = marr(i)
        Next i
        j = j + 1
    Loop
    Close #1
End With
End Sub

TA的精华主题

TA的得分主题

 楼主| 发表于 2017-2-14 11:53 | 显示全部楼层
Sub 保存文件为指定的文件名并删除已有的同名文件()
Dim myfilename As String
myfilename = "Adele.csv"
On Error Resume Next
Kill ThisWorkbook.Path & "\" & myfilename
On Error GoTo 0
Worksheets("Sheet1").Copy
ActiveWorkbook.SaveAs Filename:=ThisWorkbook.Path & "\" & myfilename, FileFormat:=xlCSV
MsgBox "保存成功!"
ActiveWorkbook.Close savechanges:=False
End Sub

TA的精华主题

TA的得分主题

 楼主| 发表于 2017-2-14 13:42 | 显示全部楼层
Sub xls格式转换为csv格式()
    Dim myfilename As String
    Dim mydataar() As Variant
    Dim mystr As String
    Dim i  As Long
    Dim finalrow As Long
    Dim j   As Long
    Dim finalcol As Long
    myfilename = "Adele.csv"
    On Error Resume Next
    Kill ThisWorkbook.Path & "\" & myfilename
    On Error GoTo 0
    finalrow = Range("a65536").End(3).Row
    finalcol = Range("iv1").End(xlToLeft).Column
    ReDim mydataar(1 To finalrow, 1 To finalcol)
    For i = 1 To finalrow
        For j = 1 To finalcol
            mydataar(i, j) = Cells(i, j).Value
        Next
    Next
    Open ThisWorkbook.Path & "\" & myfilename For Output As #1
    For i = 1 To UBound(mydataar, 1)
        mystr = ""
        For j = 1 To UBound(mydataar, 2)
            mystr = mystr & CStr(mydataar(i, j)) & ","
        Next
        mystr = Left(mystr, (Len(mystr) - 1))
        Print #1, mystr
    Next
    Close #1
    MsgBox "保存成功!"
End Sub

TA的精华主题

TA的得分主题

 楼主| 发表于 2017-2-14 15:37 | 显示全部楼层
Sub 苏宁系统数量和金额匹配_以原始数据为基础()
If MsgBox("请选择苏宁系统各门店当期销售金额汇总工作簿," _
& "确保该簿中有《合并结果》表!", vbYesNo + vbQuestion + vbDefaultButton1) = vbYes Then
    GoTo 100
Else
    Exit Sub
End If
100:
strfind = Application.InputBox("请输入当期销售报表的起始日期:", Type:=1)
Dim d As Object, sh As Worksheet
Dim arr, brr, crr(), wb As Workbook
Dim x&, y&, z&, k&
Dim i&, j&
Dim dStandard As Object
Dim arrStandard, xstd&, kFinal As Variant, sFinal As String
Dim dFinal  As Object, xFinal&
Dim arrFinal As Variant, n&, kk&, splFinal As Variant
Application.ScreenUpdating = False
Set d = CreateObject("scripting.dictionary")
Set dnow = CreateObject("scripting.dictionary")
With Application.FileDialog(msoFileDialogFilePicker)
    .AllowMultiSelect = False
    If .Show Then p = .SelectedItems(1) Else: Exit Sub
End With
With GetObject(p)
    arr = .Sheets("合并结果").Range("a1").CurrentRegion
    .Close False
    For x = 2 To UBound(arr)
        If arr(x, 13) > strfind Then
            If arr(x, 10) = "9019" Or arr(x, 10) = "8417" Then
                sell = arr(x, 10) & "+" & arr(x, 13) & "+" & arr(x, 16) '门店代码+销售时间+商品名称
                d(sell) = d(sell) + arr(x, 18)
            End If
        End If
    Next
End With
'sj门店代码  9019
'sm门店代码  8417
Set wb = ActiveWorkbook
With wb
    brr = .Sheets("合并结果").Range("a1").CurrentRegion
    Application.DisplayAlerts = False
    For Each sh In .Sheets
        If sh.Name = "提取结果" Then sh.Delete
    Next
    Application.DisplayAlerts = True
    For y = 2 To UBound(brr)
        If brr(y, 3) = "9019" Or brr(y, 3) = "8417" Then
            nowsell = brr(y, 3) & "+" & brr(y, 1) & "+" & brr(y, 7) '门店代码+销售时间+商品名称
            dnow(nowsell) = dnow(nowsell) + brr(y, 9)
        End If
    Next y
    anow = dnow.keys
    bnow = dnow.items
    ReDim crr(1 To UBound(anow) + 1, 1 To 3)
    For z = 0 To UBound(anow)
        k = k + 1
        crr(k, 1) = anow(z)
        crr(k, 2) = bnow(z)
    Next z
    For i = 1 To UBound(crr)
        If d.exists(crr(i, 1)) Then
            crr(i, 3) = d(crr(i, 1))
        End If
    Next i
    ReDim Preserve crr(1 To UBound(crr), 1 To UBound(crr) + 4)
    '==============型号标准数据=================
    Set dStandard = CreateObject("scripting.dictionary")
    With GetObject("C:\Users\Administrator\AppData\Roaming\Microsoft\AddIns" & "\单品名称和型号标准数据表.xlsx")
        arrStandard = .Sheets("苏宁系统结算平台型号整理-字典法").[a1].CurrentRegion
        .Close False
    End With
    For xstd = 2 To UBound(arrStandard)
        If Not dStandard.exists(arrStandard(xstd, 1)) Then
            dStandard(arrStandard(xstd, 1)) = arrStandard(xstd, 2)
        End If
    Next
    '==============型号标准数据=================
    For j = 1 To UBound(crr)
        spl = Split(crr(j, 1), "+")
        crr(j, 4) = spl(0)
        crr(j, 5) = spl(1)
        crr(j, 6) = spl(2)
        If dStandard.exists(crr(j, 6)) Then
            crr(j, 7) = dStandard(crr(j, 6))
        End If
    Next j
  '============对提取的金额和数量分类汇总=====================
      Set dFinal = CreateObject("scripting.dictionary")
      For xFinal = 1 To UBound(crr)
        sFinal = crr(xFinal, 4) & "+" & crr(xFinal, 7)
        If Not dFinal.exists(sFinal) Then
            dFinal(sFinal) = Array(crr(xFinal, 2), crr(xFinal, 3))
        Else
            kFinal = dFinal(sFinal)
            kFinal(0) = kFinal(0) + crr(xFinal, 2)
            kFinal(1) = kFinal(1) + crr(xFinal, 3)
            dFinal(sFinal) = kFinal
        End If
      Next
      afinal = dFinal.keys
      bfinal = dFinal.items
      ReDim arrFinal(1 To UBound(afinal) + 1, 1 To 4)
      For n = 0 To UBound(afinal)
        kk = kk + 1
        splFinal = Split(afinal(n), "+")
        arrFinal(kk, 1) = splFinal(0)
        arrFinal(kk, 2) = splFinal(1)
        arrFinal(kk, 3) = bfinal(n)(0)
        arrFinal(kk, 4) = bfinal(n)(1)
      Next
      '============对提取的金额和数量分类汇总=====================
    .Sheets.Add(after:=Sheets(Sheets.Count)).Name = "提取结果"
    With .Sheets("提取结果")
        .[a1].Resize(1, 4) = Array("门店代码", "商品名称", "数量", "金额")
        .[a2].Resize(UBound(arrFinal), UBound(arrFinal, 2)) = arrFinal
        .Range("a:g").EntireColumn.AutoFit
    End With
End With
Application.ScreenUpdating = True
End Sub

TA的精华主题

TA的得分主题

 楼主| 发表于 2017-2-14 15:48 | 显示全部楼层
[广告] VBA代码宝 - VBA编程加强工具 · VBA代码随查随用  · 内置多项VBA编程加强工具       ★ 免费下载 ★      ★使用手册
Sub 往指定的文本文件中写入数据()
Dim fso As Scripting.FileSystemObject
Dim mytxt As Scripting.TextStream
Dim myfile As String
myfile = ThisWorkbook.Path & "\FSOTest.txt"
Set fso = New Scripting.FileSystemObject
Set mytxt = fso.CreateTextFile(Filename:=myfile, overwrite:=True)
With mytxt
    .Write "我爱Adele"
    .Write "第一行" & vbCrLf
    .WriteBlankLines 5
    .WriteLine "第七行"
    .WriteLine "第八行"
    .Write "第9行" & vbCrLf & "第10行"
    .Close
End With
Set mytxt = Nothing
Set fso = Nothing
End Sub

TA的精华主题

TA的得分主题

 楼主| 发表于 2017-2-14 15:54 | 显示全部楼层
[广告] Excel易用宝 - 提升Excel的操作效率 · Excel / WPS表格插件       ★免费下载 ★       ★ 使用帮助
Sub 在指定文本文件的末尾插入新的数据()
Dim fso As Scripting.FileSystemObject
Dim f As Scripting.File
Dim mytxt  As Scripting.TextStream
Dim myfile As String
myfile = ThisWorkbook.Path & "\Adele.txt"
Set fso = New Scripting.FileSystemObject
Set f = fso.GetFile(myfile)
Set mytxt = f.OpenAsTextStream(ForAppending)
With mytxt
    .WriteLine "插入Adele的心中"
    .Close
End With
Set mytxt = Nothing
Set fso = Nothing

TA的精华主题

TA的得分主题

 楼主| 发表于 2017-2-14 16:01 | 显示全部楼层
Sub 将指定文本文件的数据导入excel()
Dim fso   As Scripting.FileSystemObject
Dim mytxt  As Scripting.TextStream
Dim myfile As String
Dim i As Long
ActiveSheet.Cells.Clear
myfile = ThisWorkbook.Path & "\Adele.txt"
Set fso = New Scripting.FileSystemObject
Set mytxt = fso.OpenTextFile(Filename:=myfile, IOMode:=ForReading)
With mytxt
    i = 1
    Do Until .AtEndOfStream
        Cells(i, 1) = .ReadLine
        i = i + 1
    Loop
    .Close
End With
Set mytxt = Nothing
Set fso = Nothing
End Sub
您需要登录后才可以回帖 登录 | 免费注册

本版积分规则

手机版|关于我们|联系我们|ExcelHome

GMT+8, 2024-7-7 19:13 , Processed in 0.041240 second(s), 5 queries , Gzip On, MemCache On.

Powered by Discuz! X3.4

© 1999-2023 Wooffice Inc.

沪公网安备 31011702000001号 沪ICP备11019229号-2

本论坛言论纯属发表者个人意见,任何违反国家相关法律的言论,本站将协助国家相关部门追究发言者责任!     本站特聘法律顾问:李志群律师

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