Having hard time with VBA while creating sheets from other workbook - vba

I have written this sort of code in VBA:
Sub itemselecter()
Dim Filename1 As String
Dim Sourcewb1 As Workbook
Dim Targetwb1 As Workbook
With Application.FileDialog(msoFileDialogFilePicker)
.AllowMultiSelect = False
If .Show = 0 Then
Exit Sub
Else
Filename1 = .SelectedItems(1)
Err.Clear
On Error GoTo 0
End If
End With
Application.ScreenUpdating = False
Set Sourcewb1 = Workbooks.Open(Filename1) 'Open FIC data
Set Targetwb1 = ThisWorkbook
Targetwb1.Worksheets("Data").ClearContents
Sourcewb1.Worksheets(1).Cells.Copy Destination:=Targetwb.Sheets("Data").Cells
Sourcewb1.Close (False)
Application.ScreenUpdating = True
End Sub
It gives me at the moment error 424, while trying to select the file from documents. What is wrong?

Try the code below, check for comments inside the code where I've made modifications.
If you would have added Option Explicit at the top of your code, then the second error wouldn't have occurred (where you mixed-up Targetwb with Targetwb1).
Code
Option Explicit
Sub itemselecter()
Dim Filename1 As String
Dim Sourcewb1 As Workbook
Dim Targetwb1 As Workbook
With Application.FileDialog(msoFileDialogFilePicker)
.AllowMultiSelect = False
If .Show = 0 Then
Exit Sub
Else
Filename1 = .SelectedItems(1)
Err.Clear
On Error GoTo 0
End If
End With
Application.ScreenUpdating = False
Set Sourcewb1 = Workbooks.Open(Filename1) 'Open FIC data
Set Targetwb1 = ThisWorkbook
Targetwb1.Worksheets("Data").Cells.ClearContents '<-- added .Cells to clear the worksheet's entire cells contents
Sourcewb1.Worksheets(1).Cells.Copy Destination:=Targetwb1.Sheets("Data").Cells '<-- need to be Targetwb1 not Targetwb
Sourcewb1.Close (False)
Application.ScreenUpdating = True
End Sub

Kindly change this line of code,
Targetwb1.Worksheets("Data").ClearContents
into something like
Targetwb1.Sheets("Data").Cells.ClearContents
Please let me suggest you to check if the sheet "Data" exists in that workbook.

Related

VBA to BROWSE & COPY Data from SELECTED DCM File in Excel

As you can figure out of the topic, I am struggeling at VBA. I want to build a Code with the function:
click on a button
search the DCM file
select file
Open the document in my excel
I realised a code, but I always get a debugg "9" at this line:
ThisWorkbook.Worksheets("Tabelle1").Range("A10").PasteSpecial xlPasteValues
If you may help me I would be very happy :) thanks.
CODE
Sub Get_Data_From_File()
Dim FileToOpen As Variant
Dim OpenBook As Workbook
Application.ScreenUpdating = False
FileToOpen = Application.GetOpenFilename(Title:="Browse for your File & Import Range", _
FileFilter:="DCM_Datei (*.DCM*),*dcm*")
If FileToOpen <> False Then
Set OpenBook = Application.Workbooks.Open(FileToOpen)
OpenBook.Sheets(1).Range("A:O").Copy
ThisWorkbook.Worksheets("Tabelle1").Range("A10").PasteSpecial xlPasteValues
OpenBook.Close False
End If
Application.ScreenUpdating = True
End Sub
try this i change structure of copy/paste method and declarate variable for main workbook and worksheet // not tested
Sub Get_Data_From_File()
Dim FileToOpen As Variant
Dim OpenBook As Workbook
dim wb as workbook, ws as worksheet
Application.ScreenUpdating = False
set wb = thisworkbook
set ws = wb.Worksheets("Tabelle1")
FileToOpen = Application.GetOpenFilename(Title:="Browse for your File & Import Range", FileFilter:="DCM_Datei (*.DCM*),*dcm*")
If FileToOpen <> False Then
Set OpenBook = Application.Workbooks.Open(FileToOpen)
OpenBook.Sheets(1).Range("A:O").Copy
ws.Range("A10").PasteSpecial Paste:=xlPasteValues
OpenBook.Close False
set OpenBook = nothing
End If
set wb = nothing
set ws = nothing
Application.ScreenUpdating = True
End Sub

Looping through dynamic sheet names

