확장명 VBA가 없는 파일 이름
나는 VBA로 확장자 이름 없이 파일 이름을 얻어야 합니다.알고있어요ActiveWorkbook.Name
속성, 그러나 사용자가 Windows 속성을 가지고 있는 경우Hide extensions for known file types
꺼짐, 내 코드의 결과는 [이름]이 될 것입니다.내선번호].Windows 속성과 관계없이 워크북 이름만 반환하려면 어떻게 해야 합니까?
나는 짝수ActiveWorkbook.Application.Caption
하지만 이 숙박업소는 커스터마이즈할 수 없습니다.
여기에 제시된 답은 이미 제한된 상황에서 효과가 있을 수 있지만, 이에 대한 최선의 방법은 아닙니다.바퀴를 다시 만들지 마.Microsoft 스크립팅 런타임 라이브러리의 파일 시스템 개체에는 이미 이 작업을 수행할 수 있는 방법이 있습니다.GetBaseName이라고 합니다.파일 이름의 마침표를 그대로 처리합니다.
Public Sub Test()
Dim fso As New Scripting.FileSystemObject
Debug.Print fso.GetBaseName(ActiveWorkbook.Name)
End Sub
Public Sub Test2()
Dim fso As New Scripting.FileSystemObject
Debug.Print fso.GetBaseName("MyFile.something.txt")
End Sub
간단하지만 저에게는 잘 맞습니다.
FileName = ActiveWorkbook.Name
If InStr(FileName, ".") > 0 Then
FileName = Left(FileName, InStr(FileName, ".") - 1)
End If
제 생각에는 InStr과 Left보다 스플릿 기능을 사용하는 것이 더 우아해 보입니다.
Private Sub CommandButton2_Click()
Dim ThisFileName As String
Dim BaseFileName As String
Dim FileNameArray() As String
ThisFileName = ThisWorkbook.Name
FileNameArray = Split(ThisFileName, ".")
BaseFileName = FileNameArray(0)
MsgBox "Base file name is " & BaseFileName
End Sub
이렇게 하면 파일 형식을 마지막 문자에서 가져옵니다(따라서 파일 이름의 점과 관련된 문제를 방지할 수 있습니다).
Function getFileType(fn As String) As String
''get last instance of "." (full stop) in a filename then returns the part of the filename starting at that dot to the end
Dim strIndex As Integer
Dim x As Integer
Dim myChar As String
strIndex = Len(fn)
For x = 1 To Len(fn)
myChar = Mid(fn, strIndex, 1)
If myChar = "." Then
Exit For
End If
strIndex = strIndex - 1
Next x
getFileType = UCase(Mid(fn, strIndex, Len(fn) - x + 1))
함수 종료
당신은 언제든지 사용할 수 있습니다.Replace()
워크북의 이름에서 이 작업을 수행하고 있기 때문에 거의 확실하게 끝날 것입니다..xlsm
VBA를 사용함으로써.
예제에 따라 Active Workbook 사용:
Replace(Application.ActiveWorkbook.Name, ".xlsm", "")
이 워크북 사용:
Replace(Application.ThisWorkbook.Name, ".xlsm", "")
이 실은 최근에 저에게 많은 도움이 되었습니다.@RubberDuck으로 답변을 확장하기 위해 Microsoft 스크립팅 런타임 라이브러리의 파일 시스템 개체가 이미 있습니다.또한 아래와 같이 개체로 정의하면 VBA Tools > References에서 'Microsoft Scripting Runtime'을 활성화해야 하는 번거로움을 줄일 수 있습니다.
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
Debug.Print fso.GetBaseName(ActiveWorkbook.Name)
이렇게 하면 확장자 없이 활성 워크북의 이름이 반환됩니다.
다음과 같은 INSTRREV 기능을 사용하는 다른 방법이 있습니다.
Dim fname As String
fname = Left(ActiveWorkbook.Name, InStrRev(ActiveWorkbook.Name, ".") - 1)
MsgBox fname
둘 다 동일한 결과를 반환합니다.또한 위의 두 가지 방법 모두 파일 이름에 모든 전체 중지를 유지하고 마지막 전체 중지와 파일 확장자만 제거합니다.
자세한 내용은 워크북에서 확장을 제거하는 방법을 설명합니다.이제 다양한 확장자를 가지고 있습니다. 저장되지 않은 새로운 Book1에는 ext가 없습니다. 파일에 대해서도 동일하게 작동합니다.
Function WorkbookIsOpen(FWNa$, Optional AnyExt As Boolean = False) As Boolean
Dim wWB As Workbook, WBNa$, PD%
FWNa = Trim(FWNa)
If FWNa <> "" Then
For Each wWB In Workbooks
WBNa = wWB.Name
If AnyExt Then
PD = InStr(WBNa, ".")
If PD > 0 Then WBNa = Left(WBNa, PD - 1)
PD = InStr(FWNa, ".")
If PD > 0 Then FWNa = Left(FWNa, PD - 1)
'
' the alternative of using split.. see commented out below
' looks neater but takes a bit longer then the pair of instr and left
' VBA does about 800,000 of these small splits/sec
' and about 20,000,000 Instr Lefts per sec
' of course if not checking for other extensions they do not matter
' and to any reasonable program
' THIS DISCUSSIONOF TIME TAKEN DOES NOT MATTER
' IN doing about doing 2000 of this routine per sec
' WBNa = Split(WBNa, ".")(0)
'FWNa = Split(FWNa, ".")(0)
End If
If WBNa = FWNa Then
WorkbookIsOpen = True
Exit Function
End If
Next wWB
End If
End Function
저는 개인적으로 매크로를 사용합니다.xlsb를 실행하고 xlsm과 xlsx 파일 모두에서 실행하므로 내가 사용하는 David Metcalfe의 답변에 대한 변형은 다음과 같습니다.
딤워크북 As String
워크북 = 교체(응용 프로그램).활성 워크북입니다.이름, ".xlsx", ".pdf")
워크북 = 교체(응용 프로그램).활성 워크북입니다.이름, ".xlsm", ".pdf")
다음은 FSO를 사용하지 않으려는 경우의 해결책입니다.이전에도 비슷한 답변이 있었지만, 여기서는 확장자 없이 이름과 이름의 여러 점을 처리하기 위해 몇 가지 검사를 수행합니다.
Function getFileNameWithoutExtension(FullFileName As String)
Dim a() As String
Dim ext_len As Integer, name_len As Integer
If InStr(FullFileName, ".") = 0 Then
getFileNameWithoutExtension = FullFileName
Exit Function
End If
a = Split(ActiveWorkbook.Name, ".")
ext_len = Len(a(UBound(a))) 'extension length (last element of array)
name_len = Len(FullFileName) - ext_len - 1 'length of name without extension and a dot before it
getFileNameWithoutExtension = Left(FullFileName, name_len)
End Function
Sub test1() 'testing the function
MsgBox (getFileNameWithoutExtension("test.xls.xlsx")) ' -> test.xls
MsgBox (getFileNameWithoutExtension("test")) ' -> test
MsgBox (getFileNameWithoutExtension("test.xlsx")) ' -> test
End Sub
strTestString = Left(ThisWorkbook.Name, (InStrRev(ThisWorkbook.Name, ".", -1, vbTextCompare) - 1))
전체 크레딧: http://mariaevert.dk/vba/ ?p=credit
언급URL : https://stackoverflow.com/questions/27923926/file-name-without-extension-name-vba
'programing' 카테고리의 다른 글
16진수 색상 값에서 솔리드 색상 브러시 만들기 (0) | 2023.04.28 |
---|---|
원격 RDP에서 로컬 시스템으로 파일 복사 (0) | 2023.04.28 |
Apple 스타일 스크롤 막대 WPF (0) | 2023.04.28 |
Azure의 정적 콘텐츠(svg,woff,ttf)에 대한 404 (0) | 2023.04.28 |
Azure 스토리지 시작하기:블롭 대 테이블 대 SQL Azure (0) | 2023.04.28 |