使用Excel VBA更改closures的工作簿中单元格的值?

我目前在VBA中使用这个函数来获取封闭工作簿中单元格的值。 我想使用类似的过程来设置单元格的值为我想要的,而不打开文件。 那可能吗?

Private Function GetValue(path, file, sheet, ref) Dim arg As String If Right(path, 1) <> "\" Then path = path & "\" If Dir(path & file) = "" Then GetValue = "File Not Found" Exit Function End If arg = "'" & path & "[" & file & "]" & sheet & "'!" & _ Range(ref).Range("A1").Address(, , xlR1C1) GetValue = ExecuteExcel4Macro(arg) End Function 

是的,你可以使用ADO作为Gary的评论,但只有当你的Excel工作表安排在数据库结构。
这意味着你有有效的字段排列(有或没有标题)。
例如:

在这里输入图像说明

现在,您看到身份证号码12345有一个约翰·约翰的名字,你想把它更新为约翰·奈特
使用ADO你可以尝试:

编辑1:你可以做到这一点,而不使用Recordset 。 见下面的更新。

 Sub conscious() Dim con As ADODB.Connection Dim sqlstr As String, datasource As String Set con = New ADODB.Connection datasource = "C:\Users\UserName\Desktop\TestDataBase.xlsx" 'change to suit Dim sconnect As String sconnect = "Provider=Microsoft.ACE.OLEDB.12.0;" & _ "Data Source=" & datasource & ";" & _ "Extended Properties=""Excel 12.0;HDR=YES"";" With con .Open sconnect sqlstr = "UPDATE [Sheet1$] SET [Name] = ""John Knight"" WHERE [ID Number] = 12345" .Execute sqlstr .Close End With Set con = Nothing End Sub 

结果:

在这里输入图像描述

我不完全确定,如果这是你想要的,但HTH。

笔记:

  1. 您需要添加对Microsoft ActiveX数据对象XX库 (早期绑定)的引用。
  2. 但是你也可以使用迟绑定(无参考)来做到这一点。
  3. 连接string用于Excel 2007及以上。
  4. Sheet1是要更新值的目标工作表的名称。

编辑1:这是如何做到这一点,如果你的文件没有头

首先将连接stringHDR参数更改为NO :。

 sconnect = "Provider=Microsoft.ACE.OLEDB.12.0;" & _ "Data Source=" & datasource & ";" & _ "Extended Properties=""Excel 12.0;HDR=NO"";" 

然后调整你的SQLstring为:

 sqlstr = "UPDATE [Sheet1$] SET F2 = ""John Knight"" WHERE F1 = 12345" 

这就是场1的 F2场2的 F2