I am looping through a bunch of files in my folder and trying to copy a static column and paste to a master sheet. However every sheet I am looping through is a different name.
I believe this part of the code has to be changed:
xlsFiles.Sheets("Sheet3").Columns("20").Copy Destination:=wsMaster.Sheets("Sheet1").Range("A" & r).Offset(1, 0).
What can I use in place of sheets("Sheet3") ?
Here is the full code:
Option Explicit
Dim wsMaster As Workbook, csvFiles As Workbook
Dim Filename As String
Dim File As Integer
Dim r As Long
Public Sub Consolidate()
With Application
.ScreenUpdating = False
.EnableEvents = False
End With
With Application.FileDialog(msoFileDialogOpen)
.AllowMultiSelect = True
.Title = "Select files to process"
.Show
If .SelectedItems.Count = 0 Then Exit Sub
Set wsMaster = ActiveWorkbook
For File = 1 To .SelectedItems.Count
Filename = .SelectedItems.Item(File)
If Right(Filename, 5) = ".csv*" Then
Set csvFiles = Workbooks.Open(Filename, 0, True)
r = wsMaster.Sheets("Sheet1").UsedRange.Rows.Count
csvFiles.Sheets(1).Columns("col name").Copy Destination:=wsMaster.Sheets("Sheet1").Range("A" & r).Offset(1, 0)
csvFiles.Close SaveChanges:=False 'close without saving
End If
Next File 'go to the next file and repeat the process
End With
Set wsMaster = Nothing
Set csvFiles = Nothing
With Application
.ScreenUpdating = True
.EnableEvents = True
End With
End Sub
The answer you already got by #sktneer in the comments above.
You could shorten and "clean-up" your If section code a little, try the code below:
If Right(Filename, 5) = ".xls*" Then
Set xlsFiles = Workbooks.Open(Filename, 0, True)
r = wsMaster.Sheets("Sheet1").UsedRange.Rows.Count
xlsFiles.Sheets(3).Columns("20").Copy Destination:=wsMaster.Sheets("Sheet1").Range("A" & r).Offset(1, 0)
xlsFiles.Close SaveChanges:=False 'close without saving
End If

Getting Subscription out of range Error

Code is running well while checking if "Test_Worksheet" worksheet exists in workbook file opened by dialog. Workbook File is opening correctly & if "Test_Worksheet" sheet exists in that file then debug.print (in Sub ChkSalfile) give "Name is True".
But if sheet not available in Workbook, then "Subscription out of Range" error coming. Please help. My code is as below
Sub Main()
Dim salefor As Workbook
Dim salpathfileName As String, salfileName As String
Dim fd As Office.FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.AllowMultiSelect = False
.Title = "Please select file."
.Filters.Clear
.Filters.Add "Excel 2003", "*.xls?"
.InitialFileName = "*SAL*.*"
result4 = .Show
If (result4 <> 0) Then
salfileName = Dir(.SelectedItems(1))
salpathfileName = .SelectedItems(1)
Else
'if user pressed CANCEL - exit sub
Application.ScreenUpdating = True
MsgBox "User pressed CANCEL"
Exit Sub
End If
End With
Set salefor = Workbooks.Open(salfileName, ReadOnly:=True)
Call ChkSalfile(salfileName, salefor)
End Sub
Sub ChkSalfile (salfileName As String, salefor As Workbook)
Dim chksalsheet As String
chksalsheet = DoesWorkSheetExist("Test_Worksheet", salfileName)
If chksalsheet = True Then
Debug.Print "Name is " & chksalsheet
Else
Debug.Print "File not found"
End If
End Sub
Option Explicit
Public Function DoesWorkSheetExist(WorkSheetName As String, Optional WorkBookName As String)
Dim WS As Worksheet
On Error Resume Next
If WorkBookName = vbNullString Then
Set WS = Sheets(WorkSheetName)
Else
Set WS = Workbooks(WorkBookName).Sheets(WorkSheetName)
End If
On Error GoTo 0
DoesWorkSheetExist = Not WS Is Nothing
End Function
It seems that your settings in the VBA project editor are set to break on any errors. Change this setting to break only on unhandled errors:
Tools --> Options --> General Tab --> Error Trapping --> check "Break on Unhadled Errors"
That said, don't Dim your variable as a String when it is a Boolean:
Dim chksalsheet As Boolean ' <-- Not as String

VBA Excel not responding when copy data to another workbook

