从最新文件导出数据时出现问题



我有一个问题,我的宏在Excel VBA。这是我的第一个宏…我有第一个文件,这里是按钮,用来打开另一个文件。在这另一个文件中,我做了一个UserForm,用户可以检查,在哪个区域将做某事。这就是我的问题的开始。我想要的,当用户检查区域,打开这一领域的最新文件在文件夹xd所以我foung代码和它的工作原理,下一个文件打开时,我想要分割的一部分这一最新文档的数量是和它也行,但我想这numba()+1添加到这个文件,在userform checkig面积的可能性,alsa后我想分裂和出口numba()关闭这个文件到另一个文件,从我出口numba(),但是当我做Workbooks(My Path&Latest File).Close SaveChanges=False, Vba显示一个错误。那么你能帮我解决这个问题吗?如何从打开最新文件导出此numba+1到此准确,我在哪里工作?

或者也许你有任何想法,我怎么能只导出这个最新的文件的名称而不打开它?然后,我将导出onlu名称,拆分它,并为这个文档创建下一个数字…下面我添加代码,谢谢你的帮助:)

Private Sub CommandButton1_Click()
Dim MyPath As String
Dim MyFile As String
Dim LatestFile As String
Dim LatestDate As Date
Dim LMD As Date

MyPath = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
If Right(MyPath, 1) <> "" Then MyPath = MyPath & ""
MyFile = Dir(MyPath & "*.xlsx", vbNormal)
If Len(MyFile) = 0 Then
MsgBox "No files were found...", vbExclamation
Exit Sub
End If
Do While Len(MyFile) > 0
LMD = FileDateTime(MyPath & MyFile)
If LMD > LatestDate Then
LatestFile = MyFile
LatestDate = LMD
End If
MyFile = Dir
Loop
Workbooks.Open MyPath & LatestFile

Dim numba() As String
numba() = Split(Range("I6"), "-")


Call NAZWA
Sub NAZWA()
This.Workbooks.Activate
Worksheets("Tabelle1").Activate
Range("I6") = "xx-xxxx-"
End Sub

请试试Workbooks(LatestFile).close

Workbookscollection只保留工作簿的名称,而不是其全名…

使用这个技巧:

Dim MyOpenWb As Workbook
Set MyOpenWb = Workbooks.Open(MyPath & LatestFile) 'set a reference to the opened workbook for later use
'access any worsheet/cell in that workbook like
MyOpenWb.Worksheets("Sheet1").Range("A1").Value = "write into Sheet1 cell A1"
'make sure every Range/Cells/Columns/Rows has a workbook/worksheet specified
'otherwise it is not clear where Excel should look for Range("I6")
Dim numba() As String
numba() = Split(MyOpenWb.Worksheets("Tabelle1").Range("I6"), "-")
'do your stuff here …
'Close it
MyOpenWb.Close SaveChanges:=True 'or False

打开工作簿时,将其设置为变量,例如MyOpenWb。然后,您可以使用此变量来访问工作簿并关闭它。因此,一旦打开它,您就再也不必处理它的名称或路径了。

避免使用.Select.Activate来访问工作簿和工作表,如下所示:

ThisWorkbook.Worksheets("Tabelle1").Range("I6").Value = "xx-xxxx-"

你可能从阅读中受益如何避免在Excel VBA中使用选择。

最新更新