Excel 中怎么用VBA 删除指定文件夹中的指定文件?

发布于2022-01-13 20:14:26
4个回答
admin
网友回答2022-01-13
'你想删除的文件的名称例如文件名是中国什么省汇总.xls
FN = 中国什么省汇总.xls

Dim FileName As String

FileName = Dir(D:\报表\*.xls)
Do While FileName
If FileName = FN Then
Kill D:\报表\ & FileName
End If
FileName = Dir
Loop
admin
网友回答2022-01-13
为什么不用openrowset或者opendatasource?
admin
网友回答2022-01-13
要通过EXCEL查询指定数据库中的含 有指定字段的表名时,首先得知道查询SQL,查询SQL如下:
SELECT TABLE_NAME FROM INFORMATION_SCHEMA.COLUMNS where COLUMN_NAME='字段名'
如果要写成VBA的话,下面给你一段我写的宏,测试过了:
-----------
Sub 宏7()
' 宏7 宏
Application.CutCopyMode = False
With ActiveSheet.ListObjects.Add(SourceType:=0, Source:= _
ODBC;DRIVER=SQL Server;SERVER=服务器IP;UID=sa;;APP=Microsoft Office 2016;WSID=GUESS;DATABASE=要查询的数据库名 _
, Destination:=Range($A$1)).QueryTable
.CommandType = xlCmdSql
.CommandText = Array( _
SELECT TABLE_NAME & Chr(13) & & Chr(10) & FROM 要查询的数据库名.INFORMATION_SCHEMA.COLUMNS & Chr(13) & & Chr(10) & WHERE (COLUMN_NAME='要查询的字段名'))
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.PreserveColumnInfo = True
Dim chars As String
Dim rndstr As String
chars = ABCDEFGHJKLMNPQRSTUVWXYZ0123456789
Randomize
For i = 1 To 6
rndstr = rndstr & Mid(chars, Int(Rnd() * Len(chars) + 1), 1)
Next
.ListObject.DisplayName = rndstr
.Refresh BackgroundQuery:=False
End With
End Sub
最后结果如下图:
admin
网友回答2022-01-13
你在EXCEL中增加一个列名为ID,后在VBA中写以下代码,并引用Microsoft ActiveX Data Objects 2.8后执行

Public Sub 写入SQL2008()
Dim cnn As New ADODB.Connection
Dim SQL As String, mydata As String, mytable As String
Dim i%
mydata = KKKK '指定要修改的数据库
mytable = aaaa '指定数据表

'建立与指定SQL Server数据库的连接
cnn.ConnectionString = Provider=SQLOLEDB; _
& User ID=sa; _ 'sa改成你SQL账号(通常不用改)
& Password =123; _ '123改成你SQL2008密码
& Data Source=sowin; _ 'sowin改成你的SQL2008的电脑名,
'如sql2008在网络上,则sowin改成IP地址(如192.168.0.1)
& Initial Catalog = & mydata
cnn.Open
'查询全表某些字段的记录
for i = 2 to [a65536].end(xlup).row
SQL = UPDATE & mytable & SET x= & cells(i,1) & , & _
y= & cells(i,2) & , & _
z= & cells(i,3) & , & _
where id=11
next i
'注意引号里面的空格
'数据库没有更新的数据则用INSERT INTO
'SQL = INSERT INTO & mytable & COLUMNS(x,y,z) & _
VALUES(' & CELLS(i,1) & ',' & cells(i,2) & ',' & cells(i,3) &')

cnn.Execute(SQL)

cnn.Close
Set cnn = Nothing
End Sub

回到
顶部