Excel vba 批量修改指定路径下指定名称对应的值

Sub changeFile()
 '出错时直接跳到完成
  On Error GoTo 100
  Dim file As String
  Dim basePath As String
  Dim val
  basePath = InputBox("请输入路径")
  If basePath = "" Then
      MsgBox "请输入路径"
      Exit Sub
  End If
  val = InputBox("请输入你要修改成的值")
  '忽略修改警告
   Application.DisplayAlerts = False
  '查找某路径下面所有的txt文档并弹出文件名
  file = Dir("C:\Users\星驰太帅了\Desktop\excel\*.xlsx")
  a = SetValue(basePath, file, val)
  Debug.Print "根文件下面的文件   " & file
    '如果文件名不为空代表还有文件,那么就一直循环
    Do While file <> ""
     '第二次不需要再填写路径,要不然会造成死循环
     file = Dir
     '再判断一下,免得当为空时还做了操作
     If file = "" Then Exit Do
     a = SetValue(basePath, file, val)
     Debug.Print "根文件下面的文件   " & file
    Loop
  '结束语提示
     Debug.Print "end"
  '重新开启警告
   Application.DisplayAlerts = True
100:
    MsgBox "修改完成"

End Sub

Function SetValue(basePath, worksPath, value)
  Dim rowCount
  Dim c As Range
  filePath = basePath & worksPath
  With Workbooks.Open(filePath)
        '第一列最后一行
       rowCount = .Sheets(1).Cells(Rows.Count, 1).End(xlUp).row
       For Each c In Range("a1:a" & rowCount)
            If c.value = "编制日期:" Then
            .Sheets(1).Cells(c.row, 2).value = value
            Exit For
            End If
       Next
       .Save '修改完需要保存文件
       .Close
  End With

End Function



可以用find 函数更容易,如下


Function SetValue(basePath, worksPath, value)
  Dim c As Range
  Dim rowCount As Range
  filePath = basePath & worksPath
  With Workbooks.Open(filePath)
        '第一列最后一行
       Set rowCount = .Sheets(1).Cells.Find("编制日期:", , xlFormulas, , , xlPrevious)
       .Sheets(1).Cells(rowCount.row, 2).value = value
       .Save '修改完需要保存文件
       .Close
  End With

End Function


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值