I use this simple code to copy my sheet from workbook 1 into workbook 2 in the same folder.
Sub Button27_Click()
Application.ScreenUpdating = False
Dim FileName As String
Workbooks.Open FileName:=ActiveWorkbook.Path & "\sefaresh.xlsm"
Application.Wait (Now + TimeValue("0:00:01"))
ThisWorkbook.Sheets("Sheet3").Copy
After:=Workbooks("sefaresh.xlsm").Sheets(Sheets.Count)
Application.ScreenUpdating = True
End Sub
The copy&paste function process successfully but if i close the workbook 2 first, i get not responding for excel. Any suggestion?
Thanks
Try this (Untested). You shouldn't get an error now.
Things become easier if you work with objects :)
Sub Button27_Click()
Dim wbThis As Workbook, wbThat As Workbook
Dim ws As Worksheet
Dim fName As String
On Error GoTo Whoa
Set wbThis = ThisWorkbook
Set ws = wbThis.Sheets("Sheet3")
fName = wbThis.Path & "\sefaresh.xlsm"
Application.ScreenUpdating = False
Set wbThat = Workbooks.Open(fName)
DoEvents
ws.Copy After:=wbThat.Sheets(wbThat.Sheets.Count)
'~~> close and save the workbook
wbThat.Close (True)
DoEvents '<~~ Give time for it to save and close
LetsContinue:
Application.ScreenUpdating = True
MsgBox "Done"
Exit Sub
Whoa:
MsgBox Err.Description
Resume LetsContinue
End Sub

Excel- VBA PasteSpecial Method of Range Class Failed

Excel macro is intended to copy a range from one workbook to another using FileToOpen. The same code worked earlier today in separate workbook.
Error generated is Runtime 1004' PasteSpecial Method of class failed. Here's the section that fails:
SrcWB.Worksheets("1").Range("A1:K35").Copy
TgtWB.Sheets("1").Range("A1:K35").PasteSpecial (xlPasteValues)
TgtWB.Sheets("1").Range("A1:K35").PasteSpecial (xlPasteFormats)
Error gets caught on both PasteSpecial Values and Formats. I also tried to using:
SrcWB.Worksheets("1").Range("A1:K35").Value = TgtWB.Sheets("1").Range("A1:K35")
Above method didn't create any errors, however no values were transferred to the target workbook.
I've chewed on this most of this afternoon and would appreciate any help!
Here's the full code:
Sub CopySch()
Dim sh As Worksheet
Dim TgtWB As Workbook
Dim SrcWB As Workbook
Application.EnableEvents = False
Application.ScreenUpdating = False
Set TgtWB = ThisWorkbook
FileToOpen = Application.GetOpenFilename(FILEFILTER:="Excel Workbooks (*.xls*),*.xls*", Title:="Please select a file")
If FileToOpen = False Then
MsgBox "No File Specified.", vbExclamation, "ERROR"
Exit Sub
Else
Set SrcWB = Workbooks.Open(FileToOpen, xlUpdateLinksNever, ReadOnly:=True)
SrcWB.Worksheets("1").Range("A1:K35").Copy
TgtWB.Sheets("1").Range("A1:K35").PasteSpecial (xlPasteValues)
TgtWB.Sheets("1").Range("A1:K35").PasteSpecial (xlPasteFormats)
End If
Application.EnableEvents = True
Application.ScreenUpdating = True
SrcWB.Close
End Sub

Goto the top of your module and add "Option Explicit".
Option Explicit
Sub CopySch()
Dim sh As Worksheet
Dim TgtWB As Workbook
Dim SrcWB As Workbook
...
It should solve your problem.
EDIT:
lets give another try with this code. i have tried the code it Works without error.
Option Explicit
Sub CopySch()
Dim sh As Worksheet
Dim TgtWB As Workbook
Dim SrcWB As Workbook
Dim FileToOpen As String
Application.EnableEvents = False
Application.ScreenUpdating = False
Set TgtWB = ThisWorkbook
FileToOpen = Application.GetOpenFilename(FILEFILTER:="Excel Workbooks (*.xls*),*.xls*", Title:="Please select a file")
If FileToOpen = "False" Then
MsgBox "No File Specified.", vbExclamation, "ERROR"
Exit Sub
Else
Set SrcWB = Workbooks.Open(FileToOpen, xlUpdateLinksNever, ReadOnly:=True)
SrcWB.Worksheets("1").Range("A1:K35").Copy
TgtWB.Sheets("1").Range("A1:K35").PasteSpecial (xlPasteValues)
TgtWB.Sheets("1").Range("A1:K35").PasteSpecial (xlPasteFormats)
End If
Application.EnableEvents = True
Application.ScreenUpdating = True
SrcWB.Close
End Sub