【问题标题】:EXCEL Save data into different workbook - VBAEXCEL将数据保存到不同的工作簿 - VBA
【发布时间】:2014-04-17 11:34:18
【问题描述】:

早安,

我有一张表格,要求用户输入数据,然后单击按钮将数据保存到数据库中。该数据库当前位于同一工作簿“不同工作表”中。

我基本上需要将此数据保存在我称之为“Consolidated.xlsx”的不同工作表中,该工作表可在不同文件夹“C:/reports/consolidates.xlsx”中使用,以便只有我可以访问它数据,没有其他人

如果你能帮忙,请告诉我

当前可通过以下链接获取文档: www.dropbox.com/s/3wea245lmek8hef/FormSheet.xls

谢谢

【问题讨论】:

  • 文件处理在 VBA 中可能有点棘手,但您所描述的听起来像是可行的。您能向我们展示您到目前为止所做的尝试吗?
  • 嗨,丹。如果您单击上面的链接,您可以找到我到目前为止的进度的副本。希望这可以帮助。谢谢朋友

标签: excel vba


【解决方案1】:

编辑 4/19:下面的代码已更新为写入本地“PartsData”表以及合并目标...您仍然需要确保“合并”文件中有一张表命名为“PartsData”:

Option Explicit
Sub UpdateLogWorksheet()

Dim historyWks As Worksheet, localWks As Worksheet, _
    inputWks As Worksheet, indexWks As Worksheet
Dim historyWb As Workbook
Dim MyWorksheets As New Collection
Dim nextRow As Long, oCol As Long
Dim myRng As Range, myCell As Range
Dim myCopy As String

'cells to copy from Input sheet - some contain formulas
myCopy = "D5,D7,D9,D11,D13"

'assign variables for easy reference
Set inputWks = ThisWorkbook.Worksheets("Input")
Set localWks = ThisWorkbook.Worksheets("PartsData")
Set historyWb = Workbooks.Open("C:\reports\consolidated.xlsx")
Set historyWks = historyWb.Worksheets("PartsData")

'put both target worksheets into a collection for an easy loop
MyWorksheets.Add Item:=localWks
MyWorksheets.Add Item:=historyWks

With historyWks
    nextRow = .Cells(.Rows.Count, "A").End(xlUp).Offset(1, 0).Row
End With

With inputWks
    Set myRng = .Range(myCopy)
    If Application.CountA(myRng) <> myRng.Cells.Count Then
        MsgBox "Please fill in all the cells!"
        Exit Sub
    End If
End With

'write results of form to both local parts data and consolidated parts data
For Each indexWks In MyWorksheets
    With indexWks
        With .Cells(nextRow, "A")
            .Value = Now
            .NumberFormat = "mm/dd/yyyy hh:mm:ss"
        End With
        .Cells(nextRow, "B").Value = Application.UserName
        oCol = 3
        For Each myCell In myRng.Cells
            indexWks.Cells(nextRow, oCol).Value = myCell.Value
            oCol = oCol + 1
        Next myCell
    End With
Next indexWks

historyWb.Save '<~ save and close the target workbook
historyWb.Close SaveChanges:=False

'clear input cells that contain constants
With inputWks
  On Error Resume Next
     With .Range(myCopy).Cells.SpecialCells(xlCellTypeConstants)
          .ClearContents
          Application.GoTo .Cells(1) ', Scroll:=True
     End With
  On Error GoTo 0
End With
End Sub

【讨论】:

  • 最后一件事,有没有办法将数据复制到新工作簿“Consolidated.xlsx”和当前工作簿的工作表“PartsData”中?
  • 你绝对可以做到。添加另一个工作表变量并将其分配给Set MySheet = ThisWorkbook.Worksheets("PartsData"),然后对MySheet 执行与historyWks 相同的操作
  • 谢谢丹。我试图同时在我地板上的几个人身上运行这个,但是当 2 人同时尝试保存时,只有 1 人通过。知道是否有任何解决方案吗?工作表位于共享云端硬盘上。
  • 我不知道有一种解决方案可以让多人同时尝试保存到同一个文件
  • 也许如果我将数据发送到访问db而不是excel,这在vba中很难做到吗?
猜你喜欢
  • 1970-01-01
  • 2022-10-30
  • 1970-01-01
  • 1970-01-01
  • 2017-08-24
  • 1970-01-01
  • 1970-01-01
  • 2013-08-10
  • 1970-01-01
相关资源
最近更新 